当前位置:   article > 正文

java 操作elasticsearch详细总结_java集成elasticsearch

java集成elasticsearch

一、前言

本篇将介绍如何使用java完成对es的操作,这也是实际开发中将要涉及到的。

二、java操作es的常用模式

目前,开发中使用java操作es,不管是框架集成,还是纯粹的使用es的api,主要通过下面两种方式:

rest-api,主流的像 RestHighLevelClient ;

与springboot集成时的jpa操作,主要是 ElasticsearchRepository 相关的api;

上面两种模式的api在开发中都可以方便的使用,相比之下,RestHighLevelClient相关的api灵活性更高,而ElasticsearchRepository 底层做了较多的封装,学习和使用的成本更低,上手更快。

接下来将对上面的两种操作模式做一个详细的总结,本篇所述的es基于7.6.2版本,配合的kibana也为7.6.2版本。

三、rest-api 操作

1、前置准备

导入依赖

导入核心依赖,主要是es的rest依赖,其他的可以根据自己的需要导入;

<dependencies><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.11.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.11.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.8.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-jcl</artifactId><version>2.11.2</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.6.2</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.6.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>

es连接测试

为了确保后续的所有实验能够正常进行,建议先通过下面的程序测试下是否能够连接es服务;

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RestClient;
  3. import org.elasticsearch.client.RestHighLevelClient;
  4. import java.io.IOException;
  5. publicclassEsClientTest{
  6. publicstaticvoidmain(String[] args)throws IOException {
  7. RestHighLevelClient esClient = new RestHighLevelClient(
  8. RestClient.builder(new HttpHost("IP",9200,"http"))
  9. );
  10. System.out.println("success");
  11. esClient.close();
  12. }
  13. }

运行上面的代码,出现下面的效果说明连接成功

2、索引相关操作api的使用

为了减少连接相关的编码,我们将es的client提出到全局的静态变量中,其他方法中就可以直接引用了

  1. publicstatic RestHighLevelClient esClient;
  2. static {
  3. esClient = new RestHighLevelClient(
  4. RestClient.builder(new HttpHost("IP", 9200, "http"))
  5. );
  6. }

2.1 创建索引

  1. /**
  2. * 创建索引
  3. * @throws IOException
  4. */publicstaticvoidcreateIndex()throws IOException {
  5. CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
  6. CreateIndexResponse indexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
  7. boolean acknowledged = indexResponse.isAcknowledged();
  8. System.out.println("索引创建状态:" + acknowledged);
  9. }

main方法中调用方法即可

  1. publicstaticvoidmain(String[] args)throws IOException {
  2. System.out.println("connect success");
  3. createIndex();
  4. esClient.close();
  5. }

运行main创建索引

通过kibana查询确认索引是否创建成功

2.2 获取索引

  1. /**
  2. * 索引信息查询
  3. * @throws IOException
  4. */publicstaticvoidgetIndex()throws IOException {
  5. GetIndexRequest getIndexRequest = new GetIndexRequest("user");
  6. GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
  7. System.out.println(getIndexResponse.getAliases());
  8. System.out.println(getIndexResponse.getMappings());
  9. System.out.println(getIndexResponse.getSettings());
  10. }

2.3 删除索引

  1. /**
  2. * 删除索引
  3. * @throws IOException
  4. */publicstaticvoiddeleteIndex() throws IOException {
  5. DeleteIndexRequest getIndexRequest = new DeleteIndexRequest("user");
  6. AcknowledgedResponse delete = esClient.indices().delete(getIndexRequest, RequestOptions.DEFAULT);
  7. System.out.println("索引删除状态:" + delete.isAcknowledged());
  8. }

3、文档常用操作api的使用

在实际开发过程中,对于文档的操作更为的频繁,接下来演示与es文档相关的操作api。

前置准备

  1. publicstatic ObjectMapper objectMapper = new ObjectMapper();
  2. publicstatic RestHighLevelClient esClient;
  3. static {
  4. esClient = new RestHighLevelClient(
  5. RestClient.builder(new HttpHost("IP", 9200, "http"))
  6. );
  7. }

