Rails:我可以一起使用elasticsearch-model和active_model_serializers吗?

时间:2017-01-15 18:21:51

标签: ruby-on-rails json ruby elasticsearch active-model-serializers

我在Rails中构建JSON API,我想使用Elasticsearch来加快响应并允许搜索。

我刚刚为我的第一个模型实现了elasticsearch-rails Gem,我可以从控制台成功查询ES。

现在我想向API消费者提供结果,例如对/articles/index.json?q="blah"的GET请求;将从ES检索匹配的文章并根据JSON:API标准进行渲染。

是否可以使用rails active_model_serializers gem来实现这一目标?我问,因为那里(与jbuilder相反)JSON:API格式已经被处理。

编辑:我现在站在这里:

在我的模型中,我有以下内容:

require 'elasticsearch/rails'
require 'elasticsearch/model'
class Thing < ApplicationRecord
    validates :user_id, :active, :status, presence: true
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks

    index_name Rails.application.class.parent_name.underscore
    document_type self.name.downcase

    settings index: { number_of_shards: 1, number_of_replicas: 1 } do 
        mapping dynamic: 'strict' do 
            indexes :id, type: :string
            indexes :user_id, type: :string
            indexes :active, type: :boolean
            indexes :status, type: :string
        end 
    end

    def as_indexed_json(options = nil)
      self.as_json({
        only: [:id, :user_id, :active, :status],
      })
    end

    def self.search(query) 
        __elasticsearch__.search( { 
            query: { 
                multi_match: { 
                    query: query, 
                    fields: ['id^5', 'user_id'] 
                } 
            }
        } )
    end
end

这可以正确地索引ES中的模型,并可以搜索ES索引。 在我的控制器中,我有:

class ThingsController < ApplicationController
    def index
        things = Thing.search(params[:query]).results.map{|m| m._source}
        render json: things, each_serializer: ThingSerializer
    end
end

目前,在序列化程序中,有以下内容:

class ThingSerializer < ActiveModel::Serializer
    attributes :id, :user_id, :active, :status
end

这很遗憾地在视图中显示以下JSON:

{"data":[{"id":"","type":"hashie-mashes","attributes":{"user-id":null,"active":null,"status":null}}]}

因此序列化程序无法正确解析结果,该结果从ES gem包装到此Hashie :: Mash对象中。

1 个答案:

答案 0 :(得分:4)

我终于设法让它工作得很好,而不需要从数据库中获取记录。以下是未来googlers的完整解决方案:

Serializer(可能更适合为搜索结果创建一个专用的):

class SearchableThingSerializer < ActiveModel::Serializer
  type 'things' # This needs to be overridden, otherwise it will print "hashie-mashes"
  attributes :id # For some reason the mapping below doesn't work with :id

  [:user_id, :active, :status].map{|a| attribute(a) {object[:_source][a]}}

  def id
    object[:_source].id
  end
end

控制器:

def index
  things = Thing.search(params[:query])
  render json: things, each_serializer: SearchableThingSerializer
end

使用此功能,您可以按照本指南中的说明构建JSON API,还可以直接从Elasticsearch提供数据:

https://www.simplify.ba/articles/2016/06/18/creating-rails5-api-only-application-following-jsonapi-specification/

相关问题