Elaticsearch简称为es, es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用 Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通过简单的RESTful API来隐藏Lucene的复杂性,从而让全文搜索变得简单。 据国际权威的数据库产品评测机构DB Engines的统计,在2016年1月,ElasticSearch已超过Solr等,成 为排名第一的搜索引擎类应用。
此为原生依赖
注意:elasticsearch的依赖需要与下载的ES版本一致,本次使用的7.6.2的!!!
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>7.6.2version>
dependency>
不过在SpringBoot中无需如此,直接导入
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
也有最简单的方式,在创建SpringBoot项目时直接勾选依赖组件。
导入后的项目依赖pom.xml文件为如下,同学顺便导入jackJson方便传输数据!!
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.1.RELEASEversion>
<relativePath/>
parent>
<groupId>top.hcodegroupId>
<artifactId>hcode-es-api-1artifactId>
<version>0.0.1-SNAPSHOTversion>
<name>hcode-es-api-1name>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
<elasticsearch.version>7.6.2elasticsearch.version>
properties>
<dependencies>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.62version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
然后编写配置文件,注入到Spring容器中
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(
//有几个集群写几个!!
new HttpHost("127.0.0.1",9200,"http"),
new HttpHost("127.0.0.1",9100,"http")
)
);
}
}
注入RestHighLevelClient
@Autowired
private RestHighLevelClient restHighLevelClient;
创建索引
void createIndex() throws IOException {
//创建索引请求
CreateIndexRequest index = new CreateIndexRequest("hcode_index"); //hcode_index为索引名
//执行请求,获得响应
CreateIndexResponse response = restHighLevelClient.indices().create(index, RequestOptions.DEFAULT);
System.out.println(response);
}
判断索引是否存在
void ExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("hcode_index");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
删除索引
void DeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("hcode_index");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged()); //为true表示删除成功
}
添加文档
void AddDocument() throws IOException {
User user = new User("hcode", 22);
//创建索引请求
IndexRequest request = new IndexRequest("hcode_index");
//设置规则 例如相当于 PUT /hcode_index/_doc/1 命令
request.id("1").timeout(TimeValue.timeValueSeconds(1));//设置id,1秒超时
request.timeout("1s");
// 数据转换成json 放入请求
request.source(JSON.toJSONString(user), XContentType.JSON);
//将请求发出去,获取响应结果
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.status()); // 返回当前操作的类型:CREATE
System.out.println(indexResponse.toString()); //响应内容
}
判断文档是否存在
void IsExists() throws IOException {
GetRequest getRequest = new GetRequest("hcode_index", "1");
// 不获取返回的_source 的上下文,会提高速度
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
获取文档的信息 GET /hcode_index/_doc/1
//相当于 GET /hcode_index/_doc/1
void getDocument() throws IOException {
GetRequest getRequest = new GetRequest("hcode_index", "1");
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString()); //获取文档的内容
}
更新文档信息
void updateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("hcode_index", "1");
request.timeout("1s");
User user = new User("hzh", 18);
request.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.status()); //成功返回 OK
System.out.println(response.toString());
}
删除文档信息
void deleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("hcode_index", "1");
request.timeout("1s");
DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status()); //成功返回 OK
System.out.println(response.toString());
}
批量操作
void BulkRequest() throws IOException {
BulkRequest request = new BulkRequest();
request.timeout("10s");
ArrayList<Object> list = new ArrayList<>();
list.add(new User("hcode", 1));
list.add(new User("himit", 2));
list.add(new User("youth", 3));
//批量请求,批量更新,删除都差不多!!!不设置id就会自动生成随机id,演示为批量插入
for (int i = 0; i < list.size(); i++) {
request.add(new IndexRequest("hcode_index")
.id("" + (i + 1))
.source(JSON.toJSONString(list.get(i)), XContentType.JSON));
}
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.hasFailures());//是否失败,false表示成功,true表示失败
}
搜索查询+高亮
void Query() throws IOException {
SearchRequest request = new SearchRequest();
//创建查询条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 使用QueryBuilders工具,精确查询term
//QueryBuilders.matchAllQuery() 匹配所有
TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "hcode");
//配置高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name"); //绑定属性
highlightBuilder.requireFieldMatch(false); //关闭多个高亮,只显示一个高亮
highlightBuilder.preTags(""
); //设置前缀
highlightBuilder.postTags(""); //设置后缀
sourceBuilder.highlighter(highlightBuilder);
sourceBuilder.query(termQuery);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
request.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//获取结果对象
SearchHits hits = response.getHits();
System.out.println(JSON.toJSONString(hits));
for (SearchHit searchHit : hits) {
//获取高亮的html
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField name = highlightFields.get("name");
//替换原有的字段
Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
if (name != null) {
Text[] fragments = name.fragments();
String light_name = "";
for (Text fragment : fragments) {
light_name += fragment;
}
sourceAsMap.put("name", light_name); //进行替换
}
System.out.println(searchHit.getSourceAsMap());
}
}