標籤:
參考網址:http://blog.csdn.net/huangrunqing/article/details/9112227
用mongo作為儲存,來實現搜尋附近的人具有先天的優勢,
MongoDB原生支援地理位置索引,可以直接用於位置距離計算和查詢。
另外,它也是如今最流行的NoSQL資料庫之一,除了能夠很好地支援地理位置計算之外,還擁有諸如面向集合儲存、模式自由、高效能、支援複雜查詢、支援完全索引等等特性。
先看一下我在mongo中的資料存放區格式:
/* 0 */{ "_id" : "1", "username" : "hyw", "address" : "花園村", "location" : [113.676557, 34.744776], "bloodType" : "O", "nickname" : "皇甫", "xz" : "摩羯座", "tel" : "123456", "birthday" : "1989-12-13", "sex" : "0", "email" : "[email protected]"}/* 1 */{ "_id" : "999", "username" : "uiouio", "address" : "pppppp", "location" : [113.594452, 34.742136], "bloodType" : "x", "nickname" : "oooo", "xz" : "射手", "tel" : "909090", "birthday" : null, "sex" : "男", "email" : "uuuu121"}
其實利用mongo搜尋附近的人的最主要的命令是geoNear命令,解釋如下:
geoNear返回結果集中的dis,如果指定了spherical為true, dis的值為弧度,不指定則為度。不指定sphericial,結果中的dis需要乘以111換算為km:
指定 spherical為true,結果中的dis需要乘以6371換算為km:
--擷取附近500米(0.5公裡)的人
db.runCommand({geoNear:‘userInfo‘,near:[113.676557,34.744778],spherical:true,maxDistance:0.5/6371,distanceMultiplier: 6371,query:{xz:‘雙魚‘},num:10});
其中userInfo為儲存地理位置資訊的集合(即關係型資料庫中所謂的表),maxDistance 指定搜尋的最大半徑範圍,query 指定其他搜尋條件,num(也可以是limit)指定返回結果的條數,其他具體的參數可以參考官方文檔說明http://docs.mongodb.org/manual/reference/command/geoNear/#dbcmd.geoNear
nodejs 代碼就非常簡單了:
/** * 擷取附近的人 */ getNearUser:function(queryParams,callback){ var command = {}; command.geoNear = ‘userInfo‘; command.spherical = true;//如果指定了spherical為true, dis的值為弧度,不指定則為度 command.distanceMultiplier = 6371000;//指定 spherical為true,結果中的dis需要乘以6371換算為km:查詢時指定 distanceMultiplier ,它會將這個參數乘以距離返回 var location = []; location.push(queryParams.lng); location.push(queryParams.lat); command.near = location; if(queryParams.distance){ command.maxDistance = queryParams.distance/6371000; } if(queryParams.rows){ command.num = queryParams.rows; } if(queryParams.xz){ var queryEntity = {}; queryEntity.xz = queryParams.xz; command.query = queryEntity; } db.mongoConn.command(command,function(err,result){ if(err){ return callback(err); }else{ callback(null,result.results); } }); }
nodejs+mongo 實現搜附近的人