Searchkick 实战指南:为 Rails 应用接入 Elasticsearch / OpenSearch 的智能搜索

原创2026-10-14 17:58:321,395 阅读
文章标签:后端搜索引擎

Searchkick 实战指南:为 Rails 应用接入 Elasticsearch / OpenSearch 的智能搜索

Searchkick 是一个面向 Ruby on Rails 生态的智能搜索库,为 Active Record 与 Mongoid 模型提供开箱即用的全文检索能力。它内置词干提取(stemming)、拼写纠错、同义词、自动补全、聚合统计与个性化排序等能力,让开发者可以用接近 SQL 的语法完成复杂查询。本文以仓库 README.md 为主线,结合 lib/searchkick 下的源码实现,系统讲解安装、查询、索引、智能搜索、部署与性能调优的完整链路,读完即可在项目中落地一套可生产使用的搜索方案。

入门:安装与最小可用示例

安装 Elasticsearch 或 OpenSearch

Searchkick 作为客户端库,需要先准备一个搜索服务端。当前仓库版本支持 Elasticsearch 7 与 8、OpenSearch 1 与 2;若使用 Elasticsearch 6,需切换到 4.6.3 及对应文档(见 README.md)。

macOS 下用 Homebrew 安装:

brew install elastic/tap/elasticsearch-full
brew services start elasticsearch-full
# 或
brew install opensearch
brew services start opensearch

在 Gemfile 中添加依赖

在应用的 Gemfile 中加入 searchkick,并按所选服务端二选一安装官方客户端:

gem "searchkick"

gem "elasticsearch"   # select one
gem "opensearch-ruby" # select one

两个客户端 gem 同时安装时,Searchkick 无法自动判断使用哪个,需要显式指定:

Searchkick.client_type = :elasticsearch # 或 :opensearch

否则会抛出 Multiple clients found 错误;若一个都没有安装,则会提示安装对应客户端 gem。客户端初始化逻辑见 lib/searchkick.rb。

模型接入三步骤

第一步,在目标模型中声明 searchkick:

class Product < ApplicationRecord
  searchkick
end

第二步,建立搜索索引(将数据库数据导入索引):

Product.reindex

第三步,执行搜索:

products = Product.search("apples")
products.each do |product|
  puts product.name
end

Searchkick 底层支持完整的 Elasticsearch / OpenSearch Search API,随着搜索需求变复杂,可以使用 body / body_options 直接编写服务端 DSL(详见后文「高级搜索」)。

查询:像写 SQL 一样搜索

Searchkick 的核心设计目标之一就是「query like SQL」,通过命名参数即可组合出丰富的查询条件。

基础组合查询

