Mongodb空间索引的使用以及与Django的对接

这篇具有很好参考价值的文章主要介绍了Mongodb空间索引的使用以及与Django的对接。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Mongodb的空间索引

Mongodb数据库大家都非常熟悉,是一个基于分布式文件存储的开源数据库系统,在高负载的情况下,添加更多的节点,可以保证服务器性能,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。对与Mongodb还有一个非常重要的功能那就是它的空间索引,一般存储每个地点的经纬度的坐标, 如果要查询附近的场所,则需要建立索引来提升查询效率。 Mongodb专门针对这种查询建立了地理空间索引:2d和2dsphere索引

1.首先安装Mongodb数据库,在此不再赘述

在开始教程之前呢,先介绍一下Mongodb空间索引的查询器以及查询参数,如下所示:

#查询器
$geoWithin       Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d 	  					indexes support $geoWithin. replaces $within which is deprecated.

$geoIntersects      Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index 				     supports $geoIntersects.

$near          Returns geospatial objects in proximity to a point. Requires a geospatial 						index. The 2dsphere and 2d indexes support $near.

$nearSphere        Returns geospatial objects in proximity to a point on a sphere. Requires a 						geospatial index. The 2dsphere and 2d indexes support $nearSphere.
#查询参数
$geometry	    Specifies a geometry in GeoJSON format to geospatial query operators.

$minDistance	Specifies a minimum distance to limit the results of $near and $nearSphere 		 				queries. For use with 2dsphere index only.

$maxDistance	 Specifies a maximum distance to limit the results of $near and $nearSphere 					queries. The 2dsphereand 2d indexes support $maxDistance.

$center			Specifies a circle using legacy coordinate pairs to $geoWithin queries when using 				  planar geometry. The 2d index supports $center.

$centerSphere	 Specifies a circle using either legacy coordinate pairs or GeoJSON format for
				$geoWithin queries when using spherical geometry. The 2dsphere and 2d indexes 					support$centerSphere.
    
$box	         Specifies a rectangular box using legacy coordinate pairs for $geoWithin queries. 				   The 2d index supports $box.

$polygon	     Specifies a polygon to using legacy coordinate pairs for $geoWithin queries. The 				  2d index supports $center.

$uniqueDocs	     Deprecated. Modifies a $geoWithin and $near queries to ensure that even if a         			  document matches the query multiple times, the query returns the document once.

不知道什么意思,没关系,下面开始讲解!

2.2dsphere索引

2dsphere索引是MongoDB最常用的地理空间索引之一,用于地球表面类型的地图。允许使用GeoJSON格式指定点、线、多边形。 点可以用形如[longitude,latitude]([经度,纬度])的两个元素的数组表示("locations"字段的名字可以是任意的,但是其中的子对象是有GeoJSON指定的,不能改变),存储的数据格式如下:

#点状数据
{"coorname" : "蘑菇石", 
    "locations" : {
        "type" : "Point", 
        "coordinates" : [
            108.693809,27.912161
        ]
    }, 
    "types" : "标志性建筑物
    }

#线状数据可以由点组成的数组来表示
{
    "name":"changjiang",
    "locations":{
        "type":"Line",
        "coordinates":[[108.693809,27.912161],[108.693809,27.912161],[108.693809,27.912161]]
    },
    "types" : "标志性建筑物
}

#同样多边形也时用点数组表示,不同的是type的类型
{
    "name":"changjiang",
    "locations":{
        "type":"Polygon",
        "coordinates":[[108.693809,27.912161],[108.693809,27.912161],[108.693809,27.912161]]
    },
    "types" : "标志性建筑物
}

#注意:locations字段里面的key是固定的,不要修改,否则空间索引无法添加

数据添加好之后,就要建立空间索引了:

#1.使用Mongodb命令添加
db.Periphery_basic.ensureIndex({"locations":"2dsphere"})

#2.使用django的ORM添加索引
#在setting中配置mongodb数据库
from mongoengine import connect
CONN = connect('globalmap').geo_example
#创建表
class Periphery_basic(mongoengine.Document):
    coorname = mongoengine.StringField()
    locations = mongoengine.DictField()
    types = mongoengine.StringField()
#添加完数据创建索引
Periphery_basic.create_index([("locations","2dsphere")])

在Mongodb数据库中产看添加成功没有

#查看索引
db.getCollection('Periphery_basic').getIndexes()

#删除集合所有索引
db.getCollection('Periphery_basic').dropIndexes()

#删除集合指定索引
db.getCollection('Periphery_basic').dropIndex('索引名')
3.2D索引

2d索引也是MongoDB最常用的地理空间索引之一,用于游戏地图。2d索引用于扁平表面,而不是球体表面。如果用在球体表面上,在极点附近会出现大量的扭曲变形(一句话就是说2D索引是平面的,2dsphere索引是球面的)

依然用上面的数据格式,添加完之后创建索引

