首页 > 解决方案 > 在弹性搜索中搜索对象数组

问题描述

我正在使用 elasticsearch-6.4.3

我创建了一个具有以下映射的索引 test_index:

PUT test_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "keyword"
        },
        "segments": {
          "type": "nested",
          "properties": {
            "f1": {
              "type": "keyword"
            },
            "f2": {
              "type": "integer"
            }
          }
        }
      }
    }
  }
}

我使用以下命令在索引中插入了一个文档:

POST /test_index/_doc
{
  "name": "ABC",
  "segments": [{
    "f1": "abc",
    "f2": 123
  }, 
  {
    "f1": "def",
    "f2": 124
  }]
}

我有一组值说arr = ["def", "xyz"]。我想将至少一个f1 field in segments field匹配项与给定数组中的任何值匹配的所有文档arr

您可以将其称为 array_intersect 以便更容易理解。

我正在尝试这样的事情:

GET /test_index/_search
{
"query": {
    "nested": {
      "path": "segments",
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "f1": [ 
                  "def",
                  "xyz"
                ]
              }
            }
          ]
        }
      }
    }
  }
}

我没有得到任何结果作为输出。
Expected output:文档应该匹配,因为“def”在文档中作为 f1 的值存在。

标签: elasticsearch

解决方案


您需要在您的术语查询中指定完整路径,而segments.f1不是嵌套查询f1

修改查询如下:

POST test_index/_search
{ 
   "query":{ 
      "nested":{ 
         "path":"segments",
         "query":{ 
            "bool":{ 
               "must":[ 
                  { 
                     "terms": {
                       "segments.f1": ["def","xyz"]    <---- Mention full path here

                     }
                  }
               ]
            }
         }
      }
   }
}

希望这可以帮助!


推荐阅读