//跨索引查询
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()拼接起来

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