nodejs mongo 實現搜附近的人

2022-05-03 04:00:10 字數 1348 閱讀 5522

參考**:

用mongo作為儲存,來實現搜尋附近的人具有先天的優勢,

mongodb原生支援地理位置索引,可以直接用於位置距離計算和查詢。

另外,它也是如今最流行的nosql資料庫之一,除了能夠很好地支援地理位置計算之外,還擁有諸如面向集合儲存、模式自由、高效能、支援複雜查詢、支援完全索引等等特性。

先看一下我在mongo中的資料儲存格式:

/* 0 */

/* 1 */

其實利用mongo搜尋附近的人的最主要的命令是geonear命令,解釋如下:

geonear返回結果集中的dis,如果指定了spherical為true, dis的值為弧度,不指定則為度。不指定sphericial,結果中的dis需要乘以111換算為km:

指定 spherical為true,結果中的dis需要乘以6371換算為km:

--獲取附近500公尺(0.5公里)的人

db.runcommand(,num:10});

其中userinfo為儲存地理位置資訊的集合(即關係型資料庫中所謂的表),maxdistance 指定搜尋的最大半徑範圍,query 指定其他搜尋條件,num(也可以是limit)指定返回結果的條數,其他具體的引數可以參考官方文件說明

nodejs **就非常簡單了:

/**

* 獲取附近的人

*/getnearuser:function(queryparams,callback);

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)

if(queryparams.rows)

if(queryparams.xz);

queryentity.xz = queryparams.xz;

command.query = queryentity;

}db.mongoconn.command(command,function(err,result)else

});}

MongoDB實現搜附近功能

建立對應於資料庫中的對應的實體類 document collection user location compoundindex name location index def public class userlocation implements serializable 編寫實現類 servi...

ES實現搜素建議

幫助 戶在搜尋的過程,對輸入中進行糾錯,提示建議性詞語。例如 輸 的 本分解為 token,然後在索引的字典裡查詢相似的 term 並返回。missing 如索引中已經存在,就不提供建議 popular 推薦出現頻率更加 的詞 always 論是否存在,都提供建議 預設按照 score 排序,也可以...

Hive實現隨機抽樣(附詳解)

select from tab order by rand limit 1000select from select e.cast rand 100000 as int as idx from e t order by t.idx limit 1000表e為乙個存有資料普通表,我們要從表e中隨機抽出...