如何在 Postgres 中的 JSON 字段上创建索引
How to create index on JSON field in Postgres
我需要在 jsonb 字段上优化以下查询:
示例:
create table sample (id char(10) pk, doc1 jsonb);
示例数据:
('abcd',{"_id": "__default:5cd3e-f49f", "status": "updated"}
select * from sample where doc1->>'_id'='__default:5cd3e-f49f';
我已尝试创建索引:
create index idx1 on doc1 using gin (doc1) -- not picked
create index idx2 on doc2 using gin ((doc1->>'id') - no luck
我的查询计划保持不变,它没有选择上述任何索引。并且查询执行时间非常长:
Gather (cost=1000.00..90780.97 rows=2938 width=1108) (actual time=0.277..124.337 rows=1 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on sample (cost=0.00..89487.17 rows=1224 width=1108) (actual time=79.340..120.226 rows=0 loops=3)
Filter: ((doc1 ->> '_id'::text) = '__default:5cd3e-f49f'::text)
Rows Removed by Filter: 195527
Planning Time: 0.054 ms
Execution Time: 124.359 ms
以下索引有效,查询执行时间缩短。
create index idx3 on doc2 ((doc1->>'_id'));
我需要在 jsonb 字段上优化以下查询:
示例:
create table sample (id char(10) pk, doc1 jsonb);
示例数据:
('abcd',{"_id": "__default:5cd3e-f49f", "status": "updated"}
select * from sample where doc1->>'_id'='__default:5cd3e-f49f';
我已尝试创建索引:
create index idx1 on doc1 using gin (doc1) -- not picked
create index idx2 on doc2 using gin ((doc1->>'id') - no luck
我的查询计划保持不变,它没有选择上述任何索引。并且查询执行时间非常长:
Gather (cost=1000.00..90780.97 rows=2938 width=1108) (actual time=0.277..124.337 rows=1 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on sample (cost=0.00..89487.17 rows=1224 width=1108) (actual time=79.340..120.226 rows=0 loops=3)
Filter: ((doc1 ->> '_id'::text) = '__default:5cd3e-f49f'::text)
Rows Removed by Filter: 195527
Planning Time: 0.054 ms
Execution Time: 124.359 ms
以下索引有效,查询执行时间缩短。
create index idx3 on doc2 ((doc1->>'_id'));