How can I perform a LIKE query for a jsonb key?

…衆ロ難τιáo~ 提交于 2019-12-23 07:38:53

问题


I have the following jsonb structure:

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

How do I select rows that contain a LIKE operator?

SELECT * FROM myjson WHERE j ? 'this_%'

Returns 0 rows...was hoping it would match 'this_that' and 'this_and_that'. (Note: the characters following '_' will potentially vary greatly and therefore I am not able to do an exact match).


回答1:


Your example should not work because there are not implicit cast between jsonb and text types. You can enforce casting:

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

It is not clean solution. Some better is unpacking json, and filtering over unpacked data with lateral join

postgres=# SELECT key FROM  myjson, lateral jsonb_each_text(j) 
             WHERE key LIKE 'this\_%';
┌───────────────┐
│      key      │
╞═══════════════╡
│ this_that     │
│ this_and_that │
└───────────────┘
(2 rows)


来源:https://stackoverflow.com/questions/30228984/how-can-i-perform-a-like-query-for-a-jsonb-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!