Product.search("apples", where: {in_stock: true}, limit: 10, offset: 50)
  • where:结构化过滤条件(等价于 SQL 的 WHERE)
  • limit / offset:等价于 SQL 的 LIMIT / OFFSET
  • fields:限定参与匹配的字段,如 fields: [:name, :brand]
  • order:排序,默认 order: {_score: :desc} 按相关性排序,也可按字段排序
  • select:服务端 source 过滤,如 select: <a href="https://link.gitcode.com/i/bd204e39439e1030fe52fde3ba029569" target="_blank">:name](对应源码 [query.rb 中 _source 设置)

where 支持的操作符

写法 语义 示例
{gt: v} / {gte: v} / {lt: v} / {lte: v} 范围比较 expires_at: {gt: Time.now}
1..10 区间(等价 {gte: 1, lte: 10}) orders_count: 1..10
[a, b] in 集合 aisle_id: [25, 30]
{not: v} 不等于 store_id: {not: 2}
{not: [a, b]} not in aisle_id: {not: [25, 30]}
{all: [a, b]} 数组包含全部元素 user_ids: {all: [1, 3]}
{like: "%x%"} 通配匹配(% 任意多字符、_ 单字符) category: {like: "%frozen%"}
{ilike: "%x%"} 大小写不敏感通配(需 Elasticsearch 7.10+) category: {ilike: "%frozen%"}
/regexp/ 正则匹配(Ruby 正则对象) category: /frozen .+/
{prefix: "x"} 前缀匹配 category: {prefix: "frozen"}
{exists: true} 字段存在性 store_id: {exists: true}
_not: {...} 取反整个条件 _not: {store_id: 1}
_or: [...] 或逻辑 _or: [{in_stock: true}, {backordered: true}]
_and: [...] 与逻辑 _and: [{in_stock: true}, {backordered: true}]

这些操作符在 query.rb 的 where_filters 中逐一映射为底层查询:like/ilike 会先转义 Lucene 保留字符,再把 %、_ 翻译为正则通配符;区间、in、not、exists、_or/_and/_not 分别编译为 range、terms、bool must_not、exists、bool should/must 等结构。

结果对象:Searchkick::Relation

搜索返回 Searchkick::Relation(见 relation.rb),它向数组的大多数方法委托执行结果(见 query.rb 的 delegators):

results = Product.search("milk")
results.size
results.any?
results.each { |result| ... }

常用结果访问方式:

results.total_count # 总命中数
results.took        # 搜索耗时(毫秒)
results.response    # 服务端完整响应

默认情况下,Searchkick 先从搜索服务端取回文档 id,再从数据库加载对应记录;若希望完全由服务端返回数据,使用 load: false:

Product.search("apples", load: false)

注意:Elasticsearch 与 OpenSearch 默认将分页限制在 10,000 条以内(含 total_count),原因与开销见「深度分页」一节。

相关性加权(Boosting)

字段级加权:

Product.search("milk", fields: ["title^10", "description"])

按字段值加权(字段必须为数值型):

boost_by: [:orders_count]                       # 热门商品小幅加权
boost_by: {orders_count: {factor: 10}}          # 默认 factor 为 1

按匹配条件加权:

boost_where: {user_id: 1}
boost_where: {user_id: {value: 1, factor: 100}}  # 默认 factor 为 1000
boost_where: {user_id: [{value: 1, factor: 100}, {value: 2, factor: 200}]}

按时间衰减加权(越新越靠前):

boost_by_recency: {created_at: {scale: "7d", decay: 0.5}}

源码中这些加权最终被组装成 function_score 查询:boost_by 走 field_value_factor(ln2p 修正),boost_where 走 weight 过滤函数,boost_by_distance 与 boost_by_recency 走 gauss 等衰减函数,见 query.rb 与 build_query(query.rb)。

全量查询

用 * 作为查询词即可匹配所有文档:

Product.search("*")

分页

与 kaminari、will_paginate 无缝协作:

# controller
@products = Product.search("milk", page: params[:page], per_page: 20)
<!-- kaminari -->
<%= paginate @products %>

<!-- will_paginate -->
<%= will_paginate @products %>

分页参数在 prepare 中换算为 page、per_page、offset、padding 并生成 size/from,相关实现见 query.rb。

部分匹配(Partial Matches)

默认要求命中查询中的所有词(AND 语义):

Product.search("fresh honey") # fresh AND honey

改为 OR 语义:

Product.search("fresh honey", operator: "or") # fresh OR honey

默认是整词匹配——back 不会命中 backpack。若需词前缀/中缀/后缀匹配,先在模型声明:

class Product < ApplicationRecord
  searchkick word_start: [:name]
end

重新索引后按字段与匹配模式搜索:

Product.search("back", fields: [:name], match: :word_start)

匹配模式总表:

选项 匹配范围 示例
:word 整个词 apple 命中 apple
:word_start 词的开头 app 命中 apple
:word_middle 词的任意部分 ppl 命中 apple
:word_end 词的结尾 ple 命中 apple
:text_start 文本开头 gre 命中 green apple,app 不命中
:text_middle 文本任意部分 een app 命中 green apple
:text_end 文本结尾 ple 命中 green apple,een 不命中

默认是 :word;word_middle 产生最多匹配。不同字段可指定不同匹配模式:

Product.search(query, fields: [{name: :word_start}, {brand: :word_middle}])

这些模式对应索引分析阶段生成的 searchkick_word_start_index、searchkick_word_middle_index 等一组分析器(见 index_options.rb),搜索侧使用 searchkick_word_search / searchkick_autocomplete_search 分析器(query.rb)。

精确匹配与短语匹配

大小写敏感的精确匹配:

Product.search(query, fields: [{name: :exact}])

仅匹配严格顺序的短语:

Product.search("fresh honey", match: :phrase)

词干提取与多语言

Searchkick 默认对英文做词干提取:apple 与 apples 都归并为 appl,因此两个词的搜索结果一致。切换语言:

class Product < ApplicationRecord
  searchkick language: "german"
end

支持的语言列表以 Elasticsearch 官方 stemmer 配置为准;其中部分语言需要安装插件:

语言参数 依赖插件
chinese analysis-ik
chinese2 analysis-smartcn
japanese analysis-kuromoji
korean analysis-openkoreantext
korean2 analysis-nori
polish analysis-stempel
ukrainian analysis-ukrainian
vietnamese analysis-vietnamese

这些语言在 index_options.rb 的 update_language 中分别替换默认、search、search2 三套分析器(如中文 ik_smart/ik_max_word、日文 kuromoji 系、韩文 nori 等)。

也可以改用 Hunspell 词典:

class Product < ApplicationRecord
  searchkick stemmer: {type: "hunspell", locale: "en_US"}
end

关闭词干提取:

class Image < ApplicationRecord
  searchkick stem: false
end

排除特定词不被词干化:

searchkick stem_exclusion: ["apples"]

自定义词干改写规则:

searchkick stemmer_override: ["apples => other"]

词干相关配置(stem、stemmer、stemmer_override、stem_exclusion)在 index_options.rb 的 update_stemming 中注入分析链:stemmer_override 使用 stemmer_override token filter,stem_exclusion 使用 keyword_marker filter。

同义词(Synonyms)

class Product < ApplicationRecord
  searchkick search_synonyms: [["pop", "soda"], ["burger", "hamburger"]]
end

修改同义词后需重新索引(Product.reindex)。同义词在搜索时、词干提取之前生效,可包含单词或多词。单向同义词用 =>:

search_synonyms: ["lightbulb => halogenlamp"]

动态同义词(Dynamic Synonyms)

静态同义词列表每次变更都要全量重建索引,成本较高。基于搜索转化数据分析时,通常希望免重建索引地追加同义词。

Elasticsearch 7.3+ 与 OpenSearch:把同义词写入搜索服务端 config 目录下的文件:

pop, soda
burger, hamburger

模型指向该文件:

class Product < ApplicationRecord
  searchkick search_synonyms: "synonyms.txt"
end

需要生效时热加载:

Product.search_index.reload_synonyms

reload_synonyms 的实现因服务端而异(见 index.rb):OpenSearch 调用 _plugins/_refresh_search_analyzers,Elasticsearch 调用 _reload_search_analyzers(低于 7.3 或 OSS 版本会报错)。

Elasticsearch < 7.3:可以借助 ActsAsTaggableOn 之类库,把标签拼进一个字段再对该字段搜索:

class Product < ApplicationRecord
  acts_as_taggable
  scope :search_import, -> { includes(:tags) }

  def search_data
    {
      name_tagged: "#{name} #{tags.map(&:name).join(" ")}"
    }
  end
end
Product.search(query, fields: [:name_tagged])

拼写纠错(Misspellings)

默认按编辑距离(edit distance)为 1 容忍拼写错误:

Product.search("zucini", misspellings: {edit_distance: 2}) # zucchini

为了在拼写正确的查询(大多数场景)上兼顾精度与性能,可以先不纠错搜索,结果过少时再带纠错重搜一次:

Product.search("zuchini", misspellings: {below: 5})

当结果少于 5 条时自动执行第二次带纠错的搜索并返回其结果。这一逻辑在 query.rb 记录阈值,在 execute(query.rb)中通过 retry_misspellings? 判断是否重试。

关闭拼写纠错:

Product.search("zuchini", misspellings: false) # no zucchini

限定可纠错字段(此时必须同时指定 fields):

Product.search("zucini", fields: [:name, :color], misspellings: {fields: [:name]})

若未在 fields 中声明却出现在 misspellings<a href="https://link.gitcode.com/i/c9f9c47c9b1ac3797db62812a8cf4bc5" target="_blank">:fields],会直接抛 ArgumentError([query.rb)。

排除坏匹配

用户搜 butter 却返回 peanut butter 时,可排除指定词:

Product.search("butter", exclude: ["peanut butter"])

支持按查询词映射排除项:

exclude_queries = {
  "butter" => ["peanut butter"],
  "cream" => ["ice cream", "whipped cream"]
}

Product.search(query, exclude: exclude_queries[query])

也可以降权而不是排除——把 boost factor 设为小于 1:

Product.search("butter", boost_where: {category: {value: "pantry", factor: 0.5}})

exclude 在源码中编译为 bool must_not 中的 multi_match phrase 查询(query.rb)。

Emoji 搜索

支持 :ice_cream::cake: 之类 emoji 直接命中 ice cream cake。需要额外安装 gemoji-parser:

gem "gemoji-parser"

搜索时开启:

Product.search("🍨🍰", emoji: true)

Query#initialize 中会用 EmojiParser 把 emoji 展开为对应的英文词再执行搜索(query.rb)。

索引:数据如何进入搜索服务端

控制索引内容:search_data

默认使用 to_hash/serializable_hash 的字段;需要定制时覆写 search_data(修改后调用 Product.reindex):

class Product < ApplicationRecord
  belongs_to :department

  def search_data
    {
      name: name,
      department_name: department.name,
      on_sale: sale_price.present?
    }
  end
end

默认 search_data 实现在 model.rb,会剔除 id、_id、_type 等保留字段。

批量导入与关联预加载

Searchkick 使用 find_in_batches 分批导入;需要预加载关联时通过 search_import scope:

class Product < ApplicationRecord
  scope :search_import, -> { includes(:department) }
end

条件索引:should_index?

默认所有记录都会索引,可用 should_index? 控制:

class Product < ApplicationRecord
  def should_index?
    active # only index active records
  end
end

默认实现恒返回 true(model.rb)。导入与删除时都会调用它做过滤。

中断续跑

Product.reindex(resume: true)

resume: true 会复用最近一次创建的未完成索引继续导入(见 index.rb 的 full_reindex)。

何时需要重索引

需要 reindex:安装或升级 Searchkick、修改 search_data 方法、修改 searchkick 方法的配置。

无需 reindex:应用启动(索引结构未变)。

四种索引同步策略

策略 说明 配置
Inline(默认) 记录增删改时同步写入 searchkick(默认)
Asynchronous 后台任务异步更新,性能更好 searchkick callbacks: :async
Queuing 先把待更新 id 入队,再批量后台重建,比 async 更高效 searchkick callbacks: :queue
Manual 关闭自动同步,手动控制 searchkick callbacks: false

异步任务进入名为 searchkick 的队列(可通过 Searchkick.queue_name 修改)。

手动模式下手动重索引单条记录或整个关联:

product.reindex
# 或
store.products.reindex(mode: :async)

批量更新(把多次单条更新合并为 bulk 请求):

Searchkick.callbacks(:bulk) do
  Product.find_each(&:update_fields)
end

临时跳过回调:

Searchkick.callbacks(false) do
  Product.find_each(&:update_fields)
end

覆盖单条记录的策略:

product.reindex(mode: :async) # :inline or :queue

回调机制见 searchkick.rb:callbacks_value 为 :bulk 时,块结束时统一经 indexer.perform 批量提交;模型侧的 after_commit 回调在 model.rb 注册,且以 Searchkick.callbacks? 判断是否真正触发。

关联更新不会自动同步

关联对象变更不会自动触发父文档重建,需要手动加回调:

class Image < ApplicationRecord
  belongs_to :product

  after_commit :reindex_product

  def reindex_product
    product.reindex
  end
end

默认作用域(Default Scope)

默认作用域过滤掉的记录,应通过 should_index? 同步排除,避免索引中出现“幽灵数据”:

class Product < ApplicationRecord
  default_scope { where(deleted_at: nil) }

  def should_index?
    deleted_at.nil?
  end
end

若想索引并搜索被过滤的记录,设置:

searchkick unscope: true

智能搜索:让搜索越用越聪明

转化数据(Conversions)驱动排序

追踪搜索与转化是提升搜索质量性价比最高的起点,官方配套的 Searchjoy 负责埋点:

Product.search("apple", track: {user_id: current_user.id})

然后基于转化统计为搜索词加权——例如用户搜 ice cream 并把某款冰淇淋加入购物车,该商品在类似搜索中获得更高权重:

class Product < ApplicationRecord
  has_many :conversions, class_name: "Searchjoy::Conversion", as: :convertable
  has_many :searches, class_name: "Searchjoy::Search", through: :conversions

  searchkick conversions: [:conversions] # name of field

  def search_data
    {
      name: name,
      conversions: searches.group(:query).distinct.count(:user_id)
      # {"ice cream" => 234, "chocolate" => 67, "cream" => 2}
    }
  end
end

重新索引后,通过 cron 每日增量补充转化数据。为做到零停机部署,可在数据重建完成前临时在搜索调用中设置 conversions: false。

转化加权的底层实现是把转化字段建为 nested 映射(index_options.rb),查询侧通过嵌套 function_score + field_value_factor 按 query 命中数与 count 加权(query.rb)。

高性能转化方案:缓存列 + 局部重索引

为避免 N+1 查询,可把转化数据缓存到数据库列中。Postgres 迁移:

add_column :products, :search_conversions, :jsonb

MySQL 用 :json,其他数据库用 :text 配合 JSON 序列化器。

模型把转化数据独立成方法,配合局部重索引使用:

class Product < ApplicationRecord
  searchkick conversions: [:conversions]

  def search_data
    {
      name: name,
      category: category
    }.merge(conversions_data)
  end

  def conversions_data
    {
      conversions: search_conversions || {}
    }
  end
end

部署并全量重索引(期间同样建议临时 conversions: false),然后建一个每日任务:查询近期有转化的记录,批量更新缓存列并只重索引转化数据字段。仓库 README 给出了基于 Searchjoy 的 UpdateConversionsJob 完整实现(README.md),核心步骤为:按 created_at 筛选近期转化的 id → 每 1000 条一组 → 聚合出每个记录各查询词的独立用户数 → 事务内 update_all 更新 search_conversions → reindex(:conversions_data) 局部重建。

运行方式:

UpdateConversionsJob.perform_now("Product")
UpdateConversionsJob.perform_later("Product", since: 1.day.ago)

个性化结果

让不同用户看到不同排序,例如把用户买过的商品排前面:

class Product < ApplicationRecord
  def search_data
    {
      name: name,
      orderer_ids: orders.pluck(:user_id) # boost this product for these users
    }
  end
end

重索引后搜索:

Product.search("milk", boost_where: {orderer_ids: current_user.id})

即时搜索与自动补全(Autocomplete)

自动补全能显著加快搜索体验。注意:如果只有几千条记录,建议直接把数据载入 JavaScript 在客户端补全,比走网络请求快得多。

首先声明使用该功能的字段(自动补全会明显增大索引体积,但换来的是极速查询):

class Movie < ApplicationRecord
  searchkick word_start: [:title, :director]
end

重索引后按 word_start 匹配模式搜索:

Movie.search("jurassic pa", fields: [:title], match: :word_start)

前端可配合 typeahead.js 或 jQuery UI。Rails 集成方式:

1) 控制器动作:

