例:查询条件:(Integer page, Integer size, String order, List<String> msgidList, String sid, String date)
1.elasticsearchTemplate
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9200
Pageable pageable = PageRequest.of(page - 1, size);
FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("time").order(order.equalsIgnoreCase("desc") ? SortOrder.DESC : SortOrder.ASC);
String index = INDEX_PREFIX + date;
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.termQuery("sid", sid))
.withQuery(QueryBuilders.termsQuery("msgid", msgidList))
.withIndices(index)
.withPageable(pageable)
.withSort(fieldSortBuilder)
.build();
AggregatedPage<TestDTO> ruleHitDetailDTOAggregatedPage = elasticsearchTemplate.queryForPage(query, TestDTO.class);
return ruleHitDetailDTOAggregatedPage.getContent();
2.restHighLevelClient
<!-- ES 客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<!-- ES 版本 -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
@Configuration
public class RestHighClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http"),
new HttpHost("127.0.0.2", 9200, "http"),
new HttpHost("127.0.0.3", 9200, "http")));
return client;
}
}
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
SearchRequest request = new SearchRequest();
request.indices(INDEX_PREFIX + date);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.termQuery("sid", sid));
boolQueryBuilder.must(QueryBuilders.termsQuery("msgid", msgidList));
searchSourceBuilder.query(boolQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchSourceBuilder.from(page-1);
searchSourceBuilder.size(size);
searchSourceBuilder.sort("time", order.equalsIgnoreCase("desc") ? SortOrder.DESC : SortOrder.ASC);
request.source(searchSourceBuilder);
List<String> returnList = new ArrayList<>();
try {
SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
SearchHits searchHit = searchResponse.getHits();
for (SearchHit searchHit : ruleHitDetailDTOSearchHit) {
String result = searchHit.getSourceAsString();
returnList.add(result);
}
} catch (IOException e) {
log.error("queryTraceDetails es search error:{},{}", msgidList, date, e);
}
return returnList;
附文两篇:
https://blog.csdn.net/weixin_42408648/article/details/108199320