用于测试使用的对象

  1. publicclassUser {private String name;
  2. private String sex;
  3. private Integer age;
  4. private Integer salary;
  5. publicUser(){
  6. }
  7. publicUser(String name, String sex, Integer age, Integer salary){
  8. this.name = name;
  9. this.sex = sex;
  10. this.age = age;
  11. this.salary = salary;
  12. }
  13. public Integer getSalary(){
  14. return salary;
  15. }
  16. publicvoidsetSalary(Integer salary){
  17. this.salary = salary;
  18. }
  19. public String getName(){
  20. return name;
  21. }
  22. publicvoidsetName(String name){
  23. this.name = name;
  24. }
  25. public String getSex(){
  26. return sex;
  27. }
  28. publicvoidsetSex(String sex){
  29. this.sex = sex;
  30. }
  31. public Integer getAge(){
  32. return age;
  33. }
  34. publicvoidsetAge(Integer age){
  35. this.age = age;
  36. }
  37. }

3.1 索引添加文档

注意:实际开发中,user对象应该作为参数传入【可以基于此做进一步的封装】
  1. /**
  2. * 添加数据
  3. * @throws Exception
  4. */publicstaticvoidadd()throws Exception{
  5. IndexRequest indexRequest = new IndexRequest();
  6. indexRequest.index("user").id("1008");
  7. User user = new User();
  8. user.setName("孙二娘");
  9. user.setAge(23);
  10. user.setSex("女");
  11. user.setSalary(7000);
  12. String userData = objectMapper.writeValueAsString(user);
  13. indexRequest.source(userData,XContentType.JSON);
  14. //插入数据
  15. IndexResponse response = esClient.index(indexRequest, RequestOptions.DEFAULT);
  16. System.out.println(response.status());
  17. System.out.println(response.getResult());
  18. }

在main方法调用执行下该方法

  1. publicstaticvoidmain(String[] args)throws Exception {
  2. add();
  3. esClient.close();
  4. }

可以通过kibana查询检查下数据是否添加成功

3.2 修改文档

  1. /**
  2. * 修改数据
  3. * @throws Exception
  4. */publicstaticvoidupdate()throws Exception{
  5. UpdateRequest request = new UpdateRequest();
  6. request.index("user").id("1008");
  7. request.doc(XContentType.JSON,"name","母夜叉");
  8. //插入数据
  9. UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
  10. System.out.println(response.getResult());
  11. }

3.3 删除文档

  1. /**
  2. * 删除
  3. * @throws Exception
  4. */publicstaticvoiddelete() throws Exception{
  5. DeleteRequest request = new DeleteRequest();
  6. request.index("user").id("1008");
  7. //插入数据
  8. DeleteResponse delete = esClient.delete(request, RequestOptions.DEFAULT);
  9. System.out.println(delete.getResult());
  10. }

3.4 批量添加文档

有些情况下,单条插入效率太低,可以使用es的批量插入功能一次性添加多条数据

  1. /**
  2. * 批量添加
  3. * @throws Exception
  4. */
  5. public staticvoid batchInsert() throws Exception{
  6. BulkRequest bulkRequest = new BulkRequest();
  7. User user1 = new User("关羽","男",33,5500);
  8. String userData1 = objectMapper.writeValueAsString(user1);
  9. IndexRequest indexRequest1 = new IndexRequest().index("user").id("1002").source(userData1, XContentType.JSON);
  10. bulkRequest.add(indexRequest1);
  11. User user2 = new User("黄忠","男",50,8000);
  12. String userData2 = objectMapper.writeValueAsString(user2);
  13. IndexRequest indexRequest2 = new IndexRequest().index("user").id("1003").source(userData2, XContentType.JSON);
  14. bulkRequest.add(indexRequest2);
  15. User user3 = new User("黄忠2","男",49,10000);
  16. String userData3 = objectMapper.writeValueAsString(user3);
  17. IndexRequest indexRequest3 = new IndexRequest().index("user").id("1004").source(userData3, XContentType.JSON);
  18. bulkRequest.add(indexRequest3);
  19. User user4 = new User("赵云","男",33,12000);
  20. String userData4 = objectMapper.writeValueAsString(user4);
  21. IndexRequest indexRequest4 = new IndexRequest().index("user").id("1005").source(userData4, XContentType.JSON);
  22. bulkRequest.add(indexRequest4);
  23. User user5 = new User("马超","男",38,20000);
  24. String userData5 = objectMapper.writeValueAsString(user5);
  25. IndexRequest indexRequest5 = new IndexRequest().index("user").id("1006").source(userData5, XContentType.JSON);
  26. bulkRequest.add(indexRequest5);
  27. User user6 = new User("关羽","男",41,27000);
  28. String userData6 = objectMapper.writeValueAsString(user6);
  29. IndexRequest indexRequest6 = new IndexRequest().index("user").id("1007").source(userData6, XContentType.JSON);
  30. bulkRequest.add(indexRequest6);
  31. BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
  32. System.out.println(bulkResponse.status());
  33. System.out.println(bulkResponse.getItems());
  34. }

