`
geeksun
  • 浏览: 952954 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Mongo支持地理索引

 
阅读更多
1. Geospatial Indexing

     MongoDB支持二维空间索引,这是设计时考虑到基于位置的查询。例如“找到离目标位置最近的N条记录”。可以有效地作为附加条件过滤。

 
 
2.  Creating the Index
  db.places.ensureIndex( { loc : "2d" } )     // 支持平面位置索引
或 
 db.places.ensureIndex({loc:”loc_2dsphere"})     // 支持球形位置索引
     
默认的,Mongo假设你索引的是经度/维度,因此配置了一个从-180到180的取值范围,如果你想索引更多,可以指定该参数:
db.places.ensureIndex( { loc : "2d" } , { min : -500 , max : 500 } )  
 
 
3.   Querying
索引可以被用来精确匹配:
db.places.find( { loc : [50,50] } )  
     
对于geo索引来说,更重要的是一个查询可以找到目标点附近的点,不必要精确匹配。
db.places.find( { loc : { $near : [50,50] } } )  
     上面的一句将按离目标点(50,50)距离最近的100个点(距离倒序排列),如果想指定返回的结果个数,可以使用limit()函数,若不指定,默认是返回100个。
db.places.find( { loc : { $near : [50,50] } } ).limit(20)  
 
 
4.  Compound Indexes(复合索引)
      Mongo空间索引可选的支持第二字段索引.如果想用坐标和其他属性同事作为条件查询,把这个属性也一同索引,其他属性带注释性的加入索引中可使过滤更快。
db.places.ensureIndex( { location : "2d" , category : 1 } );  
db.places.find( { location : { $near : [50,50] }, category : 'coffee' } );  
 
 
5.  geoNear Command
      虽然find()语法为查询的首选,Mongo也提供来了 geoNear 命令来执行相似的函数。geoNear命令有一个额外的好处是结果中返回距离目标点的距离,以及一些利于排除故障的信息。
> db.runCommand( { geoNear : "places" , near : [50,50], num : 10 } );  
> db.runCommand({geoNear:"asdf", near:[50,50]})  
 
 
  
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics