How do I use Java to AND multiple setQueries in elasticsearch?… here is a solution to the problem.
How do I use Java to AND multiple setQueries in elasticsearch?
I’m trying to create a query for a search filter using elasticsearch. I created a query that shows results based on search terms, price ranges, and brand lists. The results displayed for the search term and price range are correct, but when a list of brands is provided, all results related to the selected brand are displayed.
I WANT RESULTS FROM SEARCHTERM AND PRICE BRANDS
Here is my query
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String key : brands) {
query.must(QueryBuilders.matchQuery("brand", key));
}
SearchResponse searchresponse = client
.prepareSearch("product")
.setTypes("product")
.setQuery(
QueryBuilders.matchPhraseQuery("name", pSearchTerm))
.setPostFilter(
QueryBuilders.rangeQuery("unit_price").from(min)
.to(max))
.setQuery(query).setExplain(true)
.execute().actionGet();
What am I doing wrong?
Solution
You have two setQuery()
calls, so the second call overrides the first. You need to combine all the constraints into one query like this:
// brand list
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String key : brands) {
query.must(QueryBuilders.matchQuery("brand", key));
}
search term
query.must(QueryBuilders.matchPhraseQuery("name", pSearchTerm));
price range
query.filter(QueryBuilders.rangeQuery("unit_price").from(min).to(max));
SearchResponse searchresponse = client
.prepareSearch("product")
.setTypes("product")
.setQuery(query)
.setExplain(true)
.execute().actionGet();