has_and_belongs_to_many的Searchkick聚合

时间:2016-08-17 11:13:20

标签: ruby-on-rails ruby ruby-on-rails-4 elasticsearch

我有一个Rails 5应用,我正在尝试对has_and_belongs_to_many关联进行聚合搜索。

这是我到目前为止的代码:

event.rb:

class Event < ApplicationRecord
  searchkick text_start: [:title]

  has_and_belongs_to_many :services
  has_and_belongs_to_many :sectors

  def search_data
    atributes.merge(
      title: title,
      description: description,
      sector_name: sectors.map(&:name),
      service_name: services.map(&:name)
    )
  end

end

events_controller.rb:

def index
  query = params[:j].presence || "*"
  conditions = {}
  conditions[:sector] = params[:sector] if params[:sector].present?
  conditions[:service] = params[:service] if params[:service].present?
  conditions[:date] = params[:date] if params[:date].present?
  @events = Event.search query, where: conditions, aggs: [:sector, :service, :date], order: {created_at: {order: "desc"}}, page: params[:page], per_page: 10
end

当我在控制台中呼叫Event.reindex时,我希望显示某些扇区和服务已编入索引,但它无法正常工作。

说实话,我已经迷失了,并且在圈子里走了一圈,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

这是最终为我工作的代码:

event.rb:

def index
    query = params[:j].presence || "*"
    conditions = {start_date: {"gte": "now/d"}}
    conditions[:sector_name] = params[:sector_name] if params[:sector_name].present?
    conditions[:service_name] = params[:service_name] if params[:service_name].present?
    conditions[:start_date] = params[:start_date] if params[:start_date].present?
    @events = Event.search query, where: conditions, aggs: [:sector_name, :service_name], order: {start_date: {order: "asc", unmapped_type: "long"}}, page: params[:page], per_page: 10
end

events_controller.rb:

def search_data
  {
    title: title,
    location: location,
    description: description,
    start_date: start_date,
    sector_name: sectors.map(&:name),
    service_name: services.map(&:name)
  }
end