How to query values with wildcards in PostgreSQL hstore

…衆ロ難τιáo~ 提交于 2019-12-03 03:51:41

问题


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:

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

I can also get a specific value:

SELECT DISTINCT
svals(slice(data, ARRAY['Supplier'])) AS sup
FROM "products"
WHERE data @> 'Supplier => Toshiba'

What I would really like is something like (this doesn't work):

SELECT DISTINCT
svals(slice(data, ARRAY['Supplier'])) AS sup
FROM "products"
WHERE data @> 'Supplier => %tosh%'

or:

SELECT DISTINCT
svals(slice(data, ARRAY['Supplier'])) AS sup
FROM "products"
WHERE lower(sup)
LIKE '%tosh%'

for case-insensitive search. How is this done?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12520375/how-to-query-values-with-wildcards-in-postgresql-hstore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!