Match all values in a nested array using elasticsearch

后端 未结 1 403
甜味超标
甜味超标 2021-01-13 10:41

I am trying to use elasticsearch to match all values in a nested array. For eg. my search array is [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"] and m

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 11:27

    You can get away with a simple Groovy script like this one:

    def match = false; 
    for (sub_array in _source.arr) {
        match = match || (search_array.intersect(sub_array).size() == sub_array.size())
    }
    return match;
    

    The idea is to iterate over all arr sub-arrays and check if the intersection with the search array has the same size as the sub-array itself.

    Wrapping this inside a script filter, the query would look like this:

    POST index/type/_search
    {
       "query": {
          "filtered": {
             "filter": {
                "script": {
                   "script": "def match = false; for (sub_array in _source.arr) {match = match || (search_array.intersect(sub_array).size() == sub_array.size())}; return match;",
                   "params": {
                      "search_array": [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ]
                   }
                }
             }
          }
       }
    }
    

    You also need to make sure to enable dynamic scripting in order for this to work, i.e. in your elasticsearch.yml file just add script.inline: on and restart your cluster.

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