MongoDB:结合文本搜索和地理空间查询 [英] MongoDB: Combine Text Search and Geospatial Query
问题描述
我想知道是否可以组合文本搜索并对结果进行地理空间查询/我将如何做.我目前正在使用Mongoose,但不介意使用直接Mongo作为命令.
I was wondering if it's possible to combine a text search and run a geospatial query on the results / how I would do it. I'm using Mongoose at the moment but don't mind using straight Mongo for the commands.
我想做的是允许用户搜索产品并返回特定位置内的结果.我有两个单独运行的命令,但无法弄清楚如何将它们组合在一起.
What I'm trying to do is allow the user to search for a product and return the results that are within a particular location. I have the two commands running separately, but can't figure out how to combine them.
推荐答案
Mongo DB本身不同时支持文本和地理搜索. [请参阅此]( http ://docs.mongodb.org/manual/reference/limits/#Queries-cannot-use-both-text-and-Geospatial-Indexes )
Mongo DB itself does not support text and geo search at same time. [Refer this] (http://docs.mongodb.org/manual/reference/limits/#Queries-cannot-use-both-text-and-Geospatial-Indexes)
您可以按照以下说明进行操作
You can do it by following
-
请尝试使用 regex 来查找文本,而在Near处则可以查找空间搜索.
Try regex for text and near for spatial search.
var aggregate=YourCollection.aggregation()
aggregate.near({
near:coord,
includeLocs: "loc",
distanceField: "distance",
maxDistance: distance
});
aggregate.match({name:{$regex:keyword,$options: 'i'}})
aggregate.exec(function(err,yourDocuments){
//your smart code
})
使用搜索来查找文本索引,并使用以下查询来查找最近的文档,这与之前所说的相反.
use search for text index and use following query for nearest documents , its just opposite to what said before.
var aggregate=YourCollection.aggregate();
var match= {
latitude: { $lt: yourCurrentLatitude+maxDistance, $gt: yourCurrentLatitude-maxDistance },
longitude: { $lt: yourCurrentLongitude+maxDistance, $gt: yourCurrentLongitude-maxDistance },
{$text:{$search:keyword}}
};
aggregate.match(match).exec(function(err,yourDocuments){//your smart code})
` 3.使用mapreduce将文档分成多个部分.通过文本/地理位置搜索过滤文档,然后将其存储到新集合中.遍历新集合,并通过restig过滤器找到确切的集合.
` 3. Split up the documents into parts using mapreduce. Filter the doucmets either by text/geo search and store it into a new collection. Go through the new collection and findout the exact collection by remainig filter.
YourCollection.mapReduce(map, reduce, {out: {inline:1, query : yourFirstQuery}}, function(err, yourNewCollection) {
// Mapreduce returns the temporary collection with the results
collection.find(yourNewQuery, function(err, result) {
//your awsome code
});
});
这篇关于MongoDB:结合文本搜索和地理空间查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!