Range query with should not working


(Tushar Chevulkar) #1

I have a query whose purpose is to get results with should query and filter it via date range.
In the below query only the range filter is working and ignoring the should query. I have no idea what am I doing wrong.

In mysql the query will be
select * form user where (id=1 OR id=2) AND join_date>xxxx

Current elastic query

{
	"query": {
		"bool": {
			"should": [{
				"term": {
					"id": "1"
				}
			}, {
				"term": {
					"id": "2"
				}
			}]
		},
		"filter": {
			"range": {
				"join_date": {
					"gt": "now-10d"
				}
			}
		}
	}
}

(Shane Connelly) #2

This is because you're combining should and filter, and it's treating the filter as a sort of "must" and then the "shoulds" as optional. See https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html for more information, but the relevant bit is:

The clause (query) should appear in the matching document. In a boolean query with no must or filter clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

Something like the following should work

{
	"query": {
		"bool": {
			"should": [
			  {
  				"term": {
  					"id": 1
  				}
			  },
			  {
				  "term": {
					  "id": 2
				  }
			  }
			],
			"minimum_should_match": 1,
  			"filter": {
				"range": {
  					"join_date": {
  						"gt": "now-10d"
  					}
  				}
  			}
		}
	}
}

(system) #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.