想知道哪种方法可以更有效地索引我需要跟踪的文档的各种时间戳,请记住我的应用程序在编写时相当繁重,但是如果没有索引,那么查询也很重要慢。
为每个时间戳设置一个字段并为每个字段编制索引,或者将时间戳及其相关类型存储在数组字段中,并为该数组的每个字段编制索引是否更好?
第一个选项,单独的字段和每个字段的索引:
{
"_id" : "...",
"Field1.Timestamp" : '2011-01-01 01:00.000',
"Field2.Timestamp" : '2011-01-01 01:00.000',
"Field3.Timestamp" : '2011-01-01 01:00.000',
"Field4.Timestamp" : '2011-01-01 01:00.000',
"Field5.Timestamp" : '2011-01-01 01:00.000',
"Field6.Timestamp" : '2011-01-01 01:00.000',
"Field7.Timestamp" : '2011-01-01 01:00.000',
"Field8.Timestamp" : '2011-01-01 01:00.000',
"Field9.Timestamp" : '2011-01-01 01:00.000',
}
db.mycollection.ensureIndex({ "Field1.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field2.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field3.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field4.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field5.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field6.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field7.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field8.Timestamp" : 1 });
db.mycollection.ensureIndex({ "Field9.Timestamp" : 1 });
然后是一个时间戳及其状态的数组,只有一个索引
{
"_id" : "...",
"Timestamps" : [
{ "Type" : "Field1", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field2", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field3", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field4", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field5", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field6", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field7", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field8", "Timestamp" : '2011-01-01 01:00.000' },
{ "Type" : "Field9", "Timestamp" : '2011-01-01 01:00.000' },
]
}
db.mycollection.ensureIndex({ "Timestamps.Type" : 1, "Timestamps.Timestamp" : 1 });
我是不是在这里?或哪种方式更好
答案 0 :(得分:2)
这基本上归结为如果10个大小为N的索引比一个大小为N * 10的索引更有效。如果你纯粹看看读取那么单独的索引应该总是更快。相关的b树遍历将检查较小的密钥集等。
但有几点需要考虑: