简体   繁体   中英

how to search values in json field in sql (postgresql)

lets say i have a column named keyword with values like ['wood', 'grass', 'tree', 'plant'] , now how do I query that if this array contains wood or grass or both of them

my solution (here I am using a text string and searching through it)

  select * from table where keywords_column ~* 'wood';

but it is limited to one word only. It would be great if I would get solution in knex.js or Adonis Lucid

我认为这可能有效,但我没有测试它:

select * from table where keywords_column ~* 'wood' or keywords_column ~* 'grass';

You can use the contains operator ?|

select * 
from the_table 
where keywords_column ?| array['wood', 'grass'];

This assumes that keywords_columns is defined as jsonb (which it should be if you store JSON values). If it's not, you need to cast it keywords_column::jsonb

Online example

I would do like this:

SELECT * from table WHERE column SIMILAR TO '(wood |grass |tree |plant )%';

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