Florian Grell
Florian Grell

Reputation: 1025

Elasticsearch conditional filter

I need to filter out documents with some kind of conditional logic (I think), but I can't get this working.

My documents are like this: {type: 'A'} {type: 'B', foo: ['bar']} {type: 'B', foo: []}

Now I need to filter out all documents of type 'B' where foo is empty. In pseudocode the query would be: if(type == 'B' && foo == []) { // filter out this document } My main query looks like this: query: { filtered: { query: { bool: { must: { match_all: [] } } }, filter: { bool:{ must_not: { term: {'_hidden': true} } } } } } Elasticsearch Version is 1.5.0

Upvotes: 3

Views: 5466

Answers (1)

Waldemar Neto
Waldemar Neto

Reputation: 876

If I understood, is that? if type == a, all documents that have a will return. And if type == b and the field foo is not there they will return, make sense?

{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "bool": {
               "should": [
                  {
                     "term": {
                        "type": "a"
                     }
                  },
                  {
                      "bool": {
                          "must": [
                             {
                                 "term": {
                                    "type": "b"
                                 }
                             }
                          ],
                          "must_not": [
                             {
                                 "missing": {
                                    "field": "foo"
                                 }
                             }
                          ]
                      }
                  }
               ]
            }
         }
      }
   }
}

Upvotes: 2

Related Questions