Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fuzzy string match in postgres jsonb column

I have a jsonb column in a postgres table called topics which is a literal array of strings. An example record might have this for a topics value:

['healthcare', 'fitness', 'gains', 'doyouevenliftbro']

I need to find this record among many which would match %lift%

All the other queries I'm finding on stackoverflow and the pg docs can match against doyouevenliftbro as a complete string, or can do a regex match if this is converted from json_to_recordset() or whatever, but then they go on to reference properties inside the JSON, which this doesn't have. Hoping it's simple syntax that's just evading me. Thanks!

like image 998
AlienWebguy Avatar asked Sep 01 '17 22:09

AlienWebguy


1 Answers

You could use json_array_elements to un-nest the json array to a set. Once it's a set, you can apply the like operator and throw it in a subquery.

select *
from your_table
where exists (
  select *
  from json_array_elements(your_table.topics::json)
  where value::text like '%lift%'
);

EDIT: Done more bluntly, what if you just cast the whole topics array as text and match against that?

select *
from your_table
where topics::text like '%lift%';
like image 114
Andy Carlson Avatar answered Oct 13 '22 12:10

Andy Carlson