我试图在SQL中执行与以下内容相同的弹性:
select * from Pets
where type is 'cat'
and age > 10
and name in ("Barry", "Oscar", .....)
我有以下Java代码:
SearchRequest searchRequest = new SearchRequest(elasticIndexName);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("type", "cat"));
queryBuilder.must(QueryBuilders.rangeQuery("age").from("10"));
queryBuilder.must(QueryBuilders.termQuery("name", "Oscar"));
queryBuilder.must(QueryBuilders.termQuery("name", "Barry"));
但是,如果我理解正确,最后两个"必须"陈述相互矛盾。 我尝试使用"应该"这个术语似乎带来了所有猫的名字。
答案 0 :(得分:2)
你几乎就在那里,你需要这样做(即使用terms
查询):
SearchRequest searchRequest = new SearchRequest(elasticIndexName);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("type", "cat"));
queryBuilder.must(QueryBuilders.rangeQuery("age").from("10"));
queryBuilder.must(QueryBuilders.termsQuery("name", "Oscar", "Barry"));
答案 1 :(得分:0)
而不是术语查询,我认为您应该尝试这一点,它会帮助您获得最佳效果。
BoolQueryBuilder boolQueryBuilder = boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("type", cat));
boolQueryBuilder.must(QueryBuilders.rangeQuery("age").gt(10));
boolQueryBuilder.must(QueryBuilders.multiMatchQuery(String.join(" ", Arrays.asList("Barry", "Oscar"), name).type(Type.BEST_FIELDS));