首页
/ Mongoid Search 技术文档

Mongoid Search 技术文档

2024-12-20 03:07:39作者:凌朦慧Richard

安装指南

1. 添加 Gem

在项目的 Gemfile 中添加以下内容:

gem 'mongoid_search'

2. 安装 Gem

运行以下命令来安装 Gem:

bundle install

项目的使用说明

1. 定义搜索模型

首先,在你的模型中引入 Mongoid::Search 模块,并定义需要搜索的字段。例如:

class Product
  include Mongoid::Document
  include Mongoid::Search
  field :brand
  field :name
  field :unit
  field :info, type: Hash

  has_many   :tags
  belongs_to :category

  search_in :brand, :name, tags: :name, category: :name, info: %i[summary description]
  search_in :unit, index: :_unit_keywords
end

class Tag
  include Mongoid::Document
  field :name

  belongs_to :product
end

class Category
  include Mongoid::Document
  field :name

  has_many :products
end

2. 保存数据并生成关键词

当你保存一个 Product 对象时,_keywords 字段会自动生成:

p = Product.new brand: 'Apple', name: 'iPhone', unit: 'kilogram', info: { summary: 'Info-summary', description: 'Info-description' }
p.tags << Tag.new(name: 'Amazing')
p.tags << Tag.new(name: 'Awesome')
p.tags << Tag.new(name: 'Superb')
p.save
# => true
p._keywords
# => ["amazing", "apple", "awesome", "iphone", "superb", "Info-summary", "Info-description"]
p._unit_keywords
# => ["kilogram"]

3. 执行搜索

你可以通过 full_text_search 方法进行搜索,搜索结果会返回匹配的记录:

Product.full_text_search("apple iphone").size
# => 1

4. 动态字段搜索

你还可以通过定义方法来实现动态字段的搜索:

class ModelWithDynamicFields
  
  ...
  
  search_in :search_data

  def search_data
    # 将所有字符串字段的值拼接起来
    self.attributes.select{|k,v| v.is_a?(String) }.values.join(' ')
  end
end

5. 多索引搜索

你可以为不同的搜索需求定义多个索引,并通过 index 参数指定使用哪个索引进行搜索:

Product.full_text_search("kilogram", index: :_unit_keywords).size
# => 1

项目API使用文档

1. full_text_search 方法

full_text_search 方法用于执行全文搜索,支持以下参数:

  • query: 搜索的关键词。
  • match: 匹配模式,可以是 :any:all,默认为 :any
  • allow_empty_search: 是否允许空搜索,默认为 false
  • relevant_search: 是否返回相关性信息,默认为 false
  • index: 指定使用的索引,默认为 _keywords

示例:

Product.full_text_search('apple motorola', match: :any).size
# => 1

Product.full_text_search('apple motorola', match: :all).size
# => 0

2. search_in 方法

search_in 方法用于定义需要搜索的字段,支持直接字段和关联字段:

search_in :brand, :name, tags: :name, category: :name, info: %i[summary description]

3. rake mongoid_search:index 任务

该任务用于重新索引所有现有记录:

$ rake mongoid_search:index

项目安装方式

1. 通过 Gemfile 安装

Gemfile 中添加:

gem 'mongoid_search'

然后运行:

bundle install

2. 初始化配置

你可以通过创建一个初始化文件来配置 Mongoid::Search 的选项:

Mongoid::Search.setup do |config|
  config.match = :any
  config.allow_empty_search = false
  config.relevant_search = false
  config.stem_keywords = false
  config.ignore_list = []
  config.regex_search = true
  config.regex = Proc.new { |query| /#{query}/ }
  config.ligatures = { "œ"=>"oe", "æ"=>"ae" }
  config.strip_symbols = /[._:;'\"`,?|+={}()!@#%^&*<>~\$\-\\\/\[\]]/
  config.strip_accents = /[^\s\p{Alnum}]/
  config.minimum_word_size = 2
end

通过以上步骤,你可以成功安装并使用 Mongoid Search 进行全文搜索。

登录后查看全文
热门项目推荐