假设我有以下的
我需要的是例如,获取所有孩子年龄在10到12岁之间的父母。
我创建了以下查询:
parents
表格:create table parents (
id integer not null constraint parents_pkey primary key,
name text not null,
children jsonb not null
);
在这里,children
是一个以下结构的JSON数组:
[
{
"name": "child1",
"age": 10
},
{
"name": "child2",
"age": 12
}
]
我需要的是例如,获取所有孩子年龄在10到12岁之间的父母。
我创建了以下查询:
select distinct
p.*
from
parents p, jsonb_array_elements(p.children) c
where
(c->>'age')::int between 10 and 12;
当表parents
很大时(例如1M条记录),它的工作效率很低。我尝试在children
字段上使用'gin'索引,但这没有帮助。
那么有没有办法加速这样的查询?或者也许有另一种解决方案可以针对嵌套json数组中的字段进行查询/索引?
查询计划:
Unique (cost=1793091.18..1803091.18 rows=1000000 width=306) (actual time=4070.866..5106.998 rows=399947 loops=1)
-> Sort (cost=1793091.18..1795591.18 rows=1000000 width=306) (actual time=4070.864..4836.241 rows=497313 loops=1)
Sort Key: p.id, p.children, p.name
Sort Method: external merge Disk: 186040kB
-> Gather (cost=1000.00..1406321.34 rows=1000000 width=306) (actual time=0.892..1354.147 rows=497313 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Nested Loop (cost=0.00..1305321.34 rows=416667 width=306) (actual time=0.162..1794.134 rows=165771 loops=3)
-> Parallel Seq Scan on parents p (cost=0.00..51153.67 rows=416667 width=306) (actual time=0.075..239.786 rows=333333 loops=3)
-> Function Scan on jsonb_array_elements c (cost=0.00..3.00 rows=1 width=0) (actual time=0.004..0.004 rows=0 loops=1000000)
Filter: ((((value ->> 'age'::text))::integer >= 10) AND (((value ->> 'age'::text))::integer <= 12))
Rows Removed by Filter: 3
Planning time: 0.218 ms
Execution time: 5140.277 ms
VIEW
返回JSON表示。这应该是快速和简单的。但是,也有方法可以帮助拥挤的jsonb
值中的贫困儿童... - Erwin Brandstetter