Elasticsearch:按轮胎宝石分组过滤

时间:2012-08-04 18:33:37

标签: ruby-on-rails-3 elasticsearch tire

我想按年龄段过滤搜索。

现在我有: 的 program.rb

class Program < ActiveRecord::Base
  has_many :age_groups, through: :programs_age_groups_relations
  include Tire::Model::Search
  include Tire::Model::Callbacks
  mapping do
    indexes :name, analyzer: 'snowball', boost: 100
    indexes :description, analyzer: 'snowball'
    indexes :age_groups do
      indexes :name, analyzer: 'snowball'
    end
  end

  def to_indexed_json
    to_json(include: {age_groups: {only: :name}})
  end
  def self.search(params, options={})
    tire.search(load: {include: 'age_groups'}) do
      query do
        boolean do
          must { string params[:name_query] } if params[:name_query].present?
        end
      end

    filter do
      boolean do
        if params[:age_groups].present?
          params[:age_groups].each do |ag_name|
            must { string ag_name }
          end
        end
      end
    end
  end
end

index.html.haml

= form_tag programs_path, method: :get do |f|
  = text_field_tag :name_query, params[:name_query]
  - AgeGroup.all.each do |ag|
    = check_box_tag 'age_groups[]', ag.name, params[:age_groups].include?(ag.name)
控制器中的

@programs = Program.search(params)

年龄组:

AgeGroup.create([{name: 'Baby'}, {name: 'Toddler'}, {name: 'Preschoolers'}, {name: 'Elementary'}, {name: 'Middle School'}])

维吾尔:

class ProgramsAgeGroupsRelation < ActiveRecord::Base
  attr_accessible :age_group_id, :program_id
  belongs_to :age_group
  belongs_to :program
end

当我在搜索表单中检查一个或多个age_groups时,搜索结果没有发生任何事情。

如何正确使用轮胎完成此任务?

1 个答案:

答案 0 :(得分:2)

我不确定我理解您的问题,但请查看此StackOverflow答案:Elasticsearch, Tire, and Nested queries / associations with ActiveRecord以获取有关ActiveRecord与Tire关联的信息。

一旦你解决了这个问题,请更新你的问题,因为“搜索结果没有发生任何事情”提示某种失败的期望,但我不知道哪一个。