[英]Elasticsearch-model - trying to reference parent data to add to index
我正在使用带有导轨的 elasticsearch 在类似 twitter 的提要上实现实时搜索功能。 我有一个存储在 Postgres 中的User表和Post表。 我只想索引 ES 中的Post表进行搜索,但是我想要每个帖子的用户数据,这样我就可以显示谁发了帖子,他们的排名是什么等。所以基本上我想加入用户和帖子数据,然后将其索引到 elasticsearch。 现在,我的帖子model 看起来像这样:
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
我的用户model 看起来像这样:
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 上执行 elasticsearch 查询时,它返回的每个Post都是一个 object,如下所示:
{ "id": x , "title": "y" , "description": "z", "image": "", "vouches": 0, "user_id": 1}
我希望能够将相关用户 object 或用户数据存储在每个帖子 object 中 - 而不仅仅是 user_id。 理想情况下,我希望看到与此类似的 object帖子:
{ "id": x , "title": "y" , "description": "z", "image": "", "vouches": 0, "user_id": 1, "username": "a", "rank": 0...etc}
我觉得这应该发生在model的某个地方,但我在尝试使用嵌套映射时没有成功。
所以我能够使用 elasticsearch-models 中的 'as_indexed_json' 方法解决这个问题。 我只是将它放在映射下的 Post model 中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.