Hstore 查询以在 rails 上使用 ruby 查找与任何数组元素匹配的记录

Hstore Query to find records matching with any array element using ruby on rails

我在数据库 table 中有一个 hstore 字段。我想编写一个查询来查找与 hstore 字段的任何哈希中的任何数组元素匹配的记录,使用 rails.

上的 ruby
 Users Table
 --------------------------------------------------------------------------------
        ID    Name    sectors(hstore) 

        1     Piotr   {"aviation"=>"0", "oil_and_gas" => "50", "transport" => "50"}
        2     reza    {"oil_and_gas" => "70", "energy" => "30"}
        3     pat     {"transport" => "40", "energy" => "60"}
        4     Kim     {"infrastructure" => "20", "healthcare" => "20", "industrial" => "60"}

考虑到以上测试数据,我想在 hstore 字段上编写一个查询,以获取所有具有任何键的记录,如 ['oil_and_gas'、'energy'、'transport']

我可以匹配和查找单个扇区记录,如 https://nandovieira.com/using-postgresql-and-hstore-with-rails 中所述,但我的要求是找到任何记录,其中 hstore 哈希具有与数组的任何一个元素匹配的任何一个键。

我正在使用 Rails 5.1.6.2,ruby 2.5.3

可能您正在寻找以下运算符:

hstore ? key # does hstore contain key?

查询可能如下所示:

User.where("sectors ? 'oil_and_gas'")
    .or("sectors ? 'energy'")
    .or("sectors ? 'transport'")

根据postgresql docs

Check for a specific key in hstore column You can check for a specific key in an hstore column using the ? operator in the WHERE clause. For example, the following statement returns all rows with attr contains key publisher.

SELECT
  title,
  attr->'publisher' as publisher,
  attr
FROM
  books
WHERE
  attr ? 'publisher';