class MoviesController < ApplicationController
  def autocomplete
    render json: Movie.search(params[:query], {
      fields: ["title^5", "director"],
      match: :word_start,
      limit: 10,
      load: false,
      misspellings: {below: 5}
    }).map(&:title)
  end
end

性能要点:load: false + misspellings: {below: n}(或 misspellings: false)。

2) 视图与 JavaScript:

<input type="text" id="query" name="query" />

<script src="jquery.js"></script>
<script src="typeahead.bundle.js"></script>
<script>
  var movies = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: '/movies/autocomplete?query=%QUERY',
      wildcard: '%QUERY'
    }
  });
  $('#query').typeahead(null, {
    source: movies
  });
</script>

搜索建议("Did you mean")

模型声明生成建议的字段:

class Product < ApplicationRecord
  searchkick suggest: [:name] # fields to generate suggestions
end

重索引后开启建议:

products = Product.search("peantu butta", suggest: true)
products.suggestions # ["peanut butter"]

建议功能的索引侧依赖 searchkick_suggest_shingle(最大 5 元 shingle,见 index_options.rb),查询侧在 payload<a href="https://link.gitcode.com/i/1633fdc4b252fd28aad4d6573dea2a0e" target="_blank">:suggest] 中为每个字段生成 phrase suggester([query.rb),结果按分数降序去重(results.rb)。

聚合统计(Aggregations)

聚合提供搜索数据的统计摘要(相当于 SQL GROUP BY):

products = Product.search("chuck taylor", aggs: [:product_type, :gender, :brand])
products.aggs

默认情况下,where 条件同样作用于聚合:

Product.search("wingtips", where: {color: "brandy"}, aggs: [:size])
# aggregations for brandy wingtips are returned

关闭该行为(聚合不再受 where 影响):

Product.search("wingtips", where: {color: "brandy"}, aggs: [:size], smart_aggs: false)
# aggregations for all wingtips are returned

为每个聚合单独设置 where:

Product.search("wingtips", aggs: {size: {where: {color: "brandy"}}})

限制桶数量:

Product.search("apples", aggs: {store_id: {limit: 10}})

排序(如按 key 字母序):

Product.search("wingtips", aggs: {color: {order: {"_key" => "asc"}}}) # alphabetically

自定义区间(价格区间):

price_ranges = [{to: 20}, {from: 20, to: 50}, {from: 50}]
Product.search("*", aggs: {price: {ranges: price_ranges}})

最小文档数过滤:

Product.search("apples", aggs: {store_id: {min_doc_count: 2}})

脚本支持:

Product.search("*", aggs: {color: {script: {source: "'Color: ' + _value"}}})

日期直方图:

Product.search("pear", aggs: {products_per_year: {date_histogram: {field: :created_at, interval: :year}}})

其他聚合类型(含子聚合)用 body_options 直接写 DSL:

Product.search("orange", body_options: {aggs: {price: {histogram: {field: :price, interval: 10}}}})

聚合的编译逻辑在 query.rb:数组形式会先转成 {field => {}},按 ranges/date_ranges/date_histogram/metric/terms 分支生成对应聚合体;默认 terms 桶大小 1000;smart_aggs 开启时会把与聚合字段冲突的全局过滤器移入 post_filter,保证聚合结果不受自身过滤条件影响。

高亮(Highlight)

模型声明需要高亮的字段:

class Band < ApplicationRecord
  searchkick highlight: [:name]
end

搜索时开启高亮:

bands = Band.search("cinema", highlight: true)

获取高亮片段:

bands.with_highlights.each do |band, highlights|
  highlights[:name] # "Two Door <em>Cinema</em> Club"
end

自定义标签:

Band.search("cinema", highlight: {tag: "<strong>"})

高亮与搜索使用不同字段:

Band.search("cinema", fields: [:name], highlight: {fields: [:description]})

默认高亮整个字段,需要小片段时设置 fragment_size 并开启 multiple:

bands = Band.search("cinema", highlight: {fragment_size: 20})
bands.with_highlights(multiple: true).each do |band, highlights|
  highlights[:name].join(" and ")
end

按字段细调高亮选项:

Band.search("cinema", fields: [:name], highlight: {fields: {name: {fragment_size: 200}}})

高亮字段需要在索引映射中开启 term_vector: "with_positions_offsets"(index_options.rb),查询侧组装 highlight 请求体(query.rb)。

相似推荐(Similar Items)

product = Product.first
product.similar(fields: [:name], where: {size: "12 oz"})

底层使用 more_like_this 查询,like 内容取当前记录的索引数据,见 index.rb 与 query.rb。

地理空间搜索

模型声明位置字段:

class Restaurant < ApplicationRecord
  searchkick locations: [:location]

  def search_data
    attributes.merge(location: {lat: latitude, lon: longitude})
  end
end

按距离范围搜索(半径可用 100mi 或 160km):

Restaurant.search("pizza", where: {location: {near: {lat: 37, lon: -114}, within: "100mi"}})

矩形包围盒(top_right / bottom_left 同样可用):

Restaurant.search("sushi", where: {location: {top_left: {lat: 38, lon: -123}, bottom_right: {lat: 37, lon: -122}}})

多边形包围:

Restaurant.search("dessert", where: {location: {geo_polygon: {points: [{lat: 38, lon: -123}, {lat: 39, lon: -123}, {lat: 37, lon: 122}]}}})

这些语法在 query.rb 映射为 geo_distance、geo_bounding_box、geo_polygon 过滤器。

按距离加权

Restaurant.search("noodles", boost_by_distance: {location: {origin: {lat: 37, lon: -122}}})

支持衰减函数完整参数:

Restaurant.search("wings", boost_by_distance: {location: {origin: {lat: 37, lon: -122}, function: "linear", scale: "30mi", decay: 0.5}})

Geo Shapes(图形)

索引图形数据:

class Restaurant < ApplicationRecord
  searchkick geo_shape: [:bounds]

  def search_data
    attributes.merge(
      bounds: {
        type: "envelope",
        coordinates: [{lat: 4, lon: 1}, {lat: 2, lon: 3}]
      }
    )
  end
end

相交查询:

Restaurant.search("soup", where: {bounds: {geo_shape: {type: "polygon", coordinates: [[{lat: 38, lon: -123}, ...]]}}})

完全包含(within):

Restaurant.search("salad", where: {bounds: {geo_shape: {type: "circle", relation: "within", coordinates: {lat: 38, lon: -123}, radius: "1km"}}})

不相交(disjoint):

Restaurant.search("burger", where: {bounds: {geo_shape: {type: "envelope", relation: "disjoint", coordinates: [{lat: 38, lon: -123}, {lat: 37, lon: -122}]}}})

geo_shape 查询的坐标会统一转换为 <a href="https://link.gitcode.com/i/7e6666fc4b381bcb38074f5e11918980" target="_blank">lon, lat] 顺序([query.rb)。

单表继承(STI)

class Dog < Animal
end

父模型开启继承支持:

class Animal < ApplicationRecord
  searchkick inheritance: true
end

父、子模型均可触发全量重索引:

Animal.reindex
Dog.reindex # equivalent, all animals reindexed

搜索范围控制:

Animal.search("*")                   # all animals
Dog.search("*")                      # just dogs
Animal.search("*", type: [Dog, Cat]) # just cats and dogs

两点注意:

  1. suggest 目前从父模型取建议——Dog.search("airbudd", suggest: true) 返回的是所有动物的建议;
  2. 该机制依赖自动写入文档的 type 字段,不要在 search_data 里自定义 type 字段,否则会覆盖它(查询侧对 type 的过滤见 query.rb)。

调试查询

Product.search("soap", debug: true)

会向 stdout 打印 Searchkick 版本、模型配置、查询选项、示例索引数据、映射与设置、最终发送的 curl 命令及服务端响应(见 query.rb 的 handle_response)。

查看服务端打分细节:

Product.search("soap", explain: true).response

用 tokens 方法观察分词结果,排查「为什么搜不到」:

Product.search_index.tokens("Dish Washer Soap", analyzer: "searchkick_index")
# ["dish", "dishwash", "washer", "washersoap", "soap"]

Product.search_index.tokens("dishwasher soap", analyzer: "searchkick_search")
# ["dishwashersoap"] - no match

Product.search_index.tokens("dishwasher soap", analyzer: "searchkick_search2")
# ["dishwash", "soap"] - match!!

部分匹配场景:

Product.search_index.tokens("San Diego", analyzer: "searchkick_word_start_index")
# ["s", "sa", "san", "d", "di", "die", "dieg", "diego"]

Product.search_index.tokens("dieg", analyzer: "searchkick_word_search")
# ["dieg"] - match!!

tokens 直接调用服务端的 _analyze API(index.rb)。分析器完整清单见 lib/searchkick/index_options.rb。

测试

迭代搜索功能时建议补充测试。出于性能考虑,只在需要的用例中开启 Searchkick 回调。

Rails 并行测试

Rails 6 默认开启并行测试,在 test/test_helper.rb 中为每个 worker 分配独立索引后缀并预建索引:

class ActiveSupport::TestCase
  parallelize_setup do |worker|
    Searchkick.index_suffix = worker

    # reindex models
    Product.reindex

    # and disable callbacks
    Searchkick.disable_callbacks
  end
end

用例写法:

class ProductTest < ActiveSupport::TestCase
  def setup
    Searchkick.enable_callbacks
  end

  def teardown
    Searchkick.disable_callbacks
  end

  def test_search
    Product.create!(name: "Apple")
    Product.search_index.refresh
    assert_equal ["Apple"], Product.search("apple").map(&:name)
  end
end

注意:写入后需要 Product.search_index.refresh 才能立即可见——因为搜索服务端是最终一致性的。

Minitest

# test/test_helper.rb
# reindex models
Product.reindex

# and disable callbacks
Searchkick.disable_callbacks

RSpec

# spec/spec_helper.rb
RSpec.configure do |config|
  config.before(:suite) do
    # reindex models
    Product.reindex

    # and disable callbacks
    Searchkick.disable_callbacks
  end

  config.around(:each, search: true) do |example|
    Searchkick.callbacks(nil) do
      example.run
    end
  end
end

Factory Bot

为每个索引模型定义 :reindex trait,并保证其位于 trait 列表末尾:

FactoryBot.define do
  factory :product do
    # ...

    # Note: This should be the last trait in the list so `reindex` is called
    # after all the other callbacks complete.
    trait :reindex do
      after(:create) do |product, _evaluator|
        product.reindex(refresh: true)
      end
    end
  end
end

# use it
FactoryBot.create(:product, :some_trait, :reindex, some_attribute: "foo")

CI:GitHub Actions

可用 ankane/setup-elasticsearch 与 ankane/setup-opensearch action 快速安装服务端:

    - uses: ankane/setup-elasticsearch@v1
    - uses: ankane/setup-opensearch@v1

部署

Searchkick 通过环境变量定位服务端:Elasticsearch 用 ENV<a href="https://link.gitcode.com/i/19260f8a872c263ab30081afe1f16a9d" target="_blank">"ELASTICSEARCH_URL"],OpenSearch 用 ENV["OPENSEARCH_URL"],默认 http://localhost:9200(见 [searchkick.rb 的客户端构造)。