3.5 批量删除

可以通过批量操作一次性删除多条数据

  1. /**
  2. * 批量删除
  3. * @throws Exception
  4. */publicstaticvoidbatchDelete()throws Exception{
  5. BulkRequest bulkRequest = new BulkRequest();
  6. DeleteRequest indexRequest1 = new DeleteRequest().index("user").id("1002");
  7. DeleteRequest indexRequest2 = new DeleteRequest().index("user").id("1003");
  8. DeleteRequest indexRequest3 = new DeleteRequest().index("user").id("1004");
  9. DeleteRequest indexRequest4 = new DeleteRequest().index("user").id("1005");
  10. DeleteRequest indexRequest5 = new DeleteRequest().index("user").id("1006");
  11. DeleteRequest indexRequest6 = new DeleteRequest().index("user").id("1007");
  12. bulkRequest.add(indexRequest1);
  13. bulkRequest.add(indexRequest2);
  14. bulkRequest.add(indexRequest3);
  15. bulkRequest.add(indexRequest4);
  16. bulkRequest.add(indexRequest5);
  17. bulkRequest.add(indexRequest6);
  18. BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
  19. System.out.println(bulkResponse.status());
  20. System.out.println(bulkResponse.getItems());
  21. }

4、文档搜索相关api的使用

我们知道es最强大的功能就是文档检索了,接下来演示下与es文档查询相关的常用API的操作;

4.1 查询某个索引下的所有数据

  1. /**
  2. * 查询某个索引下的所有数据
  3. * @throws Exception
  4. */publicstaticvoidsearchIndexAll()throws Exception{
  5. SearchRequest request = new SearchRequest();
  6. request.indices("user");
  7. // 索引中的全部数据查询
  8. SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
  9. request.source(query);
  10. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  11. SearchHits hits = response.getHits();
  12. for (SearchHit searchHit : hits){
  13. System.out.println(searchHit.getSourceAsString());
  14. }
  15. }

执行一下对该方法的调用

这个效果和在kibana中下面的操作效果是一样的

4.2 批量查询多条数据

针对那种需要一次性查出多条数据的场景可以考虑使用

  1. MultiGetRequest multiGetRequest = new MultiGetRequest();
  2. multiGetRequest.add("user", "1002");
  3. multiGetRequest.add("user", "1003");
  4. MultiGetResponse responses = esClient
  5. .mget(multiGetRequest, RequestOptions.DEFAULT);
  6. Iterator<MultiGetItemResponse> iterator = responses.iterator();
  7. while (iterator.hasNext()){
  8. MultiGetItemResponse next = iterator.next();
  9. System.out.println(next.getResponse().getSourceAsString());
  10. }

4.3 根据条件精准查询

根据性别查询,有点类似于mysql 中的 where sex='女' 这样的效果

  1. TermQueryBuilder ageQueryBuilder = QueryBuilders.termQuery("sex", "女");
  2. SearchSourceBuilder query = new SearchSourceBuilder().query(ageQueryBuilder);
  3. request.source(query);
  4. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  5. System.out.println(response.getHits().getHits());
  6. System.out.println(response.getHits().getTotalHits());
  7. SearchHits hits = response.getHits();
  8. for (SearchHit searchHit : hits){
  9. System.out.println(searchHit.getSourceAsString());
  10. }

4.4 分页查询

考察from + size的使用

  1. SearchSourceBuilder sourceBuilder = new
  2. SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
  3. sourceBuilder.from(0).size(3);
  4. request.source(sourceBuilder);
  5. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  6. System.out.println(response.getHits().getHits());
  7. System.out.println(response.getHits().getTotalHits());
  8. SearchHits hits = response.getHits();
  9. for (SearchHit searchHit : hits){
  10. System.out.println(searchHit.getSourceAsString());
  11. }

4.5 查询结果按照某个字段进行排序

