只想找到最佳的聚合方式,不确定如何在聚合时使用索引。如果有人有这方面的经验,并且可能可以分享想法或经验.
情况:
{
"_id": "",
"timestamp": "",
"userId": "",
"userIp": "",
"country": "",
"city": "",
"applicationName": ""
}问题:我应该如何使用索引?用这样的数据来创建报告的最佳方式是什么?
发布于 2014-04-28 09:39:07
因此,为了优化索引部署,需要创建以下索引,或者在类上使用等效的@CompoundIndexes注释指定以下索引:
db.collection.ensureIndex({
"timestamp": 1, "userId": 1
})
db.collection.ensureIndex({
"timestamp": 1, "applicationName": 1, "country": 1
})这来自您对预期使用的注释,因此总共需要2索引。
还要提到的是,您希望您的“时间戳”值是BSON枣,这样您就可以得到对实际查询非常重要的日期聚合运算符。只需在这里使用shell JavaScript表单作为一般参考:
db.collection.aggregate([
// Using the index that was created
{ "$match": {
"timestamp": {
"$gte": new Date("2014-04-01"), "$lt": new Date("2014-05-01")
},
"userId": { "$gte": "lowervalue", "$lte: "uppervalue" }
}},
// Grouping Data
{ "$group": {
"_id": {
"y": { "$year": "$timestamp" },
"m": { "$month": "$timestamp" },
"d": { "$day": "$timestamp" }
},
"someField": { "$sum": "$someField" },
"otherField": { "$avg": "$otherField" }
}}
])因此,正是“日期聚合运算符”允许您将BSON日期拆分为您想要的组件(在本例中为date ),以便这些边界中包含的所有时间戳值都受其他字段上的其他聚合操作的约束。
请注意,索引只能在聚合管道的初始$match阶段使用,因此这是重要的选择数据和减少工作集的地方。但是,如果您这样做,那么您将从您的数据中获得最大的性能。
为了获得进一步的收益,请考虑在其他集合中“预聚合”信息,基于在原始“日志”数据上定期运行的基本聚合形式。
https://stackoverflow.com/questions/23326175
复制相似问题