M4V3N
M4V3N

Reputation: 629

Elasticsearch query, which returns either everything or the found hits

I can pass optional parameters to my es-query. If no parameters are passed, the es-query should simply return everything not considering the parameter filter.

What I got so far:

{
    "query": {
      "bool": {
          "must": [
            {
              "terms": {
                "person": [
                  "donald trump",
                  "bernie sanders"
                ]
              }
            },
            {
              "range": {
                "date": {
                  "gte": "now-7d",
                  "lte": "now"
                }
              }
            }
          ],
          "should": {
            "terms": {
              "source_name": [
                "nytimes.com"
              ]
            }
          }
        }
    }
}

The source_name field should be optional, meaning if I pass publishers as a parameter then it should return whatever it finds with it and if no publisher params are passed then it should ignore the source_name and simply return everything.

How can I achieve this?

Upvotes: 0

Views: 265

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

Elastic search DSL is declarative language so there is no way to use if else logic(control flow). You should not add the clause(if input is empty) while create the query itself. Or you can use minimum_should_match. In both cases you will need to do changes in the language you are using to generate your elastic search query

Query:

{
"query": {
  "bool": {
  "must": [
    {
      "terms": {
        "person": [
          "donald trump",
          "bernie sanders"
        ]
      }
    },
    {
      "range": {
        "date": {
          "gte": "now-7d",
          "lte": "now"
        }
      }
    }
  ],
  "should": {
    "terms": {
      "source_name": [
        "nytimes.com"
      ]
    }
  }, 
"minumum_should_match":1 --> 0 if input is empty
}
}
}

Upvotes: 1

Related Questions