How to write an Elasticsearch query involving contains-all-of, contains-one-of, contains-exactly and not-contains operations?

早过忘川 提交于 2019-12-13 10:34:52

问题


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"}}
      ]
    }
  }
}


来源:https://stackoverflow.com/questions/47837464/how-to-write-an-elasticsearch-query-involving-contains-all-of-contains-one-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!