我有一个包含地理空间数据(2dsphere)和时间戳(日期)的集合,我需要根据位置(即地理空间)和时间(即日期)进行查询。
我创建了一个以地理空间和时间为指标的复合索引。但是,当我执行查询(即基于位置和时间)时,queryplanner说它执行了COLLSCAN。
此外,当我仅使用时间添加索引时,它使用该索引(即带有时间戳索引的IXSCAN)。
我有点困惑,我读到您应该能够将2dsphere和时间戳用作基于位置和时间(例如MongoDB Indexing: Multiple single-field vs single compound?)的快速查找的复合索引。
所以我想我的问题是是否可以使用2dsphere作为复合索引? 2dsphere索引的行为是否与其他索引类型(即int,date等)相同,还是有较大差异?例如,假设我们有索引“ timestamp”,“ geospatial”(按该索引顺序),是否可以仅基于时间戳查询(因为它是第一个索引)?
链接到有关2dsphere的文档:https://docs.mongodb.com/manual/core/2dsphere/。
谢谢。
示例数据:
{
"_id" : ObjectId("5e300c9673f256100d5ca0b2"),
"geometry" : {
"type" : "Point",
"coordinates" : [
18.2,
59.8
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T12:01:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0b3"),
"geometry" : {
"type" : "Point",
"coordinates" : [
12.3,
52.4
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T12:10:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0b4"),
"geometry" : {
"type" : "Point",
"coordinates" : [
28.8,
50.2
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T12:50:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0b5"),
"geometry" : {
"type" : "Point",
"coordinates" : [
28.8,
50.2
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T13:50:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0af"),
"geometry" : {
"type" : "Point",
"coordinates" : [
-102.5,
22.6
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T12:01:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0b0"),
"geometry" : {
"type" : "Point",
"coordinates" : [
-104.5,
21
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T12:10:00.158Z")
}
}
{
"_id" : ObjectId("5e300c9673f256100d5ca0b1"),
"geometry" : {
"type" : "Point",
"coordinates" : [
-104.5,
21
]
},
"properties" : {
"@timestamp" : ISODate("2019-01-01T13:10:00.158Z")
}
}
索引:
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test_database.map_reduce_test_data"
},
{
"v" : 2,
"key" : {
"properties.@timestamp" : -1,
"geometry" : "2dsphere"
},
"name" : "properties.@timestamp_-1_geometry_2dsphere",
"ns" : "test_database.map_reduce_test_data",
"2dsphereIndexVersion" : 3
}
查询:
db.map_reduce_test_data.find({"properties.@timestamp": { $gt: new Date("2019-01-01T12:00:00Z"), $lt: new Date("2019-01-01T13:00:00Z") }})
说明结果:
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test_database.map_reduce_test_data",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"properties.@timestamp" : {
"$lt" : ISODate("2019-01-01T13:00:00Z")
}
},
{
"properties.@timestamp" : {
"$gt" : ISODate("2019-01-01T12:00:00Z")
}
}
]
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"$and" : [
{
"properties.@timestamp" : {
"$lt" : ISODate("2019-01-01T13:00:00Z")
}
},
{
"properties.@timestamp" : {
"$gt" : ISODate("2019-01-01T12:00:00Z")
}
}
]
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"ok" : 1
}