Elasticsearch-Rest-Client:官方RestClient,封装了 ES 操作,API层次分明,上手简单
最终选择:Elasticsearch-Rest-Client
Java REST Client

创建ES微服务#

————————————————————————-
创建好搜索服务后,导入 ES依赖包
gulimall-search/pom.xml导入ES包:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.16.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.atguigu.gulimall</groupId>
  12. <artifactId>gulimall-search</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>gulimall-search</name>
  15. <description>检索服务</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <elasticsearch>7.9.3</elasticsearch>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>com.atguigu.gulimall</groupId>
  23. <artifactId>gulimall-common</artifactId>
  24. <version>0.0.1-SNAPSHOT</version>
  25. </dependency>
  26. <!-- //引入elassearch高级版本-->
  27. <dependency>
  28. <groupId>org.elasticsearch.client</groupId>
  29. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  30. <version>7.4.2</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.elasticsearch</groupId>
  34. <artifactId>elasticsearch</artifactId>
  35. <version>7.4.2</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.elasticsearch.client</groupId>
  39. <artifactId>elasticsearch-rest-client</artifactId>
  40. <version>7.4.2</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-web</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <plugins>
  54. <plugin>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-maven-plugin</artifactId>
  57. </plugin>
  58. </plugins>
  59. </build>
  60. </project>

配置注册服务与发现

spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.application.name=gulimall-search

启动类

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class GulimallSearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallSearchApplication.class, args);
    }

}

配置类(本地elasticsearch,即Windows版本)

参考https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low-usage-requests.html#java-rest-low-usage-request-options

/**
 * @author : hzyao
 * @date : 17:56 2021/3/11
 */
@Configuration
public class GulimallElasticsearchConfig {


    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    //    @Bean
//    public void esrestClient(){
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost("127.0.0.1",9200,"http")
//
//                ));
//        return;
//    }
    @Bean
    public  RestHighLevelClient restHighLevelClient(){
        RestClientBuilder builder = null;
        builder = RestClient.builder(new HttpHost("127.0.0.1",9200,"http"));
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}

测试保存

package com.atguigu.gulimall.search;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.search.config.GulimallElasticsearchConfig;
import javafx.scene.control.IndexRange;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.IOException;


@SpringBootTest
@RunWith(SpringRunner.class)
public class GulimallSearchApplicationTests {

    @Resource
    private RestHighLevelClient client;

    @Test
    public  void indexData() throws IOException {
        IndexRequest indexRequest = new IndexRequest("users");
        indexRequest.id("1");
        User user = new User();
        user.setUserName("zhangsan");
        user.setAge(18);
        user.setGender("男");

        String JsonString = JSON.toJSONString(user);
        indexRequest.source(JsonString, XContentType.JSON);//要保存的内容
        //执行操作
        IndexResponse response = client.index(indexRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        //提取有用的
        System.out.println(response);

    }

    @Data
    class User{
        private String userName;
        private String gender;
        private Integer age;
    }
    @Test
   public  void contextLoads() {
        System.out.println(client);
    }

}

image.png
image.png

复杂查询

参考https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html

  @Test
    public  void searchData() throws IOException {
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("bank");
        //指定DSL,检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构造检索条件
        searchSourceBuilder.query(QueryBuilders.matchQuery("adress","mill"));

         //聚合检索
        //1).年龄分布聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(ageAgg);
        //2)计算平均薪资
        AvgAggregationBuilder balance = AggregationBuilders.avg("balanceAvg").field("balance");
        searchSourceBuilder.aggregation(balance);

        System.out.println("检索条件:"+searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        //2.执行检索
        SearchResponse searchResponse = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);

        //分析结果
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
       for (SearchHit hit : searchHits){
           String string = hit.getSourceAsString();
           Account account = JSON.parseObject(string, Account.class);
           System.out.println("Acount:"+account);
       }
       //分析检索聚合信息
        Aggregations aggregations = searchResponse.getAggregations();
//        for (Aggregation aggregation : aggregations.asList()) {
//            aggregation.getName();
//        }
        Terms ageAgg1 = aggregations.get("ageAgg");
        for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄"+keyAsString);
        }
        System.out.println("结果:"+searchResponse.toString());
    }

结果JSON

{
  "query": {
    "match": {
      "adress": {
        "query": "mill",
        "operator": "OR",
        "prefix_length": 0,
        "max_expansions": 50,
        "fuzzy_transpositions": true,
        "lenient": false,
        "zero_terms_query": "NONE",
        "auto_generate_synonyms_phrase_query": true,
        "boost": 1
      }
    }
  },
  "aggregations": {
    "ageAgg": {
      "terms": {
        "field": "age",
        "size": 10,
        "min_doc_count": 1,
        "shard_min_doc_count": 0,
        "show_term_doc_count_error": false,
        "order": [
          {
            "_count": "desc"
          },
          {
            "_key": "asc"
          }
        ]
      }
    },
    "balanceAvg": {
      "avg": {
        "field": "balance"
      }
    }
  }
}