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

Elasticsearch 中如何基于嵌套对象指定字段对父文档排序

Elasticsearch 嵌套对象指定条件排序方案

前置要求

你的orders字段必须设置为nested类型,普通object类型会将嵌套数组拍平,无法关联同个订单对象的name和created_at字段,无法实现该需求。如果你的orders字段当前是object类型,需要重建索引修改映射后再导入数据才能使用后续方案。nested类型映射示例如下:

{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      },
      "orders": {
        "type": "nested",
        "properties": {
          "name": {
            "type": "keyword"
          },
          "created_at": {
            "type": "date"
          }
        }
      }
    }
  }
}

排序查询DSL

直接使用nested排序规则,通过filter筛选出名称为「Bread」的订单,再按对应created_at字段升序排序即可,完整DSL如下:

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "orders.created_at": {
        "order": "asc",
        "nested": {
          "path": "orders",
          "filter": {
            "term": {
              "orders.name": "Bread"
            }
          }
        }
      }
    }
  ]
}

结果说明

执行上述查询后,返回的父文档排序结果和预期完全一致:

  • 第一位:Jane Doe(Bread订单创建时间2020-07-10最早)
  • 第二位:John Doe(Bread订单创建时间2021-08-12)
  • 第三位:John Smith(Bread订单创建时间2021-09-24最晚)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:30:03