简体   繁体   中英

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:%');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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