在 Elasticsearch 中搜索包含某些嵌套对象的文档

Search Documents Containing Certain Nested Objects in Elasticsearch

我在 Elasticsearch 索引中的文档格式如下:

{
    timestamp: "123456789",
    tags: [
        { key:"tag1", "value": "val1" }, ...
    ]
}

我想获取在 tags 字段中包含例如 { key:"tag1" }{ key:"tag2", "value": "val2" } 的所有文档。

我该怎么做?

您可以尝试使用 bool 查询,在其中指定必须部分中需要多少嵌套查询:

GET test_nested/test/_search
{
  "query": {
    "bool": {
      "must": [
        {"nested" : {
            "path" : "tags",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"tags.key" : "tag1"} }
                    ]
                }
            }
        }},
        {"nested" : {
            "path" : "tags",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"tags.key" : "tag2"} },
                    { "match" : {"tags.value" : "val2"} }
                    ]
                }
            }
        }}
      ]
    }
  }
}

在这种情况下,我有一个嵌套查询 select 包含键 "tag1" 的所有文档,第二个嵌套查询 select 包含 "tag2" 和"value2".