elasticsearch-java icon indicating copy to clipboard operation
elasticsearch-java copied to clipboard

大佬们,java使用elasticsearch-java调用elasticsearch7.17,如何追加条件呢

Open 1512033796 opened this issue 3 years ago • 1 comments

Description

我的java使用elasticsearch-java调用方式调用elasticsearch7.17,如何追加其他条件呢? 实例:现在我的前端页面上有两个筛选条件,用户可以根据自己需求不选择条件、选择一个条件或者选择两个条件,我在生成SearchRequest后该如何根据实际情况追加query的内容呢? 如图,如果departmentId不为空才添加红框内的内容,该如何实现呢 image

1512033796 avatar Aug 30 '22 08:08 1512033796

Please write issue titles and descriptions in English (Google translate does a decent job for this).

Also avoid pasting screenshots of code: some people cannot read them, and this prevents copy/pasting your code to test it.

Thanks.

swallez avatar Aug 30 '22 09:08 swallez

When call the .query() on the searchRequest multiple times. The last query will overwrite previous query. For your case, please use the bool query https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

        BoolQuery.Builder queryBuilder = new BoolQuery.Builder();
        queryBuilder.must(q -> q.match(m -> m.field("isEnable").query("0")));

        if(departmentId != null && !departmentId.isEmpty()) {
            queryBuilder.must(q -> q.match(m -> m.field("departmentId").query(24)));
        }

        SearchRequest request = SearchRequest.of(r -> r.index(esIndexName)
                .source(s -> s.filter(f -> f.includes("fileId,""filecode", "fileType")))
                .query(queryBuilder.build()._toQuery())
                .sort(s -> s.field(f -> f.field("uploadTime").order(SortOrder.Desc)))
                .from(pageBegin)
                .size(dto.getPageSize()));

jerryguowei avatar Sep 01 '22 13:09 jerryguowei

Thanks for your answer @jerryguowei

swallez avatar Oct 13 '22 09:10 swallez