Range query with should not working

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"
				}
			}
		}
	}
}
2 Likes

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 Boolean query | Elasticsearch Guide [8.11] | Elastic 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"
  					}
  				}
  			}
		}
	}
}
2 Likes

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