将查询结果按照age进行排序

  1. SearchSourceBuilder sourceBuilder = new
  2. SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
  3. sourceBuilder.sort("age",SortOrder.ASC);
  4. request.source(sourceBuilder);
  5. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  6. System.out.println(response.getHits().getHits());
  7. System.out.println(response.getHits().getTotalHits());
  8. SearchHits hits = response.getHits();
  9. for (SearchHit searchHit : hits){
  10. System.out.println(searchHit.getSourceAsString());
  11. }

4.6 查询结果过滤某些字段

类似于mysql中只查询某个表的部分字段

  1. SearchSourceBuilder sourceBuilder = new
  2. SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
  3. request.source(sourceBuilder);
  4. String[] includes = {"name","sex"};
  5. String[] excludes = {"age"};
  6. sourceBuilder.fetchSource(includes,excludes);
  7. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  8. System.out.println(response.getHits().getHits());
  9. System.out.println(response.getHits().getTotalHits());
  10. SearchHits hits = response.getHits();
  11. for (SearchHit searchHit : hits){
  12. System.out.println(searchHit.getSourceAsString());
  13. }

4.7 多条件查询

es可以像mysql那样组合多个条件进行查询,考察对BoolQuery的使用,如下:查询性别为难男,年龄在35到45之间的用户;

  1. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  2. boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
  3. boolQueryBuilder.must(QueryBuilders.rangeQuery("age").lt(45).gt(35));
  4. sourceBuilder.query(boolQueryBuilder);
  5. request.source(sourceBuilder);
  6. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  7. System.out.println(response.getHits().getHits());
  8. System.out.println(response.getHits().getTotalHits());
  9. SearchHits hits = response.getHits();
  10. for (SearchHit searchHit : hits){
  11. System.out.println(searchHit.getSourceAsString());
  12. }

4.8 范围查询

  1. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  2. RangeQueryBuilder rangeQueryBuilder =
  3. QueryBuilders.rangeQuery("age").gte(35).lte(45);
  4. sourceBuilder.query(rangeQueryBuilder);
  5. request.source(sourceBuilder);
  6. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  7. System.out.println(response.getHits().getHits());
  8. System.out.println(response.getHits().getTotalHits());
  9. SearchHits hits = response.getHits();
  10. for (SearchHit searchHit : hits){
  11. System.out.println(searchHit.getSourceAsString());
  12. }

4.9 模糊查询

  1. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  2. FuzzyQueryBuilder fuzzyQueryBuilder =
  3. QueryBuilders.fuzzyQuery("name", "黄忠")
  4. .fuzziness(Fuzziness.ONE);
  5. sourceBuilder.query(fuzzyQueryBuilder);
  6. request.source(sourceBuilder);
  7. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  8. System.out.println(response.getHits().getHits());
  9. System.out.println(response.getHits().getTotalHits());
  10. SearchHits hits = response.getHits();
  11. for (SearchHit searchHit : hits){
  12. System.out.println(searchHit.getSourceAsString());
  13. }

4.10 高亮查询

  1. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  2. TermQueryBuilder ageQueryBuilder = QueryBuilders.termQuery("age", 33);
  3. HighlightBuilder highlightBuilder = new HighlightBuilder();
  4. highlightBuilder.preTags("<font color='red'>");
  5. highlightBuilder.postTags("</font>");
  6. highlightBuilder.field("name");
  7. sourceBuilder.highlighter(highlightBuilder);
  8. sourceBuilder.query(ageQueryBuilder);
  9. request.source(sourceBuilder);
  10. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  11. System.out.println(response.getHits().getHits());
  12. System.out.println(response.getHits().getTotalHits());
  13. SearchHits hits = response.getHits();
  14. for (SearchHit searchHit : hits){
  15. System.out.println(searchHit.getSourceAsString());
  16. }

4.11 多字段查询multi_match

这个用法表示从多个字段中匹配某个关键字

  1. SearchSourceBuilder builder = new SearchSourceBuilder();
  2. MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery("黄忠","name", "sex");
  3. multiMatchQuery.operator(Operator.OR);
  4. builder.query(multiMatchQuery);
  5. request.source(builder);
  6. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  7. System.out.println(response.getHits().getHits());
  8. System.out.println(response.getHits().getTotalHits());
  9. SearchHits hits = response.getHits();
  10. for (SearchHit searchHit : hits){
  11. System.out.println(searchHit.getSourceAsString());
  12. }

