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

Elasticsearch7如何按指定值排序嵌套数组并仅返回匹配元素

你可以通过Elasticsearch嵌套查询的inner_hits参数实现需求,该参数会仅返回嵌套数组中匹配查询条件的元素,无需返回完整数组,修改后的查询语句如下:

POST test/_search
{
  "_source": false,
  "query" : {
    "nested" : {
      "query" : {
        "term" : {
          "items.item": {
            "value" : "B",
            "boost" : 1.0
          }
        }
      },
      "path" : "items",
      "ignore_unmapped" : false,
      "score_mode" : "none",
      "boost" : 1.0,
      "inner_hits": {}
    }
  },
  "sort":[
      {
        "items.price": {
              "order": "desc",
              "nested": {
                  "path": "items",
                  "filter": {
                    "term" : { "items.item": "B" }
                  }
              }
          }
      }
  ]
}

返回结果中,每个命中文档的inner_hits.items.hits字段内就是你需要的匹配元素,提取后即可得到你预期的输出格式。
参数说明:

  • "_source": false 用于关闭原始完整文档的返回,进一步减少返回体积
  • inner_hits 是嵌套查询专属的参数,会自动筛选出命中查询条件的嵌套对象,不会包含数组内其他不匹配的元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:54:04