【问题标题】:Searchkick - Autocomplete with multiple models & fieldsSearchkick - 具有多个模型和字段的自动完成
【发布时间】:2023-03-06 08:18:01
【问题描述】:

Searchkick - 具有多个模型和字段的自动完成

我正在努力为与我的Post 模型关联的多个模型实现autocomplete functionality。搜索功能工作正常并返回预期数据。如果我按照documentation 中的方式实现它,我的自动完成方法也可以正常工作(但仅适用于帖子的标题)。

我还尝试通过将Post.index.name 切换为Post.searchkick_index.name 来尝试this answer 和这个one,但不显示自动完成功能。

这是我在posts_controller.rb写的代码:

def autocomplete
    render json: Post.search(params[:query],
                             index_name: [
                               Post.searchkick_index.name,
                               Tag.searchkick_index.name,
                               User.searchkick_index.name
                              ],
                             limit: 10,
                             load: false,
                             misspellings: { below: 5 })
end

我也试过了:

def autocomplete
  render json: Searchkick.search(params[:query],
                                 models: [Post, Tag, User],
                                 limit: 10,
                                 load: false,
                                 misspellings: { below: 5 })
end

上面的代码没有错误,但自动完成功能也不起作用。

post.rb:

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
  has_many :posts_tags, dependent: :destroy
  has_many :tags, through: :posts_tags

  searchkick word_start: %i[title]

  def search_data
    {
      title: title,
      description: description,
      user: user.full_name
    }.merge(
      tag: tags.map(&:title),
      comments: comments.map(&:description)
    )
  end
end

按照答案部分的建议,我还尝试了以下方法:

def autocomplete
  posts = Post.search(params[:query], execute: false)
  tags = Tag.search(params[:query], execute: false)
  users = User.search(params[:query], execute: false)

  render json: Searchkick.multi_search([posts, tags, users])
end

这将返回以下错误:fatal - exception reentered

我希望能够自动完成帖子的 title、标签的 title 和用户的 full_name。我应该如何更改我的代码?

提前谢谢你!

【问题讨论】:

    标签: ruby-on-rails elasticsearch autocomplete typeahead.js searchkick


    【解决方案1】:

    来自searchkick的multi_search

    posts = Post.search(params[:query], execute: false)
    tags = Tag.search(params[:query], execute: false)
    users = User.search(params[:query], execute: false)
    
    Searchkick.multi_search([posts, tags, users])
    

    【讨论】:

    • 我收到此错误:undefined method 'search' for #&lt;Class:0x000000000c4db258&gt; 对于此行:tags = Tag.search(params[:query], execute: false)。我应该在我的 Tag 模型中添加 searchkick 吗?
    • 好的,我将searchkick 添加到我的标签和用户模型中,但我现在收到以下错误:fatal - exception reentered:
    猜你喜欢
    • 2015-04-22
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2020-01-23
    • 2016-05-06
    • 2019-04-27
    相关资源
    最近更新 更多