简体   繁体   English

有没有办法使用通配符查询PostgreSQL hstore字段中某些键的存在?

[英]Is there a way to query the existence of certain keys in a PostgreSQL hstore field using wildcards?

I want to filter records in a PostgreSQL 9.0 table based on the existence (or non-existence, rather) of certain keys in a hstore column. 我想根据hstore列中某些键的存在(或不存在)来过滤PostgreSQL 9.0表中的记录。 Right now, I am listing all individual candidates like this: 现在,我列出了所有这样的候选人:

SELECT AVG(array_upper(%# tags,1)) FROM nodes 
WHERE array_upper(%# tags,1) > 0 AND NOT 
tags?|ARRAY['gnis:state_id','gnis:id','gnis:Class','gnis:County',
'gnis:ST_num','gnis:ST_alpha','gnis:County_num','gnis:reviewed',
'gnis:feature_id','gnis:county_name','gnis:import_uuid'];

What I really want to do is to count the average number of key-value pairs in this column, excluding those that contain any key that starts with "gnis:". 真正想要做的是计算此列中键值对的平均数量, 不包括那些包含以“gnis:”开头的键的键值对。 Is there a more efficient way to do this? 有没有更有效的方法来做到这一点?

As I know hstore module does not support wilcards in easy shape that you want. 据我所知, hstore模块不支持你想要的简单形状的wilcards。 However it looks easy to implement such functionality, for example: 但是,实现此类功能看起来很容易,例如:

WITH excluded_tags AS
(
    SELECT array_agg(key) AS tags
    FROM (SELECT skeys(tags) AS key FROM nodes) k
    WHERE key LIKE 'gnis:%'
)
SELECT avg(array_upper(%# tags, 1))
FROM nodes
WHERE array_upper(%# tags, 1) > 0
    AND NOT tags ?| (SELECT tags FROM excluded_tags);

or much shorter: 或者更短:

SELECT avg(array_upper(%# tags, 1))
FROM nodes 
WHERE array_upper(%# tags, 1) > 0 AND
    NOT EXISTS (SELECT skeys FROM skeys(tags) WHERE skeys LIKE 'gnis:%');

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

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