文档菜单
文档首页
/ / /
Ruby MongoDB 驱动
/

文本搜索

MongoDB 提供了文本索引 以支持对字符串内容的文本搜索查询。文本索引可以包括任何值是字符串或字符串元素数组的字段。

注意

MongoDB Atlas 还提供了更强大、更灵活的文本搜索解决方案 Atlas Search。本页的其余部分将讨论文本索引,而不是 Atlas Search。

要使用 Ruby 驱动程序执行文本搜索,首先使用indexes.create_one() 创建文本索引。以下命令在 test 数据库中 restaurants 集合的 name 字段上创建文本索引。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client['restaurants'].indexes.create_one( { :name => 'text' } )

一旦创建了文本索引,您就可以将其用作查询的一部分。以下代码查找包含单词 garden 的所有文档,这些文档位于 restaurants 集合中,不区分大小写。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client[:restaurants].find(
{ '$text' =>
{ '$search' => 'garden', '$caseSensitive' => false }
}
).each do |document|
#=> Yields a BSON::Document.
end

返回

Map-Reduce