Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >玩转mongoDB(七):索引,速度的引领(全文索引、地理空间索引)

玩转mongoDB(七):索引,速度的引领(全文索引、地理空间索引)

作者头像
壮壮熊
修改于 2023-01-17 06:56:12
修改于 2023-01-17 06:56:12
1.3K00
代码可运行
举报
文章被收录于专栏:程序猿牧场程序猿牧场
运行总次数:0
代码可运行

本篇博文主要介绍mongoDB中一些常用的特殊索引类型,主要包括:

  • 用于简单字符串搜索的全文本索引;
  • 用于球体空间(2dsphere)的地理空间索引
  • 用于二维平面(2d)的地理空间索引。

一、全文索引

代码语言:txt
AI代码解释
复制
    mongoDB有一个特殊的索引用在文档中搜索文本,之前的博客都是用精确匹配来查询字符串,这些技术有一定的限制。在搜索大块文本的速度非常慢,而且无法处理自然语言礼节的问题。全文本索引使用的是“倒排索引”的思想来做的,和当前非常开源的lucene(全文检索,Apacle基金会下的开源项目)项目是一样的思想来做的。使用全文本索引可以非常快的进行文本搜索,mongoDB支持多种语言,可惜在免费版中,并不支持世界第一的火星文语言(汉语)。查mongoDB的官网可以看到,在企业版中是支持汉语的全文索引的。
代码语言:txt
AI代码解释
复制
    如果公司用的是免费版的mongoDB,而又需要用到中文的全文索引,建议使用lucene或者solr等开源项目来做。(没钱就得用技术来补,赤裸裸的现实。)
代码语言:txt
AI代码解释
复制
    使用全文本检索需要专门开启这个功能才能进行使用。启动mongoDB时指定--setParameter textSearchEnabled=true选项,或者在运行时执行setParameter命令,都可以启用全文本索引。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.adminCommand({"setParameter":1,"textSearchEnabled":true});
代码语言:txt
AI代码解释
复制
    准备10条数据:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.news.insert({"title":"SEOUL","context":"SEOUL, June 10 (Reuters) - South Korean prosecutors raided the offices of Lotte Group, the country's fifth-largest conglomerate, and several affiliates on Friday, dealing a further blow to its hotel unit's planned IPO, billed as the world's biggest this year."});
db.news.insert({"title":"Many Chinese people","context":"Many Chinese people think that a job on a diplomatic team is too good to quit. So when 28-year-old Liu Xiaoxi left her embassy post as an attache late last year to start a career in photography, she quickly became a popular topic among the Chinese online community."});
db.news.insert({"title":"About","context":"About 200 investigators searched 17 locations including group headquarters in central Seoul and the homes of Chairman Shin Dong-bin and other key executives, local news agency Yonhap reported, citing the Seoul Central Prosecutor's office."});
db.news.insert({"title":"Three people","context":"Three people with direct knowledge of the matter told Reuters that Friday's raids were part of an investigation into a possible slush fund. They also declined to be identified."});
db.news.insert({"title":"A Lotte Group spokesman","context":"A Lotte Group spokesman on Friday declined to comment on the reason for the raid, when asked whether it concerned a possible slush fund. He noted, however, that the situation was difficult given the IPO plans and Lotte Chemical's Axiall bid."});
db.news.insert({"title":"According","context":"According to bourse rules, the deadline for Hotel Lotte to list is July 27, six months from the preliminary approval for the IPO. If it needed to refile its prospectus to warn investors about risks from Friday's probe, which appeared likely, it would probably not be able to meet that deadline, an exchange official told Reuters on Friday."});
db.news.insert({"title":"Friday","context":"On Friday, dozens of Chinese tourists queued as usual to access elevators to the flagship Lotte Duty Free outlet in the group's headquarters complex, as TV cameras waited for investigators to emerge from office doors around the corner."});
db.news.insert({"title":"Named","context":"Named after the heroine of an 18th century Goethe novel, Lotte has grown from its founding in Japan 68 years ago as a maker of chewing gum to a corporate giant with interests ranging from hotels and retail to food and chemicals. The group has annual revenue of around $60 billion in Korea."});
db.news.insert({"title":"Hotel Lotte's","context":"Hotel Lotte's planned flotation of around 35 percent of its shares was intended to bring transparency and improve corporate governance at a group whose ownership structure is convoluted even by the opaque standards of South Korea's conglomerates."});
db.news.insert({"title":"Shares","context":"Shares in Lotte Shopping (023530.KS) , whose units Lotte Department Store and Lotte Home Shopping were raided, fell 1.6 percent on Friday. Lotte Himart (071840.KS) , a consumer electronics retailer, dropped 2.1 percent."});
代码语言:txt
AI代码解释
复制
    一个集合上最多只能有一个全文本索引,但是全文本索引可以包含多个字段。全文索引与“普通”的多键索引不同,全文本索引中的字段顺序不重要:每个字段都被同等对待,可以为每个字段指定不同的权重来控制不同字段的相对重要性。