Elastic Cloud

# config/initializers/elasticsearch.rb
ENV["ELASTICSEARCH_URL"] = "https://user:password@host:port"

部署后重索引:

rake searchkick:reindex:all

Heroku

可选 Bonsai、SearchBox 或 Elastic Cloud 插件。Bonsai(Elasticsearch):

heroku addons:create bonsai
heroku config:set ELASTICSEARCH_URL=`heroku config:get BONSAI_URL`

Bonsai(OpenSearch):

heroku addons:create bonsai --engine=opensearch
heroku config:set OPENSEARCH_URL=`heroku config:get BONSAI_URL`

SearchBox:

heroku addons:create searchbox:starter
heroku config:set ELASTICSEARCH_URL=`heroku config:get SEARCHBOX_URL`

Elastic Cloud(原 Found):

heroku addons:create foundelasticsearch
heroku addons:open foundelasticsearch

访问 Shield 页面重置密码后,把用户名密码拼进 URL(在 https:// 后加 elastic:password@,末尾加端口 9243):

heroku config:set ELASTICSEARCH_URL=https://elastic:password@12345.us-east-1.aws.found.io:9243

部署并重索引:

heroku run rake searchkick:reindex:all

Amazon OpenSearch Service

# config/initializers/opensearch.rb
ENV["OPENSEARCH_URL"] = "https://es-domain-1234.us-east-1.es.amazonaws.com:443"

使用签名请求时,在 Gemfile 增加:

gem "faraday_middleware-aws-sigv4"

并在初始化器中配置凭证:

Searchkick.aws_credentials = {
  access_key_id: ENV["AWS_ACCESS_KEY_ID"],
  secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],
  region: "us-east-1"
}

