You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch嵌套查询结果过滤:仅保留匹配的comment元素

解决Elasticsearch嵌套查询仅保留匹配嵌套文档的问题

你当前的nested查询会返回整个feed文档,包括未匹配关键词"ali"的comment,要实现只保留匹配的comment并指定返回feed的特定字段,需要用到inner_hits和**_source字段过滤**,具体修改后的查询如下:

GET feeds/_search
{
  "_source": ["feed_id", "title", "body"], // 指定只返回feed的这三个字段
  "query": {
    "nested": {
      "path": "comment",
      "query": {
        "multi_match": {
          "query": "ali",
          "fields": ["body","title","comment.c_text"]
        }
      },
      "inner_hits": {} // 仅返回匹配当前nested查询的comment对象
    }
  }
}

关键说明:

  • _source:明确指定需要保留的feed级字段,直接过滤掉不需要的冗余内容。
  • inner_hits:在嵌套查询中添加该参数后,Elasticsearch会在每个命中的feed文档下生成单独的inner_hits节点,里面仅包含匹配关键词"ali"的comment对象,未匹配的comment不会出现在此节点中。

返回结果的结构示例:

{
  "hits": {
    "hits": [
      {
        "_source": {
          "feed_id": "123",
          "title": "示例标题",
          "body": "示例正文内容"
        },
        "inner_hits": {
          "comment": {
            "hits": {
              "hits": [
                {
                  "_source": {
                    "c_id": "45",
                    "c_text": "包含ali的评论内容..."
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:01:11