简体   繁体   中英

ILIKE query inside arrays of objects in jsonb column

I have a jsonb data column made up of various objects. Here is an example.

{"LicensePlates": {"Type": "LicensePlateList", "Value": ["XXXXX"]}, "SubscriptionInfo": {"Type": "SubscriptionInfoList", "Value": [{"id": "1", "lastname": "rossi", "firstname": "paola"}, {"id": "2", "lastname": "Scicolone", "firstname": "Paolo"}]}}

Now I'm searching a specific info in SubscriptionInfo key like this:

SELECT * FROM column WHERE (data -> 'SubscriptionInfo') -> 'Value' @> '[{"firstname": "Paolo"}]';

It works fine, but I would also like to search for "partial" information, eg. searching for the string "pa" (using ILIKE or anything else similar) should return the entire record. it's possible?

You have two options ( demo )

  1. convert data to lower case
select * 
from 
  test 
where 
  lower(data -> 'SubscriptionInfo' ->> 'Value')::jsonb @> lower('[{"firstname": "paolo"}]')::jsonb;
  1. Use cross join and extract JSON then use ilike
select distinct on (t.id) t.*
from 
  test t
  cross join jsonb_array_elements(data -> 'SubscriptionInfo' -> 'Value') ej
where
  value ->> 'firstname' ilike '%paolo%';

If you are using Postgres 13 or later, you can use a SQL/JSON path expression:

select t.*
from the_table t
where t.data @@ '$.SubscriptionInfo.Value[*].firstname like_regex "paolo" flag "i"'

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