Elasticsearch / Tire - 展平嵌套对象

时间:2013-02-23 01:24:57

标签: ruby-on-rails mapping elasticsearch tire

参考Query DSL Explained Tutorial Slides 14-15

如何展平嵌套对象?

我有一个名为Entry的模型和另一个名为Category的模型,它们共享一个HABTM关联。 一切都在工作,搜索结果似乎是正确的,但我不知道我的映射是否正确。该教程说,当你展平对象时,Document将如下所示:

{
    tweet      => "Perl is GREAT!",
    posted     => "2011-08-15",
    user.name  => "Clinton Gormley",
    user.email => "drtech@cpan.org",
    tags       => ["perl","opinion"],
    posts      => 2,
}

对象user被夷为平地。当我查看我的JSON文档的源代码时,它看起来像这样:

{
"title":"First",
"description":"first test",
"categories":
    {"categories_name":"CAP and Using the CAP website"},
"attachment":"VEVTVCE=\n",
"published":true
}

所以,我假设它应该说categories.categories_name,但我不知道如何指定或者甚至是必要的。这是一些模型代码:

class Entry < ActiveRecord::Base

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

  has_and_belongs_to_many :categories

  mount_uploader :doc, EntryDocUploader

  tire.mapping do
      indexes :title  
      indexes :description
      indexes :categories do
        indexes :categories_name, type: 'string', index: 'not_analyzed'
      end
      indexes :attachment, :type => 'attachment', 
                    :fields => {
                    :title    => { :store => 'yes' },
                    :attachment     => { :term_vector => 'with_positions_offsets', :store => 'yes' }
                    }
  end

 def to_indexed_json
    {
    :title          => title,
    :description    => description,
    :categories     => {:categories_name => cats}, #categories.map { |c| { :categories_name => c.name}}.to_sentence,
    :attachment      => attachment,
    }.to_json
  end

  def self.search(params)
    tire.search(load: true) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      filter :term, :published => "true"
    end
  end

  def cats
    categories.map(&:name).to_sentence
  end

end

0 个答案:

没有答案