Elasticsearch array property must contain given array items

后端 未结 3 1266
谎友^
谎友^ 2021-01-03 11:21

I have documents that look like:

{
    \"tags\" => [
        \"tag1\",
        \"tag2\",
    ],
    \"name\" => \"Example 1\"
}

{
    \"tags\" => [         


        
相关标签:
3条回答
  • 2021-01-03 11:33

    You need to set the execution mode to "and" by adding "execution": "and" to the terms filter so that all terms must be contained within a document to be considered a match

    GET _search
    {
       "query": {
          "filtered": {
             "query": {
                "match_all": {}
             },
             "filter": {
                "terms": {
                   "tags": [
                      "tag1",
                      "tag3"
                   ],
                   "execution": "and"
                }
             }
          }
       }
    }
    

    This is effectively the same as building a bool must filter with the conjunction of all terms, but in a more compact form.

    0 讨论(0)
  • 2021-01-03 11:36

    You can set minimum_should_match to match your array:

    {
        "query": {
            "filtered": {
               "query": {
                   "match_all": {}
               },
               "filter": {
                   "bool": {
                       "must": [
                          {
                              "terms": {
                                 "tags": ["tag1","tag3"],
                                 "minimum_should_match": 2
                              }
                          }
                       ]
                   }
               }
           }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 11:49

    For those who are looking at this in 2020, you might have noticed that minimum_should_match is deprecated long back.

    There is an alternative currently available, which is to use terms_set.

    For eg:

    {
      "query": {
        "terms_set": {
          "programming_languages": {
            "terms": [ "c++", "java", "php" ],
            "minimum_should_match_field": "required_matches"
          }
        }
      }
    }
    
    

    The above example assumes a field required_matches exists which contains an integer, that defines how many matches should be there.

    What is more useful is the alternative field minimum_should_match_script.

    See the example below:

    {
      "query": {
        "terms_set": {
          "programming_languages": {
            "terms": [ "c++", "java", "php" ],
            "minimum_should_match_script": {
              "source": "2"
            },
          }
        }
      }
    }
    

    You can always use the inside a filter context to make it works a filter.

    Read more here

    0 讨论(0)
提交回复
热议问题