Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...