设置 aws_credentials 后会自动重置已构建的客户端(searchkick.rb)。

自建或其他

ENV["ELASTICSEARCH_URL"] = "https://user:password@host:port"
# or
ENV["OPENSEARCH_URL"] = "https://user:password@host:port"

数据保护

建议对静态数据与传输数据都加密(即使在内网),尤其是涉及用户个人信息时。Bonsai、Elastic Cloud、Amazon OpenSearch Service 均支持静态加密与 HTTPS。

自动故障转移

在 URL 中用逗号配置多个主机:

ENV["ELASTICSEARCH_URL"] = "https://user:password@host1,https://user:password@host2"
# or
ENV["OPENSEARCH_URL"] = "https://user:password@host1,https://user:password@host2"

客户端选项

Searchkick.client_options[:reload_connections] = true

client_options 会与默认配置 deep merge(searchkick.rb),完整选项参考 elasticsearch-ruby / opensearch-transport 文档。

Lograge 集成

把搜索耗时写入日志:

# config/environments/production.rb
config.lograge.custom_options = lambda do |event|
  options = {}
  options[:search] = event.payload[:searchkick_runtime] if event.payload[:searchkick_runtime].to_f > 0
  options
end

性能优化

更快的 JSON 生成:Oj

gem "oj"

Oj 会自动加速应用中所有 JSON 的生成与解析。

