Using LIKE operator for array of objects inside jsonb field in PostgreSQL

冷暖自知 提交于 2019-12-12 04:18:04

问题


Is it possible to use LIKE operator for single key/value inside array of objects for jsonb field in PostgreSQL 9.4? For example I have:

 id |                  body                                                              
------------------------------------------------------------
  1 | {"products": [{"name": "qwe", "description": "asd"}, {"name": "zxc", "description": "vbn"}]}

I know, I can get a product with something like this:

select * from table where 'body'->'products' @> '[{"name": "qwe"}]'::jsonb

The question is: can I get this product if I don't know full name of it?


回答1:


Try to get the key and value by using jsonb_each() function:

WITH json_test(data) AS ( VALUES
  ('{"products": [{"name": "qwe", "description": "asd"}, {"name": "zxc", "description": "vbn"}]}'::JSONB)
)
SELECT doc.key,doc.value
FROM json_test jt,
  jsonb_array_elements(jt.data->'products') array_elements,
  jsonb_each(array_elements) doc
WHERE
  doc.key = 'name'
AND
  doc.value::TEXT LIKE '%w%';

Output will be the following:

 key  | value 
------+-------
 name | "qwe"
(1 row)


来源:https://stackoverflow.com/questions/34596716/using-like-operator-for-array-of-objects-inside-jsonb-field-in-postgresql

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