Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql jsonb case insensitive query

I have a table like:

CREATE TABLE cityData
(
  item character varying,
  data jsonb
);

it contains values like

ITEM        DATA
test1       [{"rank":"1", "city":"New York"},{"rank":"3", "city":"Sidney"}] 
test2       [{"rank":"2", "city":"NEW YORK"},{"rank":"4", "city":"New Delhi"}] 

I need to get number of distinct json objects where city is 'New York' I am using the following query

SELECT  * FROM   cityData t
WHERE ( data @> '[{"city":"New York"}]')
and t.item ilike '%test%';

But this query outputs test1 row. I need to make the query case insensitive so that data @> '[{"city":"New York"}]' matches both New York and NEW YORK

like image 487
ranjan Avatar asked Jun 21 '16 16:06

ranjan


2 Answers

where lower(data::text)::jsonb @> lower('[{"city":"New York"}]')::jsonb
like image 123
Clodoaldo Neto Avatar answered Sep 30 '22 10:09

Clodoaldo Neto


With PostgreSQL 12+, case-insensitive matches can be done using @? operator and a jsonpath query. Following the example in question, your clause might looks something along the lines of:

where data @? '$[*].city like_regex "(?i)^NEW YORK$"'

This can be significantly faster without building specific case-insensitive indexes, as opposed to casting JSONB to string and back to use lower().

like image 29
Anton Strogonoff Avatar answered Sep 30 '22 10:09

Anton Strogonoff