持久 HTTP 连接:Typhoeus

gem "typhoeus"

安装后自动启用。为减少日志噪音:

Ethon.logger = Logger.new(nil)

限定可搜索字段

默认所有字符串字段都可参与 fields 搜索,这会拖慢索引并撑大索引体积:

class Product < ApplicationRecord
  searchkick searchable: [:name]
end

限定可过滤字段

默认所有字符串字段都可被 where 过滤:

class Product < ApplicationRecord
  searchkick filterable: [:brand]
end

注意:非字符串字段始终可过滤,不要传给该选项。

并行重索引

大数据集用后台任务并行重建:

Product.reindex(mode: :async)
# {index_name: "products_production_20250111210018065"}

任务完成后提升新索引为线上别名:

Product.search_index.promote(index_name)

可选:用 Redis 跟踪状态:

Searchkick.redis = Redis.new
Searchkick.reindex_status(index_name)

也可以阻塞等待完成:

Product.reindex(mode: :async, wait: true)

用 activejob-traffic_control 控制并发:

gem "activejob-traffic_control", ">= 0.1.3"
ActiveJob::TrafficControl.client = Searchkick.redis

class Searchkick::BulkReindexJob
  concurrency 3
end

该示例限制同时最多运行 3 个 job。reindex_status 通过 Index#batches_left 读取剩余批次(searchkick.rb)。

刷新间隔

重索引期间调大刷新间隔提速(并行重索引时效果才明显):

