Postgresql查询嵌套JSONB字段

时间:2017-02-09 07:34:41

标签: json postgresql jsonb

我正在使用PostgreSQL 9.6,我有一个名为“ItemDbModel”的表,其中有两列如下:

No integer,
Content jsonb

说我放了许多记录,如:

 "No": 2, {"obj":"x","Item": {"Name": "BigDog", "Model": "NamedHusky", "Spec":"red dog"}}
 "No": 4, {"obj":"x","Item": {"Name": "MidDog", "Model": "NamedPeppy", "Spec":"no hair"}}
 "No": 5, {"obj":"x","Item": {"Name": "BigCat", "Model": "TomCat", "Spec":"blue color"}}

如何查询表格:

  1. 记录“Content.Item.Name”包含“Dog”的内容 “Content.Item.Spec”包含“red”。
  2. 记录“Content.Item.Name”包含“Dog” OR “Content.Item.Spec”包含“red”。
  3. 记录“Content.Item”中任何 json字段包含“dog”的位置。
  4. 按“Content.Item.Name.length”排序?

    谢谢!

1 个答案:

答案 0 :(得分:23)

您应该熟悉JSON Functions and Operators

-- #1
select *
from example
where content->'Item'->>'Name' ilike '%dog%'
and content->'Item'->>'Spec' ilike '%red%'

-- #2
select *
from example
where content->'Item'->>'Name' ilike '%dog%'
or content->'Item'->>'Spec' ilike '%red%'

-- #3
select distinct on(no) t.*
from example t,
lateral jsonb_each_text(content->'Item')
where value ilike '%dog%';

-- and
select *
from example t
order by length(content->'Item'->>'Name');