How to write an Elasticsearch query involving cont

2019-09-20 11:13发布

问题:

I have documents like this:

{
'body': '',
'date': '',
}

I want to get documents with these conditions:

  • body contains all of: ['a', 'b', 'c']
  • and contains one of: ['d', 'e', 'f']
  • and contains exactly these phrases: ['g h i', 'j k l']
  • and not contains: ['m', 'n']

How can I create this query?

回答1:

You need to use bool queries. Important to note that for your "contains exactly these phrases" how that works depends on what analyzers you have applied to the body field.

https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-bool-query.html

For example:

{
  "query": {
    "bool": {
      "must": [
        {"match": {"body": "a"}},
        {"match": {"body": "b"}},
        {"match": {"body": "c"}},
        {"match_phrase": {"body": "g h i"}},
        {"match_phrase": {"body": "j k l"}}
      ],
      "should": [
        {"match": {"body": "d"}},
        {"match": {"body": "e"}},
        {"match": {"body": "f"}}
      ],
      "must_not": [
        {"match": {"body": "m"}},
        {"match": {"body": "n"}}
      ]
    }
  }
}