嵌套模型搜索Rails + Tire + ElasticSearch,索引问题

时间:2016-03-06 10:30:17

标签: ruby-on-rails elasticsearch tire

我有一个rails应用程序,它有Recipe模型,有几个多对多关联。我正在尝试构建一个高级搜索"使用ElasticSearch + Tire的功能(我知道gem已经退役)。过去几天我花了很少的运气来研究我做错了什么。这是我的食谱模型,此时适用于烹饪的自由文本搜索和过滤(也作为查询参数传递):

class Recipe < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  include Tire::Model::Search
  include Tire::Model::Callbacks

  belongs_to :chef
  belongs_to :cuisine

  has_many :recipecourses
  has_many :courses, through: :recipecourses

  has_many :recipeoccasions
  has_many :occasions, through: :recipeoccasions


  has_many :likes

  def thumbs_up_total
    self.likes.where(like: true).size
  end

  def thumbs_down_total
    self.likes.where(like: false).size
  end


  mapping do
    indexes :published_at, type: 'date'
     indexes :cuisine_id, type: 'integer'
     indexes :cuisine_name
     indexes :recipe_occasions

  end

  def self.search(params)
    tire.search( page: params[:page], per_page:4 ) do
      #query { string params[:query]} if params[:query].present?
      query do
        boolean do
          must { string params[:query]} if params[:query].present?
          must {string params[:cuisine_name]} if params[:cuisine_name].present? && !params[:cuisine_name].blank?
        end

      end
    end
  end


  def to_indexed_json
    to_json(methods: [:recipe_occasions,:cuisine_name,:thumbs_up_total, :thumbs_down_total, :chef_name, :chef_avatar, :mychef_path])
  end

  def recipe_occasions
    occasions.collect{|c| c.occasion_name}
  end


  def cuisine_name
    cuisine.cuisine_name
  end

  def chef_name
    chef.chefname
  end

  def chef_avatar
    chef.avatar.url
  end

  def mychef_path
    chef_path(chef)

  end

但是我想根据一些关联向filer添加复选框。例如,在我的搜索表单中,我将获得所有场合的列表,并根据所选的搜索将过滤该场合的唯一配方。

我尝试这样做只是为了测试,它产生0结果:

def self.search(params)
    tire.search( page: params[:page], per_page:4 ) do
      query { string params[:query]} if params[:query].present?
        filter :terms, :recipe_occasions => ['New Year']

    end
  end

我也尝试过滤字段,这是模型的一部分(cuisine_id),它的作用让我觉得我的索引搞砸了:

 def self.search(params)
    tire.search( page: params[:page], per_page:4 ) do
      query { string params[:query]} if params[:query].present?
        #filter :terms, :recipe_occasions => ['New Year']
        filter :terms, :cuisine_id => [6]
    end
  end

我已经阅读了轮胎文档以及关于堆栈溢出的几个类似问题,但老实说,我无法理解如何正确地进行索引编制。我注意到的另一个有趣的事情是我的搜索中的查询参数正在搜索to_indexed_json中指定的所有索引方法 - 例如,如果我在http请求中有参数cuisine = Chinese,而在我的to_indexed_json中我有:occasion_names恰好包含中国新年,即使菜肴不是中国菜,查询也将返回中国新年的食谱(我知道这个例子毫无意义,但这就是它的工作方式)。

回到索引问题如果有人可以解释如何正确地进行索引/映射,我会非常感激,这样我就可以在相关模型的字段上进行文件管理。

谢谢!

0 个答案:

没有答案