代码语言:txt
AI代码解释
复制
    我们来给title和context字段建立全文本索引,给title字段2的权重,context字段1的权重。(权重的范围可以是1~1,000,000,000,默认权重是1)。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.news.ensureIndex({"title":"text","context":"text"}
,{"weights":{"title":2,"context":1}})
代码语言:txt
AI代码解释
复制
    我们利用这个全文本索引来搜索一下。搜索的内容是“flotation”。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.news.find({$text:{$search:"flotation"}})
代码语言:txt
AI代码解释
复制
    结果如下图所示:

二、2dsphere索引

代码语言:txt
AI代码解释
复制
    2dsphere索引是mongoDB最常用的地理空间索引之一,用于地球表面类型的地图。允许使用GeoJSON格式(http://www.geojson.org)指定点、线、多边形。
代码语言:txt
AI代码解释
复制
    点可以用形如[longitude,latitude]([经度,纬度])的两个元素的数组表示("loc"字段的名字可以是任意的,但是其中的子对象是有GeoJSON指定的,不能改变):
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
    "name":"beijing",
    "loc":{
        "type":"Point",
        "coordinates":[40,2]
    }  
}
代码语言:txt
AI代码解释
复制
    线可以用一个由点组成的数组来表示:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
    "name":"changjiang",
    "loc":{
        "type":"Line",
        "coordinates":[[1,2],[2,3],[3,4]]
    }  
}
代码语言:txt
AI代码解释
复制
    多边形的表示方式与线一样,但是“type”不同:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
    "name":"shenzhen",
    "loc":{
        "type":"Polygon",
        "coordinates":[[1,2],[2,3],[3,4]]
    }  
}
代码语言:txt
AI代码解释
复制
    创建2dsphere索引: 
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.mapinfo.ensureIndex({"loc":"2dsphere"})
代码语言:txt
AI代码解释
复制
    地理空间查询的类型有三种:交集(intersection)、包含(within)、接近(nearness)。查询时,需要将希望查找的内容指定为形如{"$geometry":geoJsonDesc}的GeoJSON对象。
代码语言:txt
AI代码解释
复制
    使用“$geoIntersects”查询位置相交的文档:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
var customMapinfo = {
    "type":"Polygon",
    "coordinates":[[12.2223,39,4424],[13.2223,38,4424],[13.2223,39,4424]]
}
db.mapinfo.find({
    "loc":{"$geoIntersects":{"$geometry":customMapinfo}} 
})
代码语言:txt
AI代码解释
复制
    这样就会找到所有与customMapinfo区域有交集的文档。
代码语言:txt
AI代码解释
复制
    使用“$within”查询完全包含在某个区域的文档:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.mapinfo.find({
    "loc":{"$within":{"$geometry":customMapinfo}} 
})
代码语言:txt
AI代码解释
复制
    使用“$near”查询附近的位置:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.mapinfo.find({
    "loc":{"$near":{"$geometry":customMapinfo}} 
})

三、2d索引

代码语言:txt
AI代码解释
复制
    2d索引也是mongoDB最常用的地理空间索引之一,用于游戏地图。2d索引用于扁平表面,而不是球体表面。如果用在球体表面上,在极点附近会出现大量的扭曲变形。
