1

The task sounds quite simple: if document field equals specific value, add filter, otherwise not filter is applied.

F.x. get all fruits from warehouse but if fruit.type is apple get them delivered 7 days ago.

Is that possible to do on elastic level?

Thank you in advance.

1 Answer 1

1

It is possible to do this in elassticsearch using Nesting Boolean Queries with some range-sugar and date-math-magic.

Since you didn't post your mapping or some sample data I will just use the following data:

curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "orange", "delivered" : "2016-04-22"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "banana", "delivered" : "2016-03-22"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "orange", "delivered" : "2016-04-12"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "apple", "delivered" : "2016-04-12"}'
curl -XPOST http://localhost:9200/testing/foo/ -d '{ "fruit" : "apple", "delivered" : "2016-04-20"}'

Then the following query will do what you want:

curl -XGET "http://localhost:9200/testing/foo/_search" -d'
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "bool": {
                "must_not": {
                  "term": {
                    "fruit": "apple"
                  }
                }
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "fruit": "apple"
                    }
                  },
                  {
                    "range": {
                      "delivered": {
                        "lt": "now-7d"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}'

In SQL this roughly translate to:

WHERE fruit <> 'apple' OR (fruit = 'apple' AND delivered < Now-7d)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.