Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch : filter results based on the date range

I'm using Elasticsearch 6.6, trying to extract multiple results/records based on multiple values (email_address) passed to the query (Bool) on a date range. For ex: I want to extract information about few employees based on their email_address ([email protected], [email protected], [email protected]) and from the period i.e project_date (2019-01-01).

I did use should expression but unfortunately it's pulling all the records from elasticsearch based on the date range i.e. it's even pulling other employees information from project_date 2019-01-01.

{

  "query": {

    "bool": {

      "should": [

        { "match": { "email_address":   "[email protected]"        }},

        { "match": { "email_address":   "[email protected]"        }}

      ],

      "filter": [

        { "range": { "project_date": { "gte": "2019-08-01" }}}

      ]

    }

  }

}

I also tried must expression but getting no result. Could you please help me on finding employees using their email_address with the date range?

Thanks in advance.

like image 637
Chetan Ramaiah Avatar asked Sep 16 '25 11:09

Chetan Ramaiah


1 Answers

Should(Or) clauses are optional

Quoting from this article. "In a query, if must and filter queries are present, the should query occurrence then helps to influence the score. However, if bool query is in a filter context or has neither must nor filter queries, then at least one of the should queries must match a document."

So in your query should is only influencing the score and not actually filtering the document. You must wrap should in must, or move it in filter(if scoring not required).

GET employeeindex/_search
{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "projectdate": {
            "gte": "2019-01-01"
          }
        }
      },
      "must": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "email.raw": "[email protected]"
                }
              },
              {
                "term": {
                  "email.raw": "[email protected]"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

You can also replace should clause with terms clause as in @AlwaysSunny's answer.

like image 94
jaspreet chahal Avatar answered Sep 18 '25 10:09

jaspreet chahal