filtered query using NativeSearchQueryBuilder in spring-data elasticsearch

Sunny Agarwal picture Sunny Agarwal · Jan 23, 2015 · Viewed 8.3k times · Source

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?

Answer

hochraldo picture hochraldo · Aug 3, 2015

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.