elasticsearch - 检查数组是否包含一个值

gri*_*ure 3 elasticsearch

我想检查包含一些值的数组 long 类型的字段。我发现的唯一方法是使用脚本:ElasticSearch Scripting: check if array contains a value

但它仍然不适合我:查询:

  {
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            },
            "filter": {
                "script": {
                    "script": "doc['Commodity'].values.contains(param1)",
                    "params": {
                        "param1": 50
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到了 0 次点击。虽然我有记录:

{
"_index" : "aaa",
"_type" : "logs",
"_id" : "2zzlXEOgRtujWiCGtX6s9Q",
"_score" : 1,
"_source" : {

   "Commodity" : [
     50
    ],
   "Type" : 1,
    "SourceId" : "fsd",
      "Id" : 123
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*fan 6

试试这个而不是那个脚本:

{
  "query": {
    "filtered": {
      "filter": {
        "terms": {
          "Commodity": [
            55,
            150
          ],
          "execution": "and"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*kAC 6

对于那些使用最新版本 Elasticsearch (7.1.1) 的人,请注意“过滤”和“执行”已被弃用,因此 @Andrei Stefan 的回答可能不再有帮助。

您可以通过以下讨论了解替代方法。

https://discuss.elastic.co/t/is-there-an-alternative-solution-to-terms-execution-and-on-es-2-x/41089

在上述讨论中由 nik9000 编写的答案中,我只是将“term”替换为“terms”(在 PHP 中),它开始处理数组输入,并针对我使用的每个“terms”键应用 AND。

编辑:根据要求,我将发布一个用 PHP 编写的示例查询。

'body' => [ 
      'query' => [ 
           'bool' => [
               'filter' => [
                     ['terms' => ['key1' => array1]],
                     ['terms' => ['key2' => array2]],   
                     ['terms' => ['key3' => array3]],
                     ['terms' => ['key4' => array4]],                            
                           ]
                     ]
                 ]
             ] 
Run Code Online (Sandbox Code Playgroud)

key1、key2 和 key3 是我的 elasticsearch 数据中存在的键,它们将在各自的数组中进行搜索。AND 函数应用于 ["terms" => ['key' => array ] 行之间。