Elasticsearch7.6.2 RestHighLevelClient查询用法 must should(and or 关系)
阅读原文时间:2023年07月09日阅读:1

1. 引入jar

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.2</version>
        </dependency>

2. 初始化RestHighLevelClient

@Configuration
public class ElasticSearchClientConfig {

    @Value("${es.hostname}")
    private String hostname;

    @Value("${es.port}")
    private Integer port;

    @Value("${es.scheme}")
    private String scheme;

    @Bean("esClient")
    public RestHighLevelClient esClient(){
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(hostname, port, scheme)));
        return client;
    }

}

4. 查询

@Slf4j
@Component
public class MzChangeLogDao {

    @Value("${mk.mz.changLog.index}")
    private String indexName;

    @Autowired
    @Qualifier("esClient")
    private RestHighLevelClient restHighLevelClient;

    public List<Object> queryChangeLog(String table, String dbName, String elementsId, String idField) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("fieldA", table));
        boolQueryBuilder.must(QueryBuilders.matchQuery("filedB",  dbName));
        if (StringUtils.isNotBlank(elementsId)) {
            BoolQueryBuilder shouldQueryBuilder = QueryBuilders.boolQuery();
            String[] idFiledArr = idField.split(",");
            for (String id : idFiledArr) {
                shouldQueryBuilder.should(QueryBuilders.matchQuery(id,  elementsId));
            }
            boolQueryBuilder.must(shouldQueryBuilder);
        }

        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(100);
        searchSourceBuilder.sort(new FieldSortBuilder("log_time").order(SortOrder.DESC));
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            // 这里有可能会抛ElasticsearchException,比如没索引 没字段啥的
            log.error("请求ES出错: ", e);
            throw new BizException("请求ES出错: ", e);
        }
        List<Object> retList = new ArrayList<>();
        // 根据状态和数据条数验证是否返回了数据
        if (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().getTotalHits().value > 0) {
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                // 将 JSON 转换成对象
                //UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
                Object json = JSONObject.parse(hit.getSourceAsString());
                retList.add(json);
            }
        }
        return retList;
    }
}

5. must should 解释

用 mysql语法 举例比如 要查询

 where fieldA = 'aaaa' and filedB = 'bbbbb' and (filedC = 'c1' or filedC = 'c2');

对于上述查询,针对ES: RestHighLevelClient查询的写法为利用 mustshould 配合:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("fieldA", "aaaa"));
boolQueryBuilder.must(QueryBuilders.matchQuery("filedB",  "bbbb"));

BoolQueryBuilder shouldQueryBuilder = QueryBuilders.boolQuery();
shouldQueryBuilder.should("filedC", "c1");
shouldQueryBuilder.should("filedC", "c2");
boolQueryBuilder.must(shouldQueryBuilder);

...

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章