2015-04-22 2 views
3

Fondamentalement, j'ai eu 3 modèles (Livre, Chapitre, Auteur), et je veux inclure certains des livres et des attributs de l'auteur lors de l'indexation chapitre.rails élastique recherche relation attributs non indexés

ici est mon Chapter.rb

class Chapter < ActiveRecord::Base 
    belongs_to :book, :counter_cache => true 
    include Elasticsearch::Model 

    index_name [Rails.env, model_name.collection.gsub(/\//, '-')].join('_') 

    mappings do 
     indexes :id, type: :integer 
     indexes :title, type: :string 
     indexes :description, type: :string 
     indexes :content, type: :string 
     indexes :updated_at, type: :date # Date example 
     indexes :book_title 
     indexes :book_type 
     indexes :author_name 
     indexes :book_id 
    end 

    def book_title 
    book.title 
    end 
    def book_type 
    book.book_type 
    end 
    def author_name 
    " #{book.author.firstname} #{book.author.lastname} " 
    end 

    def to_indexed_json 
    to_json methods: [:book_title, :book_type, :author_name] 
    end 
end 

http://localhost:9200/development_chapters/_mapping?pretty montre correcte cartographie

{ 
    "development_chapters" : { 
    "mappings" : { 
     "chapter" : { 
     "properties" : { 
      "author_name" : { 
      "type" : "string" 
      }, 
      "book_title" : { 
      "type" : "string" 
      },.... 
     } 
     } 
    } 
    } 
} 

Alors, pourquoi dois-je pas eu author_name, BOOK_TITLE etc ... dans les résultats de recherche

<Elasticsearch::Model::Response::Result:0x00000105e393a0 @result=#<Hashie::Mash _id="415" _index="development_chapters" _score=1.0 _source=#<Hashie::Mash book_id=153 content="[\"Explicabo accusantium odit .\"]" created_at="2015-04-22T18:43:58.586Z" description="You can't generate the application without quantifying the cross-platform SDD bandwidth!" id=415 title="Future Communications Orchestrator" updated_at="2015-04-22T18:43:58.586Z"> _type="chapter">> 

Répondre

6

Vous définissez une méthode de sérialisation incorrecte. Elasticsearch::Model recherche la méthode as_indexed_json et vous définissez to_indexed_json. En bijou elasticesearch-modèle que vous pouvez trouver des exemples https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb#L82

Il devrait ressembler à ceci:

def as_indexed_json(options = {}) 
    as_json methods: [:book_title, :book_type, :author_name] 
end 
+0

Changé, maintenant je reçois ceci: ArgumentError: nombre incorrect d'arguments (1 pour 0) de/Utilisateurs /mac/RubymineProjects/ESAA/app/models/chapter.rb:52:in 'as_indexed_json ' – Richardlonesteen

+1

' as_indexed_json' prend un hash d'options donc devrait être 'def as_indexed_json (options = {})' – Shadwell

+0

@Shadwell merci vous avez raison, merci :) – edariedl