在Elasticsearch中如何按nested嵌套字段属性对检索结果排序
要实现按匹配到的actions.createdDate对返回用户排序,你需要在查询语句中新增针对nested字段的排序配置,完整查询如下:
GET users/_search?pretty { "query": { "bool": { "must": [ { "nested": { "path": "actions", "query": { "bool": { "must": [ { "match": { "actions.userId.keyword": "4E3B2ACF-8D21-4CA8-865A-5A128873A6D9" } } ] } }, "inner_hits": {} } } ] } }, "sort": [ { "actions.createdDate": { "order": "desc", "nested": { "path": "actions", "filter": { "match": { "actions.userId.keyword": "4E3B2ACF-8D21-4CA8-865A-5A128873A6D9" } } } } } ], "_source": false }
配置说明
- 排序时必须显式指定nested路径
actions,和查询时的nested路径保持一致 - filter配置和nested查询的过滤条件完全相同,确保排序取的是匹配到目标userId的那条nested文档的createdDate值,避免取到同个用户下其他actions条目的时间
order参数可根据需求调整,desc为按操作时间倒序(最新的在前),asc为按操作时间升序(最早的在前)
内容的提问来源于stack exchange,提问作者Marzouk
相关产品推荐
相关产品推荐

