实现类似,但用例差异在Geospatial Haystack Indexing页面上进行了描述。
haystack 索引是针对小区域经度/纬度搜索调整的“基于桶”(又名“象限”)搜索:
In addition to ordinary 2d geospatial indices, mongodb supports the use
of bucket-based geospatial indexes. Called "Haystack indexing", these
indices can accelerate small-region type longitude / latitude queries
when additional criteria is also required.
For example, "find all restaurants within 25 miles with name 'foo'".
Haystack indices allow you to tune your bucket size to the distribution
of your data, so that in general you search only very small regions of
2d space for a particular kind of document. They are not suited for
finding the closest documents to a particular location, when the
closest documents are far away compared to bucket size.
该bucketSize
参数是必需的,并确定干草堆索引的粒度。
因此,例如:
db.places.ensureIndex({ pos : "geoHaystack", type : 1 }, { bucketSize : 1 })
此示例 bucketSize 为 1 创建一个索引,其中 1 个经度或纬度单位内的键存储在同一存储桶中。索引中还可以包含一个附加类别,这意味着将在查找位置详细信息的同时查找信息。
B-tree 表示类似于:
{ loc: "x,y", category: z }
如果您的用例通常搜索“附近”位置(即“25 英里内的餐厅”),干草堆索引可能更有效。可以在每个存储桶中找到并计算附加索引字段(例如类别)的匹配项。
相反,如果您正在搜索“最近的餐厅”并且想要返回结果而不考虑距离,则普通的 2d 索引会更有效。
目前(从 MongoDB 2.2.0 开始)对 haystack 索引有一些限制:
- haystack 索引中只能包含一个附加字段
- 附加索引字段必须是单个值,而不是数组
- 不支持空 long/lat 值
注意:纬度之间的距离会有很大差异(经度,较小)。请参阅:纬度和经度之间的距离是多少?.