es or查询
//跨索引查询SearchRequest request = new SearchRequest(index1,index2);想实现类似于 select * from table where (a != 1 and b != 1) or (startTime> “2022-05-20” and (a == 1 or b == 1)) 废话不多说,直接上代码@Autowiredprivate
·
//跨索引查询
SearchRequest request = new SearchRequest(index1,index2);
想实现类似于 select * from table where (a != 1 and b != 1) or (startTime> “2022-05-20” and (a == 1 or b == 1)) 废话不多说,直接上代码
@Autowired
private RestHighLevelClient client;
public List<Map<String,Object>> searchList(String index1,String index2,Map<String,Object> paramMap
,String time,int page,int size) {
List<Map<String,Object>> hitList = new ArrayList();
try {
//搜索请求
SearchRequest request = new SearchRequest(index1,index2);
//请求条件构建器,这里和mybatis中的自定义查询有点类型
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//等于条件(其他的一些条件)
if (paramMap != null && !paramMap.isEmpty()) {
paramMap.forEach((k, v) -> {
boolQueryBuilder.must(QueryBuilders.termsQuery(k + KEYWORD, v));
});
}
BoolQueryBuilder query1 = QueryBuilders.boolQuery();
query1.mustNot(QueryBuilders.termsQuery("a" + ".keyword", "1"));
query1.mustNot(QueryBuilders.termsQuery("b" + ".keyword", "1"));
BoolQueryBuilder query2 = QueryBuilders.boolQuery();
//时间范围查询
if (StringUtils.isNotBlank(time)) {
query2.must(QueryBuilders.rangeQuery("startTime"+KEYWORD).from(time));
}
BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();
shouldQuery.should(QueryBuilders.termsQuery("a" + KEYWORD, "1"));
shouldQuery.should(QueryBuilders.termsQuery("b" + KEYWORD, "1"));
query2.must(shouldQuery);
BoolQueryBuilder query3 = QueryBuilders.boolQuery();
query3.should(query1);
query3.should(query2);
boolQueryBuilder.must(query3);
//把查询添加放入请求中
sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
//起始位置
sourceBuilder.from((page - 1) * size);
//查询数量
sourceBuilder.size(size);
sourceBuilder.trackTotalHits(true);
//建立SearchResponse
SearchResponse response;
response = client.search(request, RequestOptions.DEFAULT);
//封装查询的信息
for (SearchHit hit : response.getHits().getHits()) {
hitList.add(hit.getSourceAsMap());
log.debug("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
e.printStackTrace();
}
return hitList;
}
将每一块拆成一个BoolQueryBuilder ,最后or用should()拼接起来
更多推荐
已为社区贡献2条内容
所有评论(0)