使用 mongoose regex 与文本在 mongo db 中搜索 [英] Searching in mongo db using mongoose regex vs. text

查看:30
本文介绍了使用 mongoose regex 与文本在 mongo db 中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下两者之间的区别:

Can anyone please explain the difference between:

db.collection.find({ $text: { $search: "dog cat" } })

Product.find({ "drug": { "$regex": "cols", "$options": "i" } })

我们应该什么时候去哪一个?

When should we go for which one ?

推荐答案

$正则表达式

为查询中的模式匹配字符串提供正则表达式功能.MongoDB 使用 Perl 兼容的正则表达式(即PCRE")版本 8.36,支持 UTF-8.

Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.36 with UTF-8 support.

$text

对使用文本索引编入索引的字段内容执行文本搜索.

<小时>

对于数据


For data

{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line
Second line" }
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before     line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple
line description" }

要搜索字段sku是单个字符串值,可以使用$regex

To search field sku which is single string value, could use $regex

db.products.find( { sku: { $regex: /^ABC/i } } )

而搜索字段description是文本内容值,可以使用$text,当然我们应该在description上建立文本索引首先.

Whereas to search field description which is text content value, could use $text, of course, we should build text index on description firstly.

db.products.find( { $text: { $search: "coffee" } } )

<小时>

为什么不只是正则表达式?


Why not only regex?

  • 正则表达式有其天然的局限性,因为它们缺乏任何词干提取功能,并且无法以微不足道的方式处理诸如action -superhero"之类的方便搜索查询.
  • 他们无法使用传统索引,这会导致大型数据集中的查询速度非常慢.
  • regular expressions have their natural limitations because they lack any stemming functionality and cannot handle convenient search queries such as "action -superhero" in a trivial way.
  • they cannot use traditional indexes which makes queries in large datasets really slow.

这里有一个链接进行比较

这篇关于使用 mongoose regex 与文本在 mongo db 中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