Product.reindex(mode: :async, refresh_interval: "30s")

提升时恢复为映射中配置的值(默认 1s):

Product.search_index.promote(index_name, update_refresh_interval: true)

promote 的实现见 index.rb:通过别名切换完成零停机上线。

Queuing(入队式重索引)

把待更新记录的 id 推入队列、再批量重建。初始化 Redis(推荐 connection_pool):

Searchkick.redis = ConnectionPool.new { Redis.new }

模型切换到 queue 策略:

class Product < ApplicationRecord
  searchkick callbacks: :queue
end

后台任务处理队列:

Searchkick::ProcessQueueJob.perform_later(class_name: "Product")

查看队列长度:

Product.search_index.reindex_queue.length

Routing(路由)

routing 可显著加速搜索:

class Business < ApplicationRecord
  searchkick routing: true

  def search_routing
    city_id
  end
end

重索引并搜索:

Business.search("ice cream", routing: params[:city_id])

局部重索引(Partial Reindexing)

只重建部分字段,减少生成 search data 的时间与网络流量:

class Product < ApplicationRecord
  def search_data
    {
      name: name,
      category: category
    }.merge(prices_data)
  end

  def prices_data
    {
      price: price,
      sale_price: sale_price
    }
  end
end
Product.reindex(:prices_data)

高级用法

自定义映射(Advanced Mapping)

class Product < ApplicationRecord
  searchkick mappings: {
    properties: {
      name: {type: "keyword"}
    }
  }
end

注意:使用自定义映射后,搜索也必须使用自定义 DSL(body 选项),否则默认生成的查询无法匹配。

保留 Searchkick 生成的映射/设置,只在其上合并自定义部分:

class Product < ApplicationRecord
  searchkick merge_mappings: true, mappings: {...}
end

merge_mappings 的差异见 index_options.rb:未开启时直接用自定义配置替换生成结果;开启时用自定义配置 deep merge 到生成的映射/设置之上。

自定义搜索(Advanced Search)

直接使用服务端 DSL:

products = Product.search(body: {query: {match: {name: "milk"}}})
products.response

在 Searchkick 生成的查询基础上修改:

products = Product.search("milk", body_options: {min_score: 1})

或通过 block 修改请求体:

products =
  Product.search("apples") do |body|
    body[:min_score] = 1
  end

block 在请求体组装完成后执行(query.rb)。

直接访问客户端

Searchkick.client

Multi Search(批量搜索)

合并多个搜索请求以提升性能:

products = Product.search("snacks")
coupons = Coupon.search("snacks")
Searchkick.multi_search([products, coupons])

之后按普通结果使用 products 与 coupons。注意:multi search 不会像单请求那样抛错,需通过每个查询的 error 方法检查错误。实现见 multi_search.rb,其内部使用 msearch 接口并支持拼写纠错重试。

多模型搜索

Searchkick.search("milk", models: [Product, Category])

按模型加权:

indices_boost: {Category => 2, Product => 1}

indices_boost 在 query.rb 中被转换为 payload[:indices_boost]。

多租户

可参考 Apartment gem 搭配 Searchkick 的多租户实践,其他租户隔离 gem 也可沿用类似模式。

Scroll API

scroll 不面向实时用户请求,适合批量处理大量数据:

Product.search("*", scroll: "1m").scroll do |batch|
  # process batch ...
end

手动滚动:

products = Product.search("*", scroll: "1m")
while products.any?
  # process batch ...

  products = products.scroll
end

products.clear_scroll

scroll 在 results.rb 中实现:无块调用时返回下一批结果,块调用时循环取数并在结束后清除 scroll 上下文;scroll id 过期会抛出 Scroll id has expired。

深度分页

Elasticsearch 与 OpenSearch 默认把分页限制在前 10,000 条(含总数统计)。如确需全量结果:

class Product < ApplicationRecord
  searchkick deep_paging: true
end

若只需要准确的总数,则:

Product.search("pears", body_options: {track_total_hits: true})

deep_paging: true 会将默认 limit 放大到 10 亿并设置 track_total_hits(query.rb 与 track_total_hits?)。

嵌套数据

用点号访问嵌套字段:

Product.search("san", fields: ["store.city"], where: {"store.zip_code" => 12345})

最近邻搜索(k-NN)

适用于 Elasticsearch 8.6+ 与 OpenSearch 2.4+:

class Product < ApplicationRecord
  searchkick knn: {embedding: {dimensions: 3, distance: "cosine"}}
end

支持 euclidean 与 inner_product。重索引后按向量搜索:

Product.search(knn: {field: :embedding, vector: [1, 2, 3]}, limit: 10)

服务端版本不满足要求时会在建索引阶段直接报错(index_options.rb)。查询侧(query.rb)针对 Elasticsearch 与 OpenSearch 分别生成 knn 或 script_score(精确搜索)查询,且要求 knn 与关键词搜索混用时走 Searchkick.multi_search。

语义搜索(Semantic Search)

先给模型加上最近邻配置:

class Product < ApplicationRecord
  searchkick knn: {embedding: {dimensions: 768, distance: "cosine"}}
end

为每条记录生成向量(可借助外部服务或 Informers 等库):

embed = Informers.pipeline("embedding", "Snowflake/snowflake-arctic-embed-m-v1.5")
embed_options = {model_output: "sentence_embedding", pooling: "none"} # specific to embedding model

Product.find_each do |product|
  embedding = embed.(product.name, **embed_options)
  product.update!(embedding: embedding)
end

查询时同样生成查询向量(查询前缀依嵌入模型而定):

query_prefix = "Represent this sentence for searching relevant passages: "
query_embedding = embed.(query_prefix + query, **embed_options)

执行最近邻搜索:

Product.search(knn: {field: :embedding, vector: query_embedding}, limit: 20)

完整可运行示例见 examples/semantic.rb。

混合搜索(Hybrid Search)

关键词搜索与语义搜索并行执行:

