首页 > 解决方案 > 在 ElasticSearch 中包含嵌套字段作为结果项

问题描述

我有一个数据类型,其中包含与嵌套字段相同的数据类型列表。我想查询类型并从外部和内部项目中获取结果。这是我想要实现的一个小例子:

    PUT /testindex?pretty=true
    {
      "mappings": {
        "entry": {
          "dynamic": false,
          "properties": {
            "description": {
              "type": "text"
            },
            "entries": {
              "type": "nested",
              "dynamic": false,
              "properties": {
                "description": {
                  "type": "text"
                }
              }
            }
          }
        }
      }
    }

    PUT /testindex/entry/1?pretty=true
    {
      "id": 1,
      "description": "",
      "entries": [
        {
          "id": 1, "description": "lorem ipsum 11"
        },
        {
          "id": 1, "description": "lorem ipsum 22"
        },
        {
          "id": 1, "description": "dolor sit amet"
        }
      ]
    }

  PUT /testindex/entry/2?pretty=true&refresh=true
  {
    "id": 2, "description": "lorem ipsum", "entries": []
  }

父级有描述或列表。内部类型总是只有一个描述和父级的 Id。当我现在搜索时,我想得到总数 4。此外,当我搜索以“lorem”开头的描述时,结果应该包含 3 个项目。有可能吗?

标签: elasticsearch

解决方案


您需要使用下面的嵌套inner_hits功能。

{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "description": "lorem"
          }
        },
        {
          "nested": {
            "path": "entries",
            "query": {
              "match_phrase": {
                "entries.description": "lorem"
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

推荐阅读