Hstore使用通配符搜索值

时间:2015-06-29 17:27:05

标签: sql postgresql hstore

使用PostgreSQL,我希望能够在HEMore字段中找到与给定查询匹配的所有键值对。因此,例如,给出如下表格:

Name        Parentage (Hstore)
_____       ___________________
Rover       Mother => Yellow Lab, Father => Black Lab
Fido        Mother => Black Lab, Father => Rottweiler
Rex         Mother => Labrador Retriever, Father => Springer Spaniel 
Lassie      Mother => Border Collie, Father => Collie

我怎样才能对任何拥有'%lab%'的狗进行查询?在它的家谱?即搜索将带来罗孚,菲多和雷克斯,但不是拉西。我见过的唯一例子是在一个密钥中进行搜索 - 我需要在允许使用通配符的所有值中进行搜索。

我查看了this类似的问题,但它似乎只对特定键进行搜索,而不是对所有键中Hstore字段中找到的所有值进行搜索。

请注意,这是一个构造示例,我试图让它可访问。在我的实际数据库中,我有语言代码的键,后面跟着不同语言中相同单词的翻译值。我需要能够进行任何值的搜索,无论它是什么语言。

1 个答案:

答案 0 :(得分:1)

将hstore分解为name / parent行,然后选择distinct 父列与您的搜索条件匹配的狗的名字。

根据实际数据的性质,这可能需要额外的数据 索引。我不会为此使用hstore,但您的实际数据可能会 与众不同。

% psql -qe -f hstore.sql
begin;
create extension hstore;
create temp table dogs (
    "name" text,
    parentage hstore
);
insert into dogs values
('Rover', 'Mother => "Yellow Lab",Father => "Black Lab"')
,('Fido', 'Mother => "Black Lab",Father => "Rottweiler"')
,('Rex', 'Mother => "Labrador Retriever",Father => "Springer Spaniel"')
,('Lassie', 'Mother => "Border Collie",Father => "Collie"')
;
table dogs;
  name  |                          parentage                           
--------+--------------------------------------------------------------
 Rover  | "Father"=>"Black Lab", "Mother"=>"Yellow Lab"
 Fido   | "Father"=>"Rottweiler", "Mother"=>"Black Lab"
 Rex    | "Father"=>"Springer Spaniel", "Mother"=>"Labrador Retriever"
 Lassie | "Father"=>"Collie", "Mother"=>"Border Collie"
(4 rows)

select * from dogs where "name" in
(select distinct "name" from (
            select "name", unnest(avals(parentage)) as parent
        ) as plist
        where parent ilike '%lab%'
);
 name  |                          parentage                           
-------+--------------------------------------------------------------
 Rover | "Father"=>"Black Lab", "Mother"=>"Yellow Lab"
 Fido  | "Father"=>"Rottweiler", "Mother"=>"Black Lab"
 Rex   | "Father"=>"Springer Spaniel", "Mother"=>"Labrador Retriever"
(3 rows)

rollback;