Postgresql查询嵌套JSONB字段中的对象

ifd*_*dog 16 postgresql json jsonb postgresql-9.6 postgresql-12

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

No integer,
Content jsonb
Run Code Online (Sandbox Code Playgroud)

说我把很多记录像:

 "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"}}
Run Code Online (Sandbox Code Playgroud)

如何查询表格:

  1. 记录"Content.Item.Name"包含"Dog" "Content.Item.Spec"包含"red"的记录.
  2. "Content.Item.Name"包含"Dog" "Content.Item.Spec"的记录包含"red".
  3. 记录"Content.Item" 中的任何 json字段包含"dog"的位置.

并按"Content.Item.Name.length"排序?

谢谢!

kli*_*lin 29

您应该熟悉JSON函数和操作符.

-- #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');
Run Code Online (Sandbox Code Playgroud)

  • ` - >`运算符给出一个json对象,而` - >>`给出文本. (6认同)
  • 我可以知道如何在“->”和“->>”之间进行选择吗? (2认同)
  • 老实说,对 Postgres 感到失望。这些是不必要的混淆运算符。 (2认同)
  • @jstuartmilne - `i` 代表不区分大小写的匹配,请参见[9.15.2.2。正则表达式](https://www.postgresql.org/docs/current/functions-json.html#JSONPATH-REGULAR-EXPRESSIONS)了解详细信息。 (2认同)