4.12 聚合查询

  1. SearchSourceBuilder builder = new SearchSourceBuilder();
  2. AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
  3. builder.aggregation(aggregationBuilder);
  4. request.source(builder);
  5. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  6. System.out.println(response.getHits().getHits());
  7. System.out.println(response.getHits().getTotalHits());
  8. SearchHits hits = response.getHits();
  9. for (SearchHit searchHit : hits){
  10. System.out.println(searchHit.getSourceAsString());
  11. }

4.13 分组查询

  1. SearchSourceBuilder builder = new SearchSourceBuilder();
  2. AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
  3. builder.aggregation(aggregationBuilder);
  4. request.source(builder);
  5. SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
  6. System.out.println(response.getHits().getHits());
  7. System.out.println(response.getHits().getTotalHits());
  8. SearchHits hits = response.getHits();
  9. for (SearchHit searchHit : hits){
  10. System.out.println(searchHit.getSourceAsString());
  11. }

四、与springboot 整合

es提供了与spring,springboot快速整合的第三方SDK,接下来以spring-data为例进行说明;

spring-boot-starter-data-elasticsearch 与spring其他相关的jpa方式使用类似,封装了丰富的API接口,客户只需要继承其提供的接口,就能方便的使用内置的API

前置准备

本地创建一个maven工程

1、导入核心依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.6.RELEASE</version><relativePath/></parent><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-test</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId></dependency></dependencies>

2、核心配置文件

  1. # es 服务地址
  2. elasticsearch.host=IP
  3. # es 服务端口
  4. elasticsearch.port=9200
  5. # 配置日志级别,开启 debug 日志
  6. logging.level.com.congge=debug

整合过程

1、创建一个实体类

该实体类属于连接es文档与客户端的一个中间转换层,使用过jpa或者mybatis-plus的同学对这个应该不陌生;

  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import lombok.ToString;
  5. import org.springframework.data.annotation.Id;
  6. import org.springframework.data.elasticsearch.annotations.Document;
  7. import org.springframework.data.elasticsearch.annotations.Field;
  8. import org.springframework.data.elasticsearch.annotations.FieldType;
  9. @Data@NoArgsConstructor@AllArgsConstructor@ToString@Document(indexName = "shopping", shards = 3, replicas = 1)
  10. publicclassProduct{
  11. //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"@Idprivate Long id;//商品唯一标识/**
  12. * type : 字段数据类型
  13. * analyzer : 分词器类型
  14. * index : 是否索引(默认:true)
  15. * Keyword : 短语,不进行分词
  16. */@Field(type = FieldType.Text, analyzer = "ik_max_word")
  17. private String title;//商品名称@Field(type = FieldType.Keyword)
  18. private String category;//分类名称@Field(type = FieldType.Double)
  19. private Double price;//商品价格@Field(type = FieldType.Keyword, index = false)
  20. private String images;//图片地址
  21. }

2、提供一个接口,继承ElasticsearchRepository

  1. importcom.congge.entity.Product;
  2. importorg.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  3. importorg.springframework.stereotype.Repository;
  4. @Repository
  5. public interface ProductDao extends ElasticsearchRepository<Product, Long>{
  6. }

3、核心配置类

  1. import lombok.Data;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestClientBuilder;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.springframework.boot.context.properties.ConfigurationProperties;
  7. import org.springframework.context.annotation.Configuration;
  8. //import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;@ConfigurationProperties(prefix = "elasticsearch")
  9. @Configuration@DatapublicclassEsConfigextendscom.congge.config.AbstractElasticsearchConfiguration{
  10. private String host ;
  11. private Integer port ;
  12. //重写父类方法@Overridepublic RestHighLevelClient elasticsearchClient(){
  13. RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
  14. RestHighLevelClient restHighLevelClient = new
  15. RestHighLevelClient(builder);
  16. return restHighLevelClient;
  17. }
  18. }
  1. import org.elasticsearch.client.RestHighLevelClient;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
  4. import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
  5. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  6. import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
  7. publicabstractclassAbstractElasticsearchConfigurationextendsElasticsearchConfigurationSupport{
  8. //需重写本方法publicabstract RestHighLevelClient elasticsearchClient();
  9. @Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
  10. public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter){
  11. returnnew ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
  12. }
  13. }

模拟测试

接下来通过junit的方式进行测试

