【大型电商项目开发】ElasticSearch整合SpringBoot&ElasticSearch-Rest-Client-34

一:Elasticsearch-Rest-Client

1)9300:TCP
spring-data-elasticsearch:transport-api.jar;

  • springboot 版本不同, transport-api.jar 不同,不能适配 es 版本
  • 7.x 已经不建议使用,8 以后就要废弃
  • 不建议9300端口操作es

2)9200:HTTP(推荐使用9200端口操作es)

  • JestClient:非官方,更新慢
  • RestTemplate:模拟发 HTTP 请求,ES 很多操作需要自己封装,麻烦
  • HttpClient:同上
  • Elasticsearch-Rest-Client:官方 RestClient,封装了 ES 操作,API 层次分明,上手简单

结论:
最终选择 Elasticsearch-Rest-Client(elasticsearch-rest-high-level-client)

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

1.新建gulimail-search微服务

【大型电商项目开发】ElasticSearch整合SpringBoot&ElasticSearch-Rest-Client-34_第1张图片

2.导入es的rest-high-level-client的依赖

		>
            >org.elasticsearch.client>
            >elasticsearch-rest-high-level-client>
            >7.4.2>
        >

顺便将es的版本改为7.4.2

	>
        >1.8>
        >7.4.2>
    >

3.添加es的配置

1)在search包下新建config包,并且新建GulimailElasticSearchConfig配置文件
【大型电商项目开发】ElasticSearch整合SpringBoot&ElasticSearch-Rest-Client-34_第2张图片
2)添加@Configuration注解
3)引入common包

		>
            >com.sysg.gulimail>
            >gulimail-common>
            >0.0.1-SNAPSHOT>
        >

4)在application.properties添加配置

#应用名称
spring.application.name=gulimail-search
#注册发现中心地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

5)在主启动类添加@EnableDiscoveryClient注解,开启服务注册发现功能
6)编写config配置

@Configuration
public class GulimailElasticSearchConfig {
    @Bean
    public RestHighLevelClient esRestClient(){
        
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
        return client;
    }
}

给容器中注入一个RestHighLevelClient
7)在test中测试es

@SpringBootTest
@RunWith(SpringRunner.class)
public class GulimailSearchApplicationTests {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Test
    public void contextLoads() {
        System.out.println(restHighLevelClient);
    }
}

二:测试es的增删改查

1.配置ES安全头信息RequestOptions

作用:当所有请求访问es的时候,会带上请求头信息。此时通过RequestOptions对请求进行一些设置。给每个请求发送之前构建一些授权信息,带上token令牌

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();
}

2.测试存储数据到es

   /**
     * 测试存储数据到es
     */
    @Test
    public void indexData() throws IOException {
        //users-需要保存的索引名称
        IndexRequest indexRequest = new IndexRequest("users");
        //设置保存数据的主键
        indexRequest.id("1");
        //添加需要保存的数据
        User user = new User();
        user.setAge(18);
        user.setUserName("sysg");
        user.setGender("男");
          //将user对象转化为json字符串
        String toJSONString = JSON.toJSONString(user);
        indexRequest.source(toJSONString, XContentType.JSON);
        //使用客户端执行保存操作
        IndexResponse index = client.index(indexRequest, GulimailElasticSearchConfig.COMMON_OPTIONS);
        //响应数据
        System.out.println(index);
    }
    @Data
    class User{
        private String userName;
        private String gender;
        private Integer age;
    }

1)首先去kibana中查看user索引
【大型电商项目开发】ElasticSearch整合SpringBoot&ElasticSearch-Rest-Client-34_第3张图片
2)在测试类执行保存方法
在这里插入图片描述
【大型电商项目开发】ElasticSearch整合SpringBoot&ElasticSearch-Rest-Client-34_第4张图片
此时就有数据了!!!
注:更新数据也可以,当主键相同时,就会替换之前的数据!!!!

三:ES完成复杂检索

/**
     * 测试检索数据
     */
    @Test
    public void searchData() throws IOException {
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定检索的索引
        searchRequest.indices("bank");
        //指定检索条件,dsl。此方法需要传入searchSourceBuilder对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();s
        //1.1)构建检索条件
        //查询条件
        sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
        //聚合条件
        //1.2)按照年龄的值进行聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        sourceBuilder.aggregation(ageAgg);
        //1.3)计算平均薪资
        AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
        sourceBuilder.aggregation(balanceAvg);
        searchRequest.source(sourceBuilder);
        //2.执行检索
        SearchResponse searchResponse = client.search(searchRequest, GulimailElasticSearchConfig.COMMON_OPTIONS);
        //3.分析结果
        /*Map map = JSON.parseObject(searchResponse.toString(), Map.class);*/
        //3.1)获取到所有查询到的数据
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            String string = hit.getSourceAsString();
            JSONObject object = JSON.parseObject(string);
            System.out.println(object);
        }
        //3.2)获取这次检索到的分析信息
        Aggregations aggregations = searchResponse.getAggregations();
        /*for (Aggregation aggregation : aggregations.asList()) {
            String name = aggregation.getName();
            System.out.println("当前聚合名字:"+name);
        }*/
        Terms ageAgg1 = aggregations.get("ageAgg");
        
    }

你可能感兴趣的:(elasticsearch,spring,boot,java)