keyword_search = Product.search(query, limit: 20)
semantic_search = Product.search(knn: {field: :embedding, vector: query_embedding}, limit: 20)
Searchkick.multi_search([keyword_search, semantic_search])

用 Reciprocal Rank Fusion(RRF)融合结果:

Searchkick::Reranking.rrf(keyword_search, semantic_search).first(5)

RRF 的分数计算为各排名中 1 / (k + rank) 之和(默认 k = 60),实现见 lib/searchkick/reranking.rb。

或使用重排序模型:

rerank = Informers.pipeline("reranking", "mixedbread-ai/mxbai-rerank-xsmall-v1")
results = (keyword_search.to_a + semantic_search.to_a).uniq
rerank.(query, results.map(&:name)).first(5).map { |v| results[v[:doc_id]] }

完整示例见 examples/hybrid.rb。

参考速查(Reference)

单条记录重索引:

product = Product.find(1)
product.reindex

多条记录:

Product.where(store_id: 1).reindex

关联重索引:

store.products.reindex

清理旧索引:

Product.search_index.clean_indices

自定义设置:

class Product < ApplicationRecord
  searchkick settings: {number_of_shards: 3}
end

自定义索引名:

class Product < ApplicationRecord
  searchkick index_name: "products_v2"
end

动态索引名:

class Product < ApplicationRecord
  searchkick index_name: -> { "#{name.tableize}-#{I18n.locale}" }
end

索引名前缀(单模型或全局):

class Product < ApplicationRecord
  searchkick index_prefix: "datakick"
end

Searchkick.index_prefix = "datakick"

转化加权术语覆盖:

Product.search("banana", conversions_term: "organic banana")

多个转化字段:

class Product < ApplicationRecord
  has_many :searches, class_name: "Searchjoy::Search"

  # searchkick also supports multiple "conversions" fields
  searchkick conversions: ["unique_user_conversions", "total_conversions"]

  def search_data
    {
      name: name,
      unique_user_conversions: searches.group(:query).distinct.count(:user_id),
      # {"ice cream" => 234, "chocolate" => 67, "cream" => 2}
      total_conversions: searches.group(:query).count
      # {"ice cream" => 412, "chocolate" => 117, "cream" => 6}
    }
  end
end

查询侧可分别控制:

Product.search("banana") # boost by both fields (default)
Product.search("banana", conversions: "total_conversions") # only boost by total_conversions
Product.search("banana", conversions: false) # no conversion boosting

超时设置:

Searchkick.timeout = 15 # defaults to 10
Searchkick.search_timeout = 3

修改搜索方法名:

Searchkick.search_method_name = :lookup

修改队列名:

Searchkick.queue_name = :search_reindex

结果预加载:

Product.search("milk", includes: [:brand, :stores])
Searchkick.search("*",  models: [Product, Store], model_includes: {Product => [:store], Store => [:product]})

结果上追加 scope:

Product.search("milk", scope_results: ->(r) { r.with_attached_images })

默认搜索字段:

class Product < ApplicationRecord
  searchkick default_fields: [:name]
end

关闭特殊字符归一化(A 将不再匹配 Ä):

class Product < ApplicationRecord
  searchkick special_characters: false
end

转化词干提取:

class Product < ApplicationRecord
  searchkick stem_conversions: true
end

大小写敏感(注意:默认开启拼写纠错时,单个字符大小写差异仍可能命中,如不需要请同时关闭 misspellings):

class Product < ApplicationRecord
  searchkick case_sensitive: true
end

导入批大小:

class Product < ApplicationRecord
  searchkick batch_size: 200 # defaults to 1000
end

只建索引不导入:

Product.reindex(import: false)

自定义文档 id:

class Product < ApplicationRecord
  def search_document_id
    custom_id
  end
end

请求参数(如 search_type):

Product.search("carrots", request_params: {search_type: "dfs_query_then_fetch"})

全局模型选项:

Searchkick.model_options = {
  batch_size: 200
}

条件重索引:

class Product < ApplicationRecord
  searchkick callbacks: false

  # add the callbacks manually
  after_commit :reindex, if: -> (model) { model.previous_changes.key?("name") } # use your own condition
end

重索引全部模型(Rails only):

rake searchkick:reindex:all

该任务会先 eager load 全部模型再逐个重索引(lib/tasks/searchkick.rake)。

按前缀长度开启拼写纠错:

Product.search("api", misspellings: {prefix_length: 2}) # api, apt, no ahi

注意:查询长度等于 prefix_length 时,Elasticsearch 7 与 OpenSearch 1 会关闭纠错:

Product.search("ah", misspellings: {prefix_length: 2}) # ah, no aha

BigDecimal 精度:默认按 float 索引(以便加权),如需完整精度转成字符串:

class Product < ApplicationRecord
  def search_data
    {
      units: units.to_s("F")
    }
  end
end

常见坑(Gotchas)

最终一致性

搜索服务端是最终一致的,写入后最多需要约 1 秒才能反映到搜索;需要立即可见时调用 refresh:

product.save!
Product.search_index.refresh

分数不稳定

分布式环境下文档数较少时,query_then_fetch 可能导致分数/结果不稳定。解决办法是单分片:

class Product < ApplicationRecord
  searchkick settings: {number_of_shards: 1}
end

测试环境默认已设置为单分片零副本(index_options.rb)。

小结

从安装接入、SQL 式查询、索引同步策略,到转化加权、自动补全、聚合统计、语义/混合搜索与生产部署调优,Searchkick 将 Elasticsearch / OpenSearch 的底层能力封装为高度易用的 Ruby API,同时保留 body / body_options 透传能力以应对复杂场景。文中涉及的实现细节均可在仓库源码中继续深入:查询编译见 lib/searchkick/query.rb,索引映射与分析器生成见 lib/searchkick/index_options.rb,索引生命周期管理见 lib/searchkick/index.rb,模型钩子见 lib/searchkick/model.rb。

登录后查看全文
searchkick