我需要使用Jest客户端进行Elasticsearch查询,以匹配某些术语,并使用范围查询来创建日期。所以我需要使用Jest QueryBuilder
使用范围查询执行bool查询,以获得如下请求:
{
"query": {
"range": {
"gte": "begindate",
"lte": "enddate"
},
"bool": {
"must": [
{
"terms": {
"field1": [
55,
99
]
}
},
{
"terms": {
"field2": [
450
]
}
},
{
"terms": {
"field3": [
11
]
}
}
]
}
}
}
为此,我做了一个像这样的queryBuilder:
Builder search = null;
Search buildedSearch = null;
SearchResult result = null;
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder qb = QueryBuilders.boolQuery();
if (field1 != null) {
qb.must(QueryBuilders.termsQuery("field1", field1));
}
if (field2 != null) {
qb.must(QueryBuilders.termsQuery("field2", field2));
}
if (field3 != null) {
qb.must(QueryBuilders.termsQuery("field3", field3));
}
String query = searchSourceBuilder.query(qb).toString();
if (field != null) {
search = new Search.Builder(query).addIndex(index).addType(type);
if (beginIndex != -1) {
search.setParameter(Parameters.FROM, beginIndex);
}
if (endIndex != -1) {
search.setParameter(Parameters.SIZE, endIndex);
}
buildedSearch = search.build();
}
try {
result = client.execute(buildedSearch);
} catch (IOException e) {
LOGGER.info("Can't found result");
}
我的问题是,如何在searchbuilder上添加范围查询,因为我的对象qb
已经有了boolquery,我无法为此添加范围查询。
答案 0 :(得分:4)
试试这个。
QueryBuilder rangeQuery = QueryBuilders
.rangeQuery("field")
.from("2016-01-01||/D")
.to("2017-01-01||/D")
.includeLower(true)
.includeUpper(false);
QueryBuilder termsQuery = QueryBuilders.boolQuery()
.must(QueryBuilders.termsQuery("field1","12"))
.must(QueryBuilders.termQuery("field2", "abc"))
.must(QueryBuilders.termQuery("field3", "def"));
QueryBuilder qb = QueryBuilders
.boolQuery()
.should(rangeQuery)
.should(termsQuery);
答案 1 :(得分:1)
您需要一个范围查询,如下所示:
QueryBuilder rangeQ = QueryBuilders
.rangeQuery("begindate")
.from(5)
.to(10);
然后将两个查询与should:
组合在一起QueryBuilder qb = QueryBuilders
.boolQuery()
.should(rangeQ)
.should(boolQ);
请查看此帖子:How to construct a boolquery dynamically in java api?了解详情。