简体   繁体   中英

Search query on JSON column in postgresql

I have a column 'tags' in my table 'categories', which is a json type

----------------------------------------------------------------
id    name                tags
----------------------------------------------------------------
1     Electronics         ["phones","computers","watches"]
2     Fashion             ["jewelry","costumes","watches"]
3     Food                ["cakes","sweets","juices"]
4     Tools               ["keyboards","pens","drills"]
----------------------------------------------------------------

I want to fetch all categories that are having any one of the tags in the array that I match in my SQL

select * from categories where tags::jsonb ?| '{"watches","sweets"}'

I expect the result set as

------------------------------
1     Electronics 
2     Fashion
3     Food  
------------------------------

so first two categories matches for "watches" and third category for "sweets"

the above query perfectly worked on my local server as thats on 9.4 but when I moved to live itis 9.2.15 there and having no jsonb, returning error, is there a similar operator for json type that returns any one of the matching elements in query?

is the column categories.tags json or text datatype? JSON datatype support is very limited in PostgreSQL 9.2, so although you may store JSON data in it, you'll have trouble processing it in any way other than casting to text.

You could use the array overlap && , instead of the jsonb ?| operator:

with
  categories(id,name,tags) as (
    values (1, 'Electronics', '["phones","computers","watches"]'::json),
           (2, 'Fashion', '["jewelry","costumes","watches"]'),
           (3, 'Food', '["cakes","sweets","juices"]'),
           (4, 'Tools', '["keyboards","pens","drills"]'))

select *
from categories
where regexp_replace(regexp_replace(tags::text, '^\[', '{'), '\]$', '}')::text[] && '{watches,sweets}'::text[]

I just found a simple solution for this problem

I turned the json type to text first then replaced my search expression with SIMILAR TO

here is the example sql

select * from categories where tags SIMILAR TO  ("watches"|"sweets")

" are must because they help in fetching apt matches, like when you have tags like watches , watches-new using SIMILAR to with out " like (watches|sweets) will result both, if you use with "" on a json stored on text column, it works just as you wanted it to.

hope this helps some one like me.

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