Akshay Maldhure
Akshay Maldhure

Reputation: 857

Compond query with Elasticsearch

I'm trying to perform a search with the intended criteria being (activationDate in range 1598889600 to 1602051579) or someFlag=true.

Below is the query I tried, but it does not yield any records with someFlag=true (even with a big size, e.g. 5000). My Elasticsearch does have a lot of records with someFlag=true.

There are about 3000 total documents and this query returns around 280 documents.

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "activationDate": {
              "gte": 1598889600
            }
          }
        },
        {
          "range": {
            "activationDate": {
              "lte": 1602051579
            }
          }
        }
      ],
      "should": {
        "match": {
          "someFlag": true
        }
      }
    }
  },
  "from": 1,
  "size": 1000
}

Am I missing something?

Upvotes: 0

Views: 30

Answers (2)

Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14077

This should work:

{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "range": {
                  "activationDate": {
                    "gte": 1598889600,
                    "lte": 1602051579
                  }
                }
              },
              {
                "term": {
                  "someFlag": true
                }
              }
            ]
          }
        }
      ]
    }
  }
}

In theory this should do the same:

{
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "activationDate": {
              "gte": 1598889600,
              "lte": 1602051579
            }
          }
        },
        {
          "term": {
            "someFlag": true
          }
        }
      ]
    }
  }
}

However the first query I've given wraps bool clause within a filter context (so that it does not need to score and query becomes cacheable).

Your bool query might have not worked because you were using match query, not term. match is normally used for text search only.

Upvotes: 1

ibexit
ibexit

Reputation: 3667

Replace the must with an should and set minimum_should_match=1 as is is an OR query and you are fine if just one of the ceiterias is met by any record. Next reduce the two range criterias to just one, where you combine gte and lte.

Upvotes: 1

Related Questions