Docs 菜单
Docs 主页
/ / /
Mongoid
/

文本搜索(Text Search)

在此页面上

  • 定义文本搜索索引
  • 创建文本索引
  • 使用文本索引进行查询

MongoDB提供 文本索引 来支持对Atlas Search string内容进行文本 查询。文本索引可以包括值为string或string元素数组的任何字段。

注意

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

要使用 Mongoid 执行文本搜索,请按照以下步骤操作:

  1. 在模型上定义文本索引。

  2. 在服务器上创建文本索引。

  3. 构建文本搜索查询。

索引页面详细描述了通过 Mongoid 进行的索引定义。 MongoDB 手册中的文本索引部分对文本搜索索引进行了详细描述。下面是一个乐队模型的定义示例,其中的文本索引利用了描述字段:

class Band
include Mongoid::Document
field :name, type: String
field :description, type: String
index description: 'text'
end

请注意,索引类型 (text) 必须以string形式给出,而不是以符号形式给出。

要创建索引,请调用 db:mongoid:create_indexes Rake 任务:

bundle exec rake db:mongoid:create_indexes

要查找描述包含“盎司”或其变体的波段,请使用$text 操作符

Band.where('$text' => {'$search' => 'ounces'}).to_a
# => [#<Band _id: 5d5341b3ce4ef35d5016746d, name: "foo", description: "ounce">]

请注意,即使搜索查询是“盎司”,描述中也包含“盎司”一词。

另请注意,在执行文本搜索时,未显式指定字段的名称 - $text 运算符会搜索使用文本索引编制索引的所有字段。

后退

查询