sqlarraysjsonpostgresqljsonb

Query JSONB column for any value where =?


I have a jsonb column which has the unfortunate case of being very unpredictable, in some cases its value may be an array with nested values:

["UserMailer", "applicant_setup_3", ["5cbffeb7-8d5e-4b52-a475-3cf320b2cee9"]]

Sometimes it will be something with key/values like this:

[{"reference_id": "5cbffeb7-8d5e-4b52-a475-3cf320b2cee9", "job_dictionary": ["StatusUpdater", "FollowTwitterUsersJob"]}]

Is there a way to write a query which just treats the whole column like text and does a like to see if I can find the uuid in the big text blob? I want to find all the records where a particular uuid string is present in the jsonb column.

The query doesn't need to be fast or efficient.


Solution

  • Postgres has search operator ? for jsonb, but that would require you to search the json content recursively.

    A possible, although not very efficient method, would to stringify the object and use LIKE to search it:

    myjsonb::text LIKE '%"5cbffeb7-8d5e-4b52-a475-3cf320b2cee9"%'
    myjsonb::text LIKE '%"' || myuuid || '"%'
    

    Demo on DB Fiddle: