如何通过地理空间索引和文本索引快速查询 MongoDB 集合?

How can I query a MongoDB collection by both a geo spatial index and a text index quickly?

假设集合 locations 包含约 20,000,000 个文档,具有 3 个属性:

{
    _id,
    name, // string
    geo // coordinate pair, e.g. [-90.123456, 30.123456]
}

以及 name: 1 的索引和地理索引设置如下:

{ 
    "geo" : "2dsphere"
},
{ 
    "v" : 1, 
    "name" : "geo_2dsphere", 
    "ns" : "db.locations", 
    "min" : "-180.0", 
    "max" : "180.0", 
    "w" : 1.0, 
    "2dsphereIndexVersion" : 2
}

如何在 geo_2dsphere 索引和 name 索引上针对此集合进行高效查询?

当我 运行 仅对地理索引进行 $box 查询时,需要 20 多秒才能获得 return 50 个结果。当我包含针对 name 属性 的搜索时,它会进一步上升。

如果我 运行 一个 $near 查询,那么事情 可以 执行得非常快,但有时查询似乎(非常随机)从 ~200 毫秒开始到很多秒。请参阅此示例,其中唯一的区别是名称索引上的一个额外字符实际上增加了时间:

200 毫秒:

{name: /^mac/, geo: {$near: {$geometry: {type: "Point", coordinates: [ -90.123456, 30.123456 ]}, $maxDistance: 20000}}}

18,000 毫秒:

 {name: /^macy/, geo: {$near: {$geometry: {type: "Point", coordinates: [ -90.123456, 30.123456 ]}, $maxDistance: 20000}}}

我不明白为什么更具体的索引会减慢速度。当我用一个短语变得更具体时,我必须在任何合理的时间内将 $maxDistance 大幅减少到查询 return 之前的 7,000 米。

我应该在这里进行更好的设置吗?

正如 Blakes Seven 向我指出的那样,您不能在 MongoDB 中搜索多个索引:

There is a "highlander rule" (there can be only one) in the query evaluation that denies the usage of more than "one" "special" index in a query evaluation. So you cannot have multiple "text" or muliple "geospatial" or any combination of "text" and "geospatial" or usage of any of those within an $or condition, that results in multiple index selection.

因此,我选择将此特定查询转移到 Elasticsearch,仅索引完成这些多索引查询所需的内容,然后使用这些结果加载必要的 Mongo 文档。见效快,效果好。