7

I am new to elasticsearch. I have a filtered query which gives me correct results using console:

GET _search
{
  "query": {
    "filtered": {
      "query": {
             "bool" : {
            "should" : [
              {
                "match" : { "name" : "necklace" }
              },
              {
                "match" : { "skuCode" : "necklace" }
              }
            ]
        }
          },
      "filter": {
            "bool" : {
              "must" : [
                {
                  "term" : { "enabled" : true }
                },
                {
                  "term" : { "type" : "SIMPLE" }
                },
                {
                  "term" : { "tenantCode" : "Triveni" }
                }
              ]
            }
          }
    }
  }
}

I am unable to get the corresponding spring-data version going. Here is what I tried:

SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQuery().should(matchQuery("skuCode", keyword)).should(matchQuery("name", keyword))).withFilter(
                boolFilter().must(termFilter("enabled", true), termFilter("type", "SIMPLE"), termFilter("tenantCode", "Triveni"))).build();

This query gives me no results.

Can somebody please help me with this?

1 Answer 1

7

NativeSearchQueryBuilder.withFilter is converted to so called post_filter. See Post Filter for more details. So the query you have done on the console differs from the one that is generated by spring-data elasticsearch. To mimic the query from the console you have to use the FilteredQuery instead.

Change your query building to this:

QueryBuilder boolQueryBuilder = boolQuery().should(matchQuery("skuCode", keyword)).should(matchQuery("name", keyword));
FilterBuilder filterBuilder = boolFilter().must(termFilter("enabled", true), termFilter("type", "SIMPLE"), termFilter("tenantCode", "Triveni"));
NativeSearchQueryBuilder().withQuery(QueryBuilders.filteredQuery(boolQueryBuilder, filterBuilder).build();

Although as long as you do not use aggregations, this should not affect the (hits) results.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.