简体   繁体   English

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

[英]How to perform ElasticSearch query on records from only a certain user (Rails Tire gem)

I have a Mongoid model which I perform ElasticSearch search queries on. 我有一个Mongoid模型,我执行ElasticSearch搜索查询。 Very standard: 非常标准:

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

I am having a hard time understanding the documentation on how to do more advanced stuff, and currently I'm stuck in how to work into my search query that search should be restricted to ActivityLog objects that belongs to the user only. 我很难理解有关如何更高级的东西的文档 ,目前我陷入了如何处理我的搜索查询,搜索应限制为仅属于用户的ActivityLog对象。

Could anyone show me how to work the user._id match requirement into the search query? 有谁能告诉我如何将user._id匹配要求用于搜索查询?

Working with ElasticSearch, there are 2 parts: mapping and search 使用ElasticSearch,有两个部分:映射和搜索

So, if you want to search by a field of association table (users table), right. 所以,如果你想通过一个关联表(用户表)来搜索,那就对了。 There are many ways, but this one I often use for my project: 有很多方法,但这个我经常用于我的项目:

Inside the ActivityLog model 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

Notify the user_id and user_name , the above definition of mapping method will map the user.id to the user_id , and user.name to user_name . 通知user_iduser_name ,上面的映射方法定义将user.id映射到user_id ,将user.name映射到user_name

So now in search method, you can do some similar code like filter :terms, user_id: params[:search][:user_id] 所以现在在搜索方法中,你可以做一些类似的代码,比如filter :terms, user_id: params[:search][:user_id]

Hope this help 希望这有帮助

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM