Search code examples
spring-data-elasticsearchelasticsearch-2.0elasticsearch-java-api

elastic search combining multiple term and range queries is providing zero results


I am struggling on this for a week now. I need to write an elasticsearch query api in java with following combinations:

  1. Price range (0 to n number of ranges)
  2. Age range (0 to n number of ranges)
  3. Search text
  4. Term Filters (can match more than one field

I want to have OR relationship within each group (e.g. price 0-10 or 11-15) but AND relationship among different groups (e.g. price 0-10 AND productType="clothing")

I have written the below code in Java, I have verified that the data exists for the range and filter I am testing with but I am getting zero resultset. I am not sure what is missing here.

@Override
public List<Shoppingi> search(SearchCriteria criteria, Pageable pageable) {

    final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
    BoolQueryBuilder boolQuery = boolQuery();
    // apply the text search
    if (StringUtils.isNotBlank(criteria.getSearchText()))
        boolQuery.must(multiMatchQuery(criteria.getSearchText(), FIELD_NAMES_FOR_TERM_SEARCH));
    // apply the term filters
    BoolQueryBuilder termsQuery = boolQuery();
    criteria.getFilters().entrySet().stream().forEach(entry -> termsQuery.should(termsQuery(entry.getKey(), entry.getValue())));
    // apply the range filters
    BoolQueryBuilder rangeQuery = boolQuery();
    criteria.getRangeFilters().forEach((key, value) -> rangeQuery.should(rangeQuery(key).gte(value.getLowerBound()).lt(value.getUpperBound())));
    boolQuery.must(termsQuery);
    boolQuery.must(rangeQuery);
    searchQuery.withQuery(boolQuery);
    searchQuery.withPageable(pageable);
    NativeSearchQuery query = searchQuery.build();
    log.info("query: {}", query.getQuery().toString());
    return elasticsearchTemplate.queryForList(query,Shopping.class);
}

Solution

  • I annotated the price object as index.no, which caused the query to not work. Once I re-indexed my data with price as non_analyzed, my code started working. So it was nothing wrong with the code above, it was the way I configured the variable I was querying against.