I need to make an Elasticsearch query using Jest client, to match some terms and a date with a range query. So I need to perform a bool query with a range query using Jest QueryBuilder to have a request like this:
{
"query": {
"range": {
"gte": "begindate",
"lte": "enddate"
},
"bool": {
"must": [
{
"terms": {
"field1": [
55,
99
]
}
},
{
"terms": {
"field2": [
450
]
}
},
{
"terms": {
"field3": [
11
]
}
}
]
}
}
}
To do this, I used queryBuilder like this :
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");
}
How can I add a range query on the search builder, because my object qb has already a boolquery, and I can't add a range query to this.
Try this.
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);
You need a range query like below:
QueryBuilder rangeQ = QueryBuilders
.rangeQuery("begindate")
.from(5)
.to(10);
then combine the two queries with a should:
QueryBuilder qb = QueryBuilders
.boolQuery()
.should(rangeQ)
.should(boolQ);
Take a look at this post: How to construct a boolquery dynamically in java api? for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With