zoukankan      html  css  js  c++  java
  • Mongodb地理空间索引

    1. LBS地理空间索引

    关于LBS相关项目,一般存储每个地点的经纬度的坐标, 如果要查询附近的场所,则需要建立索引来提升查询效率。 Mongodb专门针对这种查询建立了地理空间索引。 2d和2dsphere索引。

    2. 创建索引

    建立places集合,来存放地点, loc字段用来存放地区数据GeoJSON Point。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    db.places.insert(
       {
          loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
          name: "Central Park",
          category : "Parks"
       }
    )
     
    db.places.insert(
       {
          loc : { type: "Point", coordinates: [ -73.88, 40.78 ] },
          name: "La Guardia Airport",
          category : "Airport"
       }
    )

    建立索引

    1
    db.places.ensureIndex( { loc : "2dsphere" } )

    参数不是1或-1,为2dsphere。还可以建立组合索引。

    1
    db.places.ensureIndex( { loc : "2dsphere" , category : -1, name: 1 } )

    3. 查询

    $geometry表示查询的几何图片.

    3.1 查询多边形范围的值

    type表示类型:polygon 多边形

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    db.places.find( { loc :
                      { $geoWithin :
                        { $geometry :
                          { type : "Polygon" ,
                            coordinates : [ [
                                              [ 0 , 0 ] ,
                                              [ 3 , 6 ] ,
                                              [ 6 , 1 ] ,
                                              [ 0 , 0 ]
                                            ] ]
                    } } } } )

    3.2 查询附近的值

    使用$near来查询附近的地点。

    1
    2
    3
    4
    5
    6
    7
    db.places.find( { loc :
                            { $near :
                              { $geometry :
                                 { type : "Point" ,
                                   coordinates : [ <longitude> , <latitude> ] } ,
                                $maxDistance : <distance in meters>
                         } } } )

    3.3 查询圆形内的值

    查询圆时,需要指定圆心, 半径。

    1
    2
    3
    4
    5
    db.places.find( { loc :
                      { $geoWithin :
                        { $centerSphere :
                           [ [ -88 , 30 ] , 10 ]
                    } } } )

    [-88, 30] 为经纬度, 10为半径。

  • 相关阅读:
    win10下Anaconda3在虚拟环境python_version=3.5.3 中配置pyspark
    在Pycharm上编写WordCount程序
    ASP.NET Core读取AppSettings
    如何高逼格读取Web.config中的AppSettings
    C# 防止同时调用=========使用读写锁三行代码简单解决多线程并发的问题
    C#double转化成字符串 保留小数位数, 不以科学计数法的形式出现。
    Sql Server 里的向上取整、向下取整、四舍五入取整的实例!
    ECMAscript5 新增数组内函数
    js 严格模式
    js中数组去重
  • 原文地址:https://www.cnblogs.com/mafeng/p/7908578.html
Copyright © 2011-2022 走看看