ES检索
1、Java操作ES
配置ES
@Configuration
public class GulimallElasticSearchConfig {
public static final RequestOptions COMMON_OPTIONS;
//RequestOptions可以配置一些请求头的,这里不设置
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 RestHighLevelClient esRestClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("192.168.56.101", 9200, "http")));
return client;
}
}
①、创建RestHighLevelClient,每次操作都是RestHighLevelClient操作ES,restHighLevelClient.search(SearchRequest searchRequest, RequestOptions options)
②、创建SearchRequest (索引请求),将检索参数封装成请求
③、创建SearchSourceBuilder,构建检索语句
④、创建QueryBuilders,构建每一个子语句
⑤、将返回的数据封装,result = buildSearchResult(response, Param);
@Override
public SearchResult search(SearchParam Param) {
SearchResult result = null;
// 1.准备检索请求
SearchRequest searchRequest = buildSearchRequest(Param);
try {
// 2.执行检索请求
SearchResponse response = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
// 3.分析响应数据
result = buildSearchResult(response, Param);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
2、构建ES查询语句
/**
* 准备检索请求 [构建查询语句]
*/
private SearchRequest buildSearchRequest(SearchParam Param) {
// 帮我们构建DSL语句的
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 1. 模糊匹配 过滤(按照属性、分类、品牌、价格区间、库存) 先构建一个布尔Query
// 1.1 must
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if(!StringUtils.isEmpty(Param.getKeyword()