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
相关产品推荐
相关产品推荐

