1

参考Query DSL Explained Tutorial Slides 14-15

如何展平嵌套对象?

我有一个命名的模型Entry和另一个命名的模型Category,它们共享一个 HABTM 关联。目前一切正常,搜索结果似乎正确,但我不知道我的映射是否正确。该教程说,当您展平对象时,文档将如下所示:

{
    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
4

0 回答 0