How can I execute a LIKE request for a jsonb key?

I have the following jsonb structure:

{'this': '1', 'this_that': '0', 'this_and_that': '5'} 

How to select rows containing a LIKE statement?

 SELECT * FROM myjson WHERE j ? 'this_%' 

Returns 0 rows ... hoped this would match 'this_that' and 'this_and_that'. (Note: the characters following the "_" can vary greatly, and therefore I cannot make an exact match.)

+7
json postgresql jsonb
source share
1 answer

Your example should not work because listing is not implied between jsonb and text types. You can force casting:

 SELECT '{"this": 1, "this_that": 0, "this_and_that": 5}'::jsonb::text like '%"this%'; 

This is not a clean solution. Some are better at unpacking json and filtering on unpacked data with a side connection

 postgres=# SELECT key FROM myjson, lateral jsonb_each_text(j) WHERE key LIKE 'this\_%'; โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ key โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก โ”‚ this_that โ”‚ โ”‚ this_and_that โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ (2 rows) 
+8
source share

All Articles