如何使用Java库(QueryBuilder)合并ElasticSearch的多个筛选器查询和应该

nwlls2ji  于 2022-10-06  发布在  Java
关注(0)|答案(2)|浏览(217)

我有一个类似以下的问题:

{
"query": {
    "bool": {
        "filter": [
            {
                "range": {
                    "age": {
                        "from": 57,
                        "to": null,
                    }
                }
            },
            {
                "terms": {
                    "_id": [
                        "1212yas1",
                        "sdfsfs1"
                    ]
                }
            }
        ],
        "should": [
            {
                "query_string": {
                 "query": "(football) OR (Cricket)",
                "default_field": "hobbies.hobby"
      }
            }
        ]
    }
}

}

我对ElasticSearch非常陌生,我想用ElasticSearch的Java库实现上面的查询,我该怎么做呢?

爱好是嵌套对象,年龄大。

6rqinv9w

6rqinv9w1#

首先,当您在_id字段上搜索时,需要使用IDs类型查询。

如果您使用的是Java高级客户端,则可以使用以下代码:

QueryBuilder query = QueryBuilders.boolQuery().filter(new RangeQueryBuilder("age").from(57))
                .filter(new IdsQueryBuilder().addIds("1212yas1", "sdfsfs1"))
                .should(new QueryStringQueryBuilder("(football) OR (Cricket)").defaultField("hobbies.hobby"));

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(query);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

如果您使用的是新Java客户端,则可以使用以下代码:

Query query = Query.of(
                q -> q.bool(BoolQuery.of(bq -> bq.filter(f -> f.range(RangeQuery.of(rq -> rq.field("age").from("57"))))
                        .filter(f -> f.ids(IdsQuery.of(iq -> iq.values("1212yas1", "sdfsfs1"))))
                        .should(s -> s.queryString(QueryStringQuery
                                .of(qs -> qs.query("(football) OR (Cricket)").defaultField("hobbies.hobby")))))));
3gtaxfhh

3gtaxfhh2#

如果您使用的是新的Java客户端Api,请尝试以下代码:

var query = Query.of(q -> q.bool(BoolQuery.of(bq -> bq
    .filter(f -> f
        .range(RangeQuery.of(rq -> rq.field("age").from("57"))))
    .filter(f -> f
        .ids(IdsQuery.of(ids -> ids.values(List.of("1212yas1", "sdfsfs1")))))
    .should(s -> s.queryString(
        QueryStringQuery.of(qs -> qs.query("(football) OR (Cricket)").defaultField("hobbies.hobby"))))
)));

var response = client.search(SearchRequest.of(sr -> sr
    .index("idx_name")
    .size(10)
    .query(query)
), Entity.class);

相关问题