Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query values with wildcards in PostgreSQL hstore

Tags:

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?

like image 489
Rob Gonzalez Avatar asked Sep 20 '12 20:09

Rob Gonzalez


People also ask

How do I use wildcards in PostgreSQL?

You construct a pattern by combining literal values with wildcard characters and use the LIKE or NOT LIKE operator to find the matches. PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.

How do I use Hstore in PostgreSQL?

The hstore module is used to implement the hstore data type in the form of key-value pairs for a single value within PostgreSQL. The hstore data type is remarkably effective in many cases, such as, multiple rows with multiple attributes which are rarely queried for or semi-structured data.

Which symbol is SQL's wildcard symbol PostgreSQL?

Wildcard operator is essential in PostgreSQL. Basically, we used percentage (%) and underscore (_) wildcard operator to fetch matching rows from the table.

How do I use like keyword in PostgreSQL?

The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.


1 Answers

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.

like image 140
willglynn Avatar answered Sep 22 '22 03:09

willglynn