我有一个 Mongoid
模型,我对其执行 ElasticSearch
搜索查询。非常标准:
class ActivityLog
include Mongoid::Document
include Mongoid::Timestamps
include Tire::Model::Search
include Tire::Model::Callbacks
field :extra, type: Hash
belongs_to :user, :inverse_of => :activity_logs
def self.search(params, user)
tire.search(load: true, page: params[:page], per_page: 5) do
query { string params[:query], default_operator: "AND" } if params[:query].present?
sort { by :created_at, "desc" }
end
end
我很难理解 documentation关于如何做更高级的事情,目前我被困在如何处理我的搜索查询中,即搜索应该仅限于仅属于用户的 ActivityLog
对象。
谁能告诉我如何将 user._id 匹配要求应用到搜索查询中?
最佳答案
使用 ElasticSearch,有 2 个部分:映射和搜索
所以,如果你想通过关联表(users表)的某个字段来查找,对吧。有很多方法,但我经常在我的项目中使用这个方法:
ActivityLog
模型内部
mapping do
indexes :id, type: 'integer'
indexes :name, type: 'string', analyzer: 'snowball', boost: 5
indexes :description, type: 'string', analyzer: 'snowball'
indexes :description_latin, as: 'description.sanitize', type: 'string', analyzer: 'snowball'
indexes :user_id, as: 'user.id', type: 'string', index: :not_analyzed
indexes :user_name, as: 'user.name', type: 'string'
indexes :created_at, type: 'date'
indexes :slug, index: :not_analyzed
indexes :publish, type: 'boolean', index: :not_analyzed
end
通知user_id
和user_name
,上面定义的映射方法会将user.id
映射到user_id
和 user.name
到 user_name
。
所以现在在搜索方法中,你可以做一些类似的代码,比如
过滤器:terms, user_id: params[:search][:user_id]
希望对你有帮助
关于ruby-on-rails - 如何仅对特定用户的记录执行 ElasticSearch 查询(Rails Tire gem),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19381199/