如何搜索包含搜索键中找到的字符串的数组?

时间:2017-10-30 02:31:47

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

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

首先,我必须将搜索键转换为字符串数组:

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

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

2 个答案:

答案 0 :(得分:2)

您只需使用@>(包含)运算符即可。

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">]> 

答案 1 :(得分:1)

好的,当您使用postgresql时,您可以使用gem pg_search

在模型中添加搜索范围:

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

有关详细信息,请查看documentation。干杯!