Elasticsearch排序问题:按tags存在性与createdAt规则多字段排序
文档排序解决方案
需求说明
需对以下三个文档按规则排序:
- 优先区分
tags字段是否为空:非空tags的文档排在空tags文档之前 tags非空的文档,按createdAt字段升序排列(更早的时间在前)tags为空的文档,按createdAt字段降序排列(更新的时间在前)
原始文档:
[ { "createdAt": "2022-11-25T09:45:00.000Z", "tags": ["Response Needed"] }, { "createdAt": "2022-11-24T09:45:00.000Z", "tags": ["Customer care","Response Needed"] }, { "createdAt": "2022-11-24T09:45:00.000Z", "tags": [] } ]
实现代码(JavaScript)
通过自定义sort函数即可实现规则:
const docs = [ { createdAt: "2022-11-25T09:45:00.000Z", tags: ["Response Needed"] }, { createdAt: "2022-11-24T09:45:00.000Z", tags: ["Customer care", "Response Needed"] }, { createdAt: "2022-11-24T09:45:00.000Z", tags: [] } ]; docs.sort((a, b) => { const aHasTags = a.tags.length > 0; const bHasTags = b.tags.length > 0; // 区分空/非空tags组,非空组排前 if (aHasTags !== bHasTags) { return aHasTags ? -1 : 1; } // 同组内按createdAt排序 if (aHasTags) { // 非空组:升序 return new Date(a.createdAt) - new Date(b.createdAt); } else { // 空组:降序 return new Date(b.createdAt) - new Date(a.createdAt); } }); console.log(docs);
最终排序结果
执行代码后,文档顺序为:
- 含双标签的doc2(非空tags,时间最早)
- 含单标签的doc1(非空tags,时间较晚)
- 空标签的doc3(空tags,按降序排在最后)
输出结果:
[ { "createdAt": "2022-11-24T09:45:00.000Z", "tags": ["Customer care", "Response Needed"] }, { "createdAt": "2022-11-25T09:45:00.000Z", "tags": ["Response Needed"] }, { "createdAt": "2022-11-24T09:45:00.000Z", "tags": [] } ]
内容的提问来源于stack exchange,提问作者Aurovindo Sahu
相关产品推荐
相关产品推荐

