var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';
var rx = '';
searchString.split(' ').forEach(e => {
rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});
rx = new RegExp(rx, 'igm');
console.log(text.match(rx));
8 回答
您可以使用以下代码执行此操作 .
由于Mongo shell支持正则表达式,这是完全可能的 .
如果我们希望查询不区分大小写,我们可以使用“i”选项,如下所示:
见:http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart
http://php.net/manual/en/mongo.sqltomongo.php
MySQL的
MongoDB的
从版本2.4开始,您可以在字段上创建text index以搜索并使用$text运算符进行查询 .
首先,创建索引:
db.users.createIndex( { "username": "text" } )
然后,搜索:
db.users.find( { $text: { $search: "son" } } )
基准(约150K文件):
正则表达式(其他答案)=> 5.6-6.9秒
文本搜索=> .164-.201秒
笔记:
集合只能有一个文本索引 . 如果要搜索任何字符串字段,可以使用通配符文本索引,如下所示:
db.collection.createIndex( { "$**": "text" } )
.文本索引可能很大 . 它为每个插入的文档的每个索引字段中的每个唯一的后梗词包含一个索引条目 .
文本索引的构建时间比正常索引要长 .
文本索引不存储有关文档中单词邻近的短语或信息 . 因此,当整个集合适合RAM时,短语查询将更有效地运行 .
由于这是搜索引擎中的第一个点击之一,并且上述所有内容似乎都不适用于MongoDB 3.x,这里有一个正常运行的正则表达式搜索:
无需创建和额外索引或类似 .
如果您通过Python连接MongoDB,则需要执行以下操作
您也可以使用变量名而不是'Son',因此也可以使用字符串连接 .
完成此任务的最简单方法
如果您希望查询为 case-sensitive
如果您希望查询为 case-insensitive
如何在RegExp匹配中忽略HTML标记:
这可能很容易变成MongoDB聚合过滤器 .