开发者

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. 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:". Is there a more efficient way to do this?


As I know hstore module does not support wilcards in easy shape that you want. 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:%');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