代码语言:txt
AI代码解释
复制
    文档中应该使用包含两个元素的数组表示2d索引字段。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{
    "name":"node1",
    "tile":[32,22]
}
代码语言:txt
AI代码解释
复制
    创建索引:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.gameMapinfo.ensureIndex({"tile":"2d"})
代码语言:txt
AI代码解释
复制
    使用$near查询点[20,20]附近的文档:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.gameMapinfo.find({"tile":{"$near":[20,20]}})
代码语言:txt
AI代码解释
复制
    使用$within查询出某个形状(矩形、圆形或者多边形)范围内的所有文档。
代码语言:txt
AI代码解释
复制
    矩形,可以指定`$box选项($`box接受一个两元素的数组,第一个元素指定左下角的坐标,第二个元素指定右上角的坐标):
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.gameMapinfo.find({"tile":{"$within":{"$box":[[10,20],[15,30]]}}})
代码语言:txt
AI代码解释
复制
    圆形,可以指定`$center选项($`center接受一个两元素数组作为参数,第一个元素是一个点,用于指定圆心,第二个元素用于指定半径):
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.gameMapinfo.find({"tile":{"$within":{"$center":[[12,12],5]}}})
代码语言:txt
AI代码解释
复制
    多边形,可以指定`$polygon($`ploygon接受一个多元素的数组,每个元素对应多边形的点),下面以一个三角形为例:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
db.gameMapinfo.find({"tile":{"$within":{"$polygon":[[0,20],[10,0],[-10,0]]}}})
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-01-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序猿牧场 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Javascript权威指南
The not-a-number value has one unusual feature in JavaScript: it does not compare equal to any other value, including itself.
全栈程序员站长
2021/12/27
8780
技术 | 用二进制算法加速神经网络
The original article is published on Nervana site: Accelerating Neural Networks with Binary Arithmetic. Please go to Nervana Homepage to learn more on Intel Nervana's deep learning technologies. At Nervana we are deeply interested in algorithmic and hard
计算机视觉研究院
2018/04/17
6870
技术 | 用二进制算法加速神经网络
Data Representation - Floating Point Numbers
In the last episode we talked about the data representation of integer, a kind of fixed-point numbers. Today we’re going to learn about floating-point numbers.
零式的天空
2022/03/28
4190
JSON5 格式标准 Data Exchange Format 官方文档 中英双语
The JSON5 Data Interchange Format is a proposed extension to JSON that aims to make it easier for humans to write and maintain by hand. It does this by adding some minimal syntax features directly from ECMAScript 5.1.JSON5 数据交换格式是一个提议的 JSON 扩展,旨在通过直接添加一些来自 ECMAScript 5.1 的最小语法特性,使人类更容易手动编写和维护。
WTSolutions
2025/03/30
1740
java.lang.NumberFormatException: Infinite or NaN原因之浮点类型除数为0结果探究
在对Double类型的数据进行计算操作,将结果转化为BigDecimal时抛出了下面的异常,进行了Debug才发现了问题原因,同时也暴露出了自己在一些基础知识上还有些欠缺。
翎野君
2023/05/12
5330
前端学习之NaN浅析
  在学习Java集合的时候遇到了Float.isNaN(float)函数,点进去一看就不理解了,函数实现如下:
Jetpropelledsnake21
2019/02/15
1.3K0
DAY34:阅读算术指令
5.4.1. Arithmetic Instructions Table 2 gives the throughputs of the arithmetic instructions that are
GPUS Lady
2018/06/22
6220
Array Broadcasting in Numpy
Let’s explore a more advanced concept in numpy called broadcasting. The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are also cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation. This article provides a gentle introduction to broadcasting with numerous examples ranging from simple to involved. It also provides hints on when and when not to use broadcasting.
狼啸风云
2019/09/25
5100
Array Broadcasting in Numpy
Source Code Reading for Vue 3: How does `hasChanged` work?
Hey, guys! The next generation of Vue has released already. There are not only the brand new composition API, much more powerful and flexible reactivity system, first-class render function, but also the natural performance with building off the modern browsers.
^_^肥仔John
2021/11/11
4160
谁是代码界3%的王者?- 第四题BigDecimal问题简单解读
提到“在Java代码界,有些陷阱外表看起来是个青铜实际上是王者,据说97%工程师会被“秒杀””
明明如月学长
2021/08/31
3530
谁是代码界3%的王者?- 第四题BigDecimal问题简单解读
基础野:细说浮点数
Brief                                 本来只打算理解JS中0.1 + 0.2 == 0.30000000000000004的原因,但发现自己对计算机的数字表示和运算十分陌生,于是只好恶补一下。  本篇我们一起来探讨一下基础——浮点数的表示方式和加减乘除运算。   在深入前有两点我们要明确的:   1. 在同等位数的情况下,浮点数可表示的数值范围比整数的大;   2. 浮点数无法精确表示其数值范围内的所有数值,只能精确表示可用科学计数法m*2e表示的数值而已;     
^_^肥仔John
2018/01/18
2.5K1
基础野:细说浮点数
常用的数学函数以及浮点数处理函数
在编程中我们总要进行一些数学运算以及数字处理,尤其是浮点数的运算和处理,这篇文章主要介绍C语言下的数学库。而其他语言中的数学库函数的定义以及最终实现也是通过对C数学库的调用来完成的,其内容大同小异,因此就不在这里介绍了。 C语言标准库中的math.h定义了非常多的数学运算和数字处理函数。这些函数大部分都是在C89标准中定义的,而有些C99标准下的函数我会特殊的说明,同时因为不同的编译器下的C标准库中有些函数的定义有差别,我也会分别的说明。
欧阳大哥2013
2018/08/22
2.7K0
常用的数学函数以及浮点数处理函数
C# 7.0简而言之 -- 02. C#基础 (1)
语句1里面计算了表达式(expression) 12 * 30, 并把结果保存到了本地变量x里面, x是整型类型.
solenovex
2018/05/03
1.1K0
C# 7.0简而言之 -- 02. C#基础 (1)
gcc x64 asm 内联汇编尝试
asm volatile(assembler template : output : input : clobber);
战神伽罗
2019/07/24
3K0
gcc x64 asm 内联汇编尝试
IEEE二进制浮点数算术标准(IEEE 754)
IEEE二进制浮点数算术标准(IEEE 754)是20世纪80年代以来最广泛使用的浮点数运算标准,为许多CPU与浮点运算器所采用。这个标准定义了表示浮点数的格式(包括负零-0)与反常值(denormal number)),一些特殊数值(无穷(Inf)与非数值(NaN)),以及这些数值的“浮点数运算符”;它也指明了四种数值舍入规则和五种例外状况(包括例外发生的时机与处理方式)。
用户7886150
2021/02/12
1.5K0
【递归】:[转]Dijkstra was right — recursion should not be difficult
“ …and discovered to my surprise that 10 % of my audience had the greatest difficulty in coping with the concept of recursive procedures. I was surprised because I knew that the concept of recursion was not difficult.” — Dijkstra’s keynote address of 1 March 1999
WEBJ2EE
2021/02/26
5620
【递归】:[转]Dijkstra was right — recursion should not be difficult
日更系列之c++的to_string的浮点数精度问题
做了一个根据搜索词计算embedding向量的服务,但是算法同学发现新服务打分精度变低了,原来能保存到小数点后16位的,现在打分只有小数点后6位。
mariolu
2022/03/05
3.1K0
Talking Head Anime from a Single Image将人脸表情移植到动漫表情中
原文地址https://pkhungurn.github.io/talking-head-anime/
水球喵子
2020/03/20
3K0
Talking Head Anime from a Single Image将人脸表情移植到动漫表情中
C++中检查浮点数值有效性
今天在项目中检查到一个bug,程序会在某些情况下崩溃,最终认定是计算一个比值时,被除数和除数均为零,导致计算结果是个无效值,在后面的代码将使用这个无效值时导致了崩溃。需要对这个结果是否有效进行判断。
用户7886150
2021/02/10
1.1K0
Under the Hood: NaN of JS
如果你还不确定这两题的答案的话,请仔细阅读本文。 这两题的答案不会直接解释,请从文章中寻找答案。
有赞coder
2020/08/25
1.6K0
Under the Hood: NaN of JS
相关推荐
Javascript权威指南
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验