【问题标题】:Searching multiple models with Searchkick使用 Searchkick 搜索多个模型
【发布时间】:2018-08-28 02:57:21
【问题描述】:

我正在开发一个 Rails 5 和 Searchkick 项目,该项目具有搜索功能以及搜索多个模型的过滤器。例如,我有加入的大学和州立模型。我希望能够在 College 模型中搜索特定的校园环境,并在 State 模型中搜索特定的州。我希望查询使用 AND 运算符,而不是 OR,但到目前为止,我只能在以前的 Searchkick 问题中找到有关使用 OR 的信息。到目前为止,我想出的是:

@results = College.search "*", index_name: [College, State], where: {_and: [{_type: "college", campus_setting: 21}, {_type: "state", state: "Massachusetts"}]}

理想情况下,我将构建一个包含所有 where 条件的哈希,例如:

where:{
  {_type: "college", campus_setting: 21},
  {_type: "state", state: "Massachusetts"}
}

然后将where条件传递给搜索:

@results = College.search "*", index_name: [College, State], where: [where]

但这不会返回任何结果,即使我可以直接查询我的数据库并获得结果。

在 SQL 中,我的查询如下所示:

SELECT * FROM colleges c
INNER JOIN states s
ON c.state_id = s.id
WHERE c.campus_setting = 21 AND s.state = 'Massachusetts';

是否有其他方法可以编写此搜索,或者此功能不可用?我能找到的最接近的东西在这里:https://github.com/ankane/searchkick/issues/904

【问题讨论】:

    标签: ruby-on-rails-5 searchkick


    【解决方案1】:

    实际上 searchkick 提供了执行多模型搜索的工具,请查看此处的文档:https://github.com/ankane/searchkick#multi-search

    以及提供的示例:

    fresh_products = Product.search("fresh", execute: false)
    frozen_products = Product.search("frozen", execute: false)
    Searchkick.multi_search([fresh_products, frozen_products])
    

    如果你使用不同的模型,你可以使用:

    fresh_products = Product.search("apples", execute: false)
    frozen_products = FrozenProduct.search("ice", execute: false)
    Searchkick.multi_search([fresh_products, frozen_products])
    

    也可以通过looking at the tests 找到一些指导。

    【讨论】:

    • 感谢您的回复!我使用的是两个不同的模型,而不是同一个模型。
    • @AndreaS 查看更新后的答案...我以为您可以尝试一下 ;)
    • Multi_search 用于批量搜索请求以提高性能,不会同时搜索两个模型。
    【解决方案2】:
    Searchkick.search "mike", models: [Video, Image]
    

    使用更高级的选项进行搜索 -

    Searchkick.search "mike", { fields: ["slug^5", "title", "about"], misspellings: {below: 5, edit_distance: 2}, models: [Video, Image]}
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多