db.Periphery_basic.ensureIndex({"locations.coordinates":"2d"})  #2d索引是要精确到经纬度字段的

#django内创建
Periphery_basic.create_index([("locations.coordinates","2d")])
4.查询

geoWithIn查询, 查询多边形范围内的点 (适用于两种索引)

#命令查询
db.Periphery_basic.find({locations: {$geoWithin: {$geometry: {type : "Polygon" ,coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ]]]}}}})

#Django查询
Periphery_basic.objects(locations={"$geoWithin": {"$geometry": {"type": "Polygon", "coordinates": [[[0, 0], [3, 6], [6, 1], [0, 0]]]}}})

#大于单个半球的查询, 需要加入crs
db.Periphery_basic.find({locations: {$geoWithin: {$geometry: {type : "Polygon" ,coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ]]],crs: {type: "name",properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}}}}})

Periphery_basic.objects(locations={"$geoWithin": {"$geometry": {"type": "Polygon", "coordinates": [[[0, 0], [3, 6], [6, 1], [0, 0]]],crs: {"type": "name",properties: {"name": "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}}}})

geoIntersects, 图形查询, 交集 (2dsphere索引支持)

#命令查询
db.Periphery_basic.find({locations: {$geoIntersects: {$geometry: {type : "Polygon" ,coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ]]]}}}})
#django查询
Periphery_basic.objects(locations={"$geoIntersects": {"$geometry": {"type": "Polygon", "coordinates": [[[0, 0], [3, 6], [6, 1], [0, 0]]]}}})

#大于单个半球的查询, 需要加入crs
db.Periphery_basic.find({locations: {$geoIntersects: {$geometry: {type : "Polygon" ,coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ]]],crs: {type: "name",properties: { name: "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}}}}})

Periphery_basic.objects(locations={"$geoIntersects": {"$geometry": {"type": "Polygon", "coordinates": [[[0, 0], [3, 6], [6, 1], [0, 0]]],crs: {"type": "name","properties": {"name": "urn:x-mongodb:crs:strictwinding:EPSG:4326"}}}}})

$near, 由近道原返回文档的点, 经纬度罗列方式为 [ lng, lat ] (两种索引都支持)

#命令查询
db.Periphery_basic.find({locations:{$near:{$geometry: {type: "Point", coordinates: [120.665283,31.317678]},$minDistance: 1000,$maxDistance: 5000}}})
#django查询
Periphery_basic.objects(locations={"$near":{"$geometry": {"type": "Point", "coordinates": [120.665283,31.317678]},"$minDistance": 1000,"$maxDistance": 5000}})

#传统坐标查询
db.Periphery_basic.find(
   { location : { $near : [120.665283,31.317678], $maxDistance: 10 } }
)

$nearSphere, 空间距离查询 (两种索引都支持)

#命令查询
db.Periphery_basic.find({locations:{$nearSphere:{$geometry: {type: "Point", coordinates: [120.665283,31.317678]},$minDistance: 1000,$maxDistance: 5000}}})
#django查询
Periphery_basic.objects(locations={"$nearSphere":{"$geometry": {"type": "Point", "coordinates": [120.665283,31.317678]},"$minDistance": 1000,"$maxDistance": 5000}})

最大距离内查询 (两种索引都支持)

db.Periphery_basic.find({
   locations: {$nearSphere: [120.665283,31.317678],$maxDistance: 10 }
} )

$center查询, 圆形查询 (2d索引支持)

#平面10公里
db.Periphery_basic.find(
   {locations: { $geoWithin: { $center: [ [120.665283,31.317678], 10 ] } } }
)
#django查询
Periphery_basic.objects(
   locations={"$geoWithin": {"$center": [ [120.665283,31.317678], 10 ] } } 
)

$centerSphere 查询, 球形查询 (两种索引都支持)

#需要把查询的半径转化为弧度
#命令行查询
db.Periphery_basic.find( {
  locations: { $geoWithin: {$centerSphere: [ [ 120.665283,31.317678 ], 3/3963.2 ] } }
} )
#django查询
Village_basic.objects(locations={"$geoWithin": {"$centerSphere": [[ 120.665283,31.317678 ], 3 / 3963.2]}})

$box查询, 先精度后纬度, first lower then upper (2d索引支持)

db.Periphery_basic.find({
   locations: { $geoWithin: {$box:  [ [ 0, 0 ], [120.665283,31.317678]]}}})

$polygon, 多边形查询 (两种索引都支持)

db.Periphery_basic.find({locations: {$geoWithin: { $polygon: [[120.665284,31.317675], [120.665245,31.317612],[120.665265,31.317631]]}}})
小结:

数据量越来越多的情况下,要想找到合适的坐标并不容易,建立空间索引之后,数据库自动会按照地理标准进行检索,速度上是非常快的,目前库中20万条数据,每次查询只需零点几秒,搜索附近的位置信息是真的快而方便。文章来源地址https://www.toymoban.com/news/detail-608975.html

到了这里,关于Mongodb空间索引的使用以及与Django的对接的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 【MongoDB】索引 – 文本索引

    【MongoDB】索引 – 文本索引

    这里准备一些数据 上面创建了description字段的文本索引 结果如下: 可以看到多了一个名称为description_text的索引;另外可以看到索引中有权重(weights)、默认语言(default_language)、指定语言字段(language_override)、文本索引版本(textIndexVersion) 结果如下: 结果如下: 可以

    2024年02月05日
    浏览(9)
  • 【MongoDB】索引 - 复合索引

    【MongoDB】索引 - 复合索引

    这里准备一些学生数据 上面创建了age、name字段的复合索引,其中1代表的是正序排序,-1代表的是倒序排序 复合查询中可以定义多个字段(最多不能超过32个字段)作为索引,但是在查询时只有使用携带第一个索引字段作为查询条件时才会使用当前索引 结果如下: 可以看到多

    2024年02月05日
    浏览(10)
  • 【MongoDB】索引 - 单字段索引

    【MongoDB】索引 - 单字段索引

    MongoDB支持在集合文档中的任意字段上创建索引,默认情况下所有的集合都有一个_id字段的索引,用户和应用可以新增索引用于查询和操作。 这里准备一些学生数据 上面我们查询了students集合中的索引列表 查询结果如下: 默认情况下,students集合中存在一个_id字段的索引;

    2024年02月05日
    浏览(11)
  • MongoDB索引

    MongoDB索引

    索引支持在MongoDB中高效执行查询。如果没有索引,MongoDB必须扫描集合中的每个文档才能返回查询结果。如果查询存在适当的索引,MongoDB将使用该索引来限制它必须扫描的文档数。 尽管索引提高了查询性能,但添加索引对写入操作的性能有负面影响。对于具有高读写比率的集

    2024年02月07日
    浏览(10)
  • MongoDB 索引全攻略

    MongoDB 索引全攻略

    目录 一、索引介绍         1.1 单字段索引         1.2 复合索引         1.3 多键索引         1.4 主键索引         1.5 TTL 索引         1.6 地理空间索引         1.7 哈希索引         1.8 创建索引时注意事项         1.9 索引效果查看  二、索引实现原理         2.1 为

    2024年04月27日
    浏览(12)
  • MongoDB之索引

    MongoDB之索引

    db.table.getIndexes() db.table.totalIndexSize() db.table.reIndex() db.COLLECTION_NAME.dropIndex(\\\"INDEX-NAME\\\") db.COLLECTION_NAME.dropIndexes() _id 索引无法删除。 参考:MongoDB干货系列2-MongoDB执行计划分析详解(1) | MongoDB中文社区、MongoDB - 执行计划 - 听雨危楼 - 博客园 耗时 executionTimeMillis executionStats.execut

    2024年01月20日
    浏览(3)
  • MongoDB索引详解-03

    MongoDB索引详解-03

    索引是一种用来快速查询数据的数据结构。B+Tree 就是一种常用的数据库索引数据结构, MongoDB采用B+Tree 做索引 ,索引创建在colletions上。MongoDB不使用索引的查 询,先扫描所有的文档,再匹配符合条件的文档。 使用索引的查询,通过索引找到文档, 使用索引能够极大的提升查

    2024年02月09日
    浏览(9)
  • MongoDB【五】索引

    在MongoDB中,索引对于提升查询性能至关重要,特别是针对大型数据集时。以下是如何在MongoDB中创建、查看和删除索引的基本操作,以及不同类型的索引如何影响查询性能。 升序索引(默认): 降序索引: 这将创建一个索引,首先按照 field1 升序,然后在 field1 相等的情况下

    2024年04月27日
    浏览(9)
  • Mongodb 添加索引 优化记录

    Mongodb 添加索引 优化记录

    因         每晚12点20分定时任务做数据统计,mongodb 50万条数据开始,每天晚上CPU报警:CPU=95,并耗时3分钟以上. 分析原因:        集合是按月进行生成,集合名称“data-2023-12”,新集合未自动添加相关索引 慢查询 增加索引 db.getCollection(\\\"data-2023-12\\\").createIndex({     dataId:

    2024年02月05日
    浏览(9)
  • Mongodb 以及 node.js中使用mongoose操作数据库

    目录 1、lowdb 2、Mongodb是什么? 3、Mongodb核心概念 4、Mongodb的下载与使用 5、数据库与集合命令 5.1、数据库命令 5.2、集合命令 5.3、文档命令 6、Mongoose 6.1、插入文档 6.2、字段类型 6.3、字段值验证 6.3.1、必填项 6.3.2、默认值 6.3.3、枚举值 6.3.4、唯一值 6.4、删除文档 6.5、更新文

    2024年02月11日
    浏览(10)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包