我有一个测试数据集(500k 行)
{
"_id": ObjectId("61309575c9346aab086f91fb"),
"listId": ObjectId("61309575c9346aab086f91fa"),
"createdDate": ISODate("2021-09-02T09:12:21.594Z"),
"es0": "Firstname 0 Moscow",
"es1": "[email protected]",
"es2": "0701230000",
"es3": "Equatorial Guinea",
"es4": "Iceland",
"es5": "Los Angeles International Airport",
"ed0": ISODate("1975-10-17T00:00:00Z"),
"ed1": ISODate("2020-01-01T00:00:00Z"),
"ei0": 46,
"ei1": 1345
}
我有一个这样的测试查询
db.collection.aggregate([{
$search: {
"index": "test_index1",
"compound": {
"filter": [{
"equals": {
"path": "listId",
"value": ObjectId("613098df46239505942b8b13")
}
}],
"must": [{
"text": {
"query": 'Los Angeles',
"path": {
'wildcard': '*'
}
}
}]
}
}
},
{
$limit: 10
}]);
速度超级快。
但是如果我添加排序阶段(在 $limit 之前)
{
$sort: {
ei0: -1
}
}
速度真的很慢
我确实在“ei0”上有一个常规索引,并且它也包含在搜索索引中(定义为数字和动态映射关闭)
是否可以在搜索管道内对任何字段(升序/降序)进行排序?
根据doc,现在在
sort
阶段使用can $search
。
这样你就可以将你的聚合重写为,Atlas 搜索允许您按照您在 Atlas 搜索索引中定义的字段对结果进行升序或降序排序。
您可以使用排序选项按日期、数字(整数、浮点和双精度值)和索引为 a
token
type 的字符串字段进行排序。您还可以按结果中文档的分数进行排序。
db.collection.aggregate([{
"$search": {
"index": "test_index1",
"compound": {
"filter": [{
"equals": {
"path": "listId",
"value": "ObjectId(613098df46239505942b8b13)"
}
}],
"must": [{
"text": {
"query": "Los Angeles",
"path": {
"wildcard": "*"
}
}
}]
},
"sort": {
"ei0": -1
}
}
},
{
"$limit": 10
}
])
根据doc,考虑性能
此功能优化使用
$search
和$limit
作为后续阶段的查询。如果 Atlas Search 需要对集合中的所有文档进行排序,响应可能会很慢。