【问题标题】:How can I search for arrays that contain strings found in my search key? [duplicate]如何搜索包含在我的搜索键中找到的字符串的数组? [复制]
【发布时间】:2018-04-10 23:14:01
【问题描述】:

假设我有一个带有名为“名称”的 json 数组属性的 Product 表。例如,Product.first.name == ["large", "black", "hoodie"]。我想在我的数据库中搜索名称包含搜索查询中的单词的产品。因此,如果我输入“large hoodie”,结果中应该返回 Product.first。

所以首先我要把搜索键变成一个字符串数组:

def search
  search_array = params[:search].split(" ")
  results = #???

但是如何搜索名称中包含的值也包含在search_array 中的产品?我找到了有关如何在 数组中搜索值的文档,但没有找到有关如何搜索数组本身的文档。

【问题讨论】:

  • 列名是jsonb还是序列化文本?

标签: sql ruby-on-rails arrays ruby postgresql


【解决方案1】:

您可以简单地使用 @>(包含)运算符。

select * from products;
 id |  name   |              tags              |         created_at         |         updated_at         
----+---------+--------------------------------+----------------------------+----------------------------
  3 | T-Shirt | {clothing,summer}              | 2017-10-30 05:28:19.394888 | 2017-10-30 05:28:19.394888
  4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(2 rows)


select * from products where tags @> '{large, hoodie}';
 id |  name   |              tags              |         created_at         |         updated_at         
----+---------+--------------------------------+----------------------------+----------------------------
  4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(1 row)

或者,作为 AR 查询,

2.3.1 :002 > Product.where("tags @> '{large, hoodie}'")
  Product Load (0.4ms)  SELECT "products".* FROM "products" WHERE (tags @> '{large, hoodie}')
 => #<ActiveRecord::Relation [#<Product id: 4, name: "Sweater", tags: ["clothing", "winter", "large", "hoodie"], created_at: "2017-10-30 05:28:38", updated_at: "2017-10-30 05:28:38">]> 

【讨论】:

【解决方案2】:

好的,既然你使用的是postgresql,那么你可以使用gem pg_search

在模型中添加搜索范围:

include PgSearch
pg_search_scope :search_on_text_columns,
                 against: %i(name),
                 using: { tsearch: { prefix: true } }

更多详情请查看documentation。干杯!

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2012-09-01
    • 2021-07-09
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多