【问题标题】:Elasticsearch-model - trying to reference parent data to add to indexElasticsearch-model - 尝试引用父数据以添加到索引
【发布时间】:2020-08-13 19:33:46
【问题描述】:

我正在使用带有 rails 的 elasticsearch 在类似 twitter 的提要上实现实时搜索功能。我有一个存储在 Postgres 中的 User 表和一个 Post 表。我只想索引 ES 中的 Post 表进行搜索,但是我想要每个帖子的 User 数据,这样我就可以显示谁发了帖子,他们的排名是多少等. 所以本质上我想加入 UserPost 数据,然后将其索引到 elasticsearch 中。现在,我的 Post 模型如下所示:


class Post < ApplicationRecord
  belongs_to :user

  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  index_name Rails.application.class.parent_name.underscore

  settings index: { number_of_shards: 1 } do    
    mapping dynamic: false do
        indexes :title, analyzer: 'english'
        indexes :description, analyzer: 'english'
    end
  end

  def self.search(query)
    __elasticsearch__.search(
    {
        query: {
          multi_match: {
          query: query,
          type: 'phrase',
          fields: ['title^5', 'description']
        },
    }
    )
  end

我的 User 模型如下所示:

class User < ApplicationRecord
    has_many :posts
end

我的架构如下所示:

ActiveRecord::Schema.define(version: 2020_04_16_175351) do
  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "image"
    t.integer "vouches"
    t.bigint "user_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "username"
    t.integer "rank"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  add_foreign_key "posts", "users"
end

当我在 localhost:9200 上进行弹性搜索查询时,它返回的每个 Post 都是一个如下所示的对象:

{ "id": x , "title": "y" , "description": "z", "image": "", "vouches": 0, "user_id": 1}

我希望能够将相关的用户对象或用户数据存储在每个帖子对象中 - 而不仅仅是 user_id。理想情况下,我希望看到一个类似于此的 Post 对象:

{ "id": x , "title": "y" , "description": "z", "image": "", "vouches": 0, "user_id": 1, "username": "a", "rank": 0...etc}

我觉得这应该发生在某个地方的 Post 模型中,但我尝试在其他模型中使用嵌套映射没有成功。

【问题讨论】:

    标签: ruby-on-rails elasticsearch elasticsearch-model


    【解决方案1】:

    所以我能够使用 elasticsearch-models 中的 'as_indexed_json' 方法解决这个问题。我只是将它放在映射下的 Post 模型中。

    def as_indexed_json(options = {})
      self.as_json(
        options.merge(
          only: [:id, :title, :body, :published_at, :created_at, :updated_at],
          include: { user: { only: [:id, :name] } }
        )
      )
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多