1、索引相关的操作测试

  1. import com.congge.entity.Product;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. @RunWith(SpringRunner.class)
  9. @SpringBootTestpublicclassEsIndexTest{
  10. //注入 ElasticsearchRestTemplate@Autowiredprivate ElasticsearchRestTemplate elasticsearchRestTemplate;
  11. //创建索引并增加映射配置@TestpublicvoidcreateIndex(){
  12. //创建索引,系统初始化会自动创建索引
  13. System.out.println("创建索引");
  14. }
  15. @TestpublicvoiddeleteIndex(){
  16. //创建索引,系统初始化会自动创建索引boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
  17. System.out.println("删除索引 = " + flg);
  18. }
  19. }

基于spring-data的方式,在工程启动的时候,会自动读取实体类相关的注解,自动完成索引的创建,运行下创建索引的测试方法;

然后去到kibana上面确认下是否创建成功;

2、文档相关的操作测试

该测试类中列举了常用的增删改查操作

  1. import com.congge.dao.ProductDao;
  2. import com.congge.entity.Product;
  3. import org.elasticsearch.index.query.QueryBuilders;
  4. import org.elasticsearch.index.query.TermQueryBuilder;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.data.domain.Page;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Sort;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. @RunWith(SpringRunner.class)
  16. @SpringBootTestpublicclassEsDocTest{
  17. @Autowiredprivate ProductDao productDao;
  18. /**
  19. * 新增
  20. */@Testpublicvoidsave(){
  21. Product product = new Product();
  22. product.setId(2L);
  23. product.setTitle("ipad mini");
  24. product.setCategory("ipad");
  25. product.setPrice(1998.0);
  26. product.setImages("http://ipad.jpg");
  27. productDao.save(product);
  28. }
  29. //修改@Testpublicvoidupdate(){
  30. Product product = new Product();
  31. product.setId(2L);
  32. product.setTitle("iphone");
  33. product.setCategory("mobile");
  34. product.setPrice(6999.0);
  35. product.setImages("http://www.phone.jpg");
  36. productDao.save(product);
  37. }
  38. //根据 id 查询@TestpublicvoidfindById(){
  39. Product product = productDao.findById(2L).get();
  40. System.out.println(product);
  41. }
  42. //查询所有@TestpublicvoidfindAll(){
  43. Iterable<Product> products = productDao.findAll();
  44. for (Product product : products) {
  45. System.out.println(product);
  46. }
  47. }
  48. //删除@Testpublicvoiddelete(){
  49. Product product = new Product();
  50. product.setId(2L);
  51. productDao.delete(product);
  52. }
  53. //批量新增@TestpublicvoidsaveAll(){
  54. List<Product> productList = new ArrayList<>();
  55. for (int i = 0; i < 10; i++) {
  56. Product product = new Product();
  57. product.setId(Long.valueOf(i));
  58. product.setTitle("iphone" + i);
  59. product.setCategory("mobile");
  60. product.setPrice(5999.0 + i);
  61. product.setImages("http://www.phone.jpg");
  62. productList.add(product);
  63. }
  64. productDao.saveAll(productList);
  65. }
  66. //分页查询@TestpublicvoidfindByPageable(){
  67. //设置排序(排序方式,正序还是倒序,排序的 id)
  68. Sort sort = Sort.by(Sort.Direction.DESC,"id");
  69. int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页int pageSize = 5;//每页显示多少条//设置查询分页
  70. PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
  71. //分页查询
  72. Page<Product> productPage = productDao.findAll(pageRequest);
  73. for (Product Product : productPage.getContent()) {
  74. System.out.println(Product);
  75. }
  76. }
  77. /**
  78. * term 查询
  79. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
  80. */@TestpublicvoidtermQuery(){
  81. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "iphone");
  82. Iterable<Product> products = productDao.search(termQueryBuilder);
  83. for (Product product : products) {
  84. System.out.println(product);
  85. }
  86. }
  87. /**
  88. * term 查询加分页
  89. */@TestpublicvoidtermQueryByPage(){
  90. int currentPage= 0 ;
  91. int pageSize = 5;
  92. //设置查询分页
  93. PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
  94. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "phone");
  95. Iterable<Product> products =
  96. productDao.search(termQueryBuilder,pageRequest);
  97. for (Product product : products) {
  98. System.out.println(product);
  99. }
  100. }
  101. }

测试其中批量新增的方法

更多丰富的API接口的使用有兴趣的同学可以基于此继续深入的研究学习。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/68049
推荐阅读
相关标签
  

闽ICP备14008679号