user1649800
user1649800

Reputation:

ElasticSearch conditional filter query by type

How would I ignore the last term filter if fileType doesn't exist/empty string/null?

An example of fileType would be a string such as 'image', 'pdf', 'excel'.

if fileType doesn't exist or is null/empty string I'd like to return all file types

{
  'query': {
    'filtered': {
      'filter': {
        'exists': {
          'field': 'file_id'
        }
      }
    }
  }
  ,'filter': {
    'terms': {
      'conversationUsers': [this._user.id]
    }
  }
  ,'filter': {
    'term': {
      'attachment.type': fileType
    }
  }
}

Upvotes: 1

Views: 1037

Answers (1)

You can use Script filter for that: https://www.elastic.co/guide/en/elasticsearch/reference/2.0/query-dsl-script-query.html

for example:

GET _search
{
  "query": {
    "filtered": {
      "query": {
        "query_string": {
          "query": "*"
        }
      },
      "filter": {
        "script": {
          "script": "if ( !doc['attachment.type'].empty ) doc['attachment.type'].value == param1; else  doc['attachment.type'].value != 0 ;",
          "params": {
            "param1" : "fileType"
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions