简体   繁体   English

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

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

I've a hstore field in a database table.我在数据库表中有一个hstore字段。 I want to write a Query to find records matching with any array element in any hash of hstore field using ruby on rails.我想编写一个查询来使用 ruby​​ on rails 在hstore字段的任何散列中查找与任何数组元素匹配的记录。

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

considering above test data, I want to write a query on hstore field to get all records having any key like ['oil_and_gas', 'energy', 'transport']考虑到上述测试数据,我想在 hstore 字段上编写一个查询以获取所有具有任何键的记录,例如 ['oil_and_gas', 'energy', 'transport']

I can match and find single sector records as its mentioned in https://nandovieira.com/using-postgresql-and-hstore-with-rails , but my requirement is to find any record where hstore hash is having any one key matching with any one element of array.我可以匹配并找到https://nandovieira.com/using-postgresql-and-hstore-with-rails 中提到的单扇区记录,但我的要求是找到 hstore 哈希与任何一个键匹配的任何记录数组的任何一个元素。

I'm using Rails 5.1.6.2, ruby 2.5.3我正在使用 Rails 5.1.6.2,ruby 2.5.3

May be you are looking for the following operator:可能您正在寻找以下运算符:

hstore ? key # does hstore contain key?

Query may looks like so:查询可能如下所示:

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

According to postgresql docs根据postgresql 文档

Check for a specific key in hstore column You can check for a specific key in an hstore column using the ?检查 hstore 列中的特定键 您可以使用 ? operator in the WHERE clause. WHERE 子句中的运算符。 For example, the following statement returns all rows with attr contains key publisher.例如,以下语句返回 attr 包含密钥发布者的所有行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM