NoMethodError (undefined метод `highlight 'для # <Elasticsearch:: Model:: Response:: Результат>
Я собираюсь использовать эластичный поиск моего проекта ruby on rails. Я получаю эту ошибку, когда искал слово, которое слишком сильно использовал в моей статье.
NoMethodError (undefined method `highlight' for #<Elasticsearch::Model::Response::Result:0x007f062ed26708>)
Я получил это в журнале. это то, что я сделал:
в контроллере:
# POST /search/article
def search
render json: Article.search(params[:query]), each_serializer: ElasticsearchResultsSerializer
end
это моя модель article.rb
#default_scope { order('created_at DESC') }
scope :visible, -> { where(enabled: true) }
after_commit on: [:create] do
self.keywords = self.keywords.each {|str| str.force_encoding("UTF-8")}
__elasticsearch__.index_document if self.enabled?
end
after_commit on: [:update] do
self.keywords = self.keywords.each {|str| str.force_encoding("UTF-8")}
__elasticsearch__.update_document if self.enabled?
end
after_commit on: [:destroy] do
__elasticsearch__.delete_document
end
settings index: { number_of_shards: 1, number_of_replicas: 0 }
mappings dynamic: 'false' do
indexes :content, type: "string", index_options: 'offsets'
indexes :title, type: "string"
indexes :description, type: "string"
indexes :category, type: "string"
indexes :created_at, type: "date"
indexes :keywords, type: "string"
end
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fields: ['title^10', 'content^5', 'description^2', 'keywords', 'category']
}
},
highlight: {
pre_tags: ['<em>'],
post_tags: ['</em>'],
fields: { title: {}, content: {} }
}
}
)
end
def as_indexed_json(options={})
as_json(
only: [:content, :title, :id, :category, :keywords, :description]
)
end
а также я использовал сериализатор
class ElasticsearchResultsSerializer < ActiveModel::Serializer
attributes :_id, :highlight, :_score, :_source
def _source
@article = object._index.singularize.capitalize.constantize.find(object._id)
@serializer = "#{object._index.singularize.capitalize}Serializer".constantize
@serializer.new(@article)
end
end
Ответы
Ответ 1
Может быть, это глупое наблюдение, но вы пытались изменить значение
:highlight
до :_highlight
?
class ElasticsearchResultsSerializer < ActiveModel::Serializer
attributes :_id, :_highlight, :_score, :_source
def _source
@article = object._index.singularize.capitalize.constantize.find(object._id)
@serializer = "#{object._index.singularize.capitalize}Serializer".constantize
@serializer.new(@article)
end
end
Ответ 2
Я бы попытался переключить поля на:
fields: {
:"*" => {}
}
Просто чтобы узнать, избавится ли от этой ошибки. См. Следующее: https://github.com/elastic/elasticsearch-rails/issues/446