Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to AND multiple setQuery in elasticsearch using java?

I am trying to create query for search filter using elasticsearch. I created query that shows results based on search term, price range and brand list. Results shown for searchterm and price range is right but when brand list is provided all results related to selected brand is shown.

I want results for searchterm AND price AND brands

This 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 here?

like image 992
Vinay Avatar asked Dec 16 '25 19:12

Vinay


1 Answers

You have two setQuery() calls so the second one is overriding the first one. You need to combine all your 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();
like image 85
Val Avatar answered Dec 19 '25 10:12

Val



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!