如何仅对特定用户(Rails Tire gem)的记录执行ElasticSearch查询

时间:2013-10-15 12:24:34

标签: ruby-on-rails elasticsearch tire

我有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匹配要求用于搜索查询吗?

2 个答案:

答案 0 :(得分:0)

使用ElasticSearch,有两部分:映射和搜索

所以,如果你想通过关联表(用户表)搜索,那就对了。有很多方法,但我经常用于我的项目:

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_iduser_name,上述映射方法定义会将user.id映射到user_iduser.name映射到user_name }。

所以现在在搜索方法中,你可以做一些类似的代码 filter :terms, user_id: params[:search][:user_id]

希望这个帮助

答案 1 :(得分:0)

对上述内容进行了一处更正,ElasticSearch删除了类型字符串,现在使用了文本。