How to query values with wildcards in PostgreSQL hstore

前端 未结 2 1645
野的像风
野的像风 2021-01-31 10:43

I\'m trying to query hstore for all the values of a certain key that match a search criteria.

I can get all the values for a certain key like this:

SELE         


        
相关标签:
2条回答
  • 2021-01-31 11:16

    You can extract values by key from an hstore column with the -> operator.

    SELECT data->'Supplier' AS sup
    FROM products
    WHERE lower(data->'Supplier') LIKE '%tosh%';
    

    Additionally, like most expressions in PostgreSQL (excepting things like random()), you can index this value:

    CREATE INDEX products_supplier_key ON products ((data->'Supplier'));
    CREATE INDEX products_supplier_lowercase_key ON products ((lower(data->'Supplier')));
    

    This would allow PostgreSQL to answer many such queries using the index instead of fetching each row and scanning the hstore column. See the notes on Index Types regarding index usage with LIKE.

    0 讨论(0)
  • 2021-01-31 11:18

    One caveat to willglynn's answer for anyone seeing this in the future -- the original query and the new query have slightly different behavior. Namely,

    SELECT data->'Supplier' AS sup
    FROM products;
    

    will include a NULL value assuming at least one row doesn't have an assignment for Supplier.

    SELECT DISTINCT
    svals(slice(data, ARRAY['Supplier']))
    FROM "products"
    

    will not return the NULL value.

    0 讨论(0)
提交回复
热议问题