经过一些调试后,我了解到为外部json元素(例如“root”)创建的索引也适用于层次结构中的所有嵌套元素。所以在我的情况下,正确的办法是:
CREATE INDEX idx_tmp_data_root ON tmp USING gin ((data->'root') jsonb_path_ops);
我选择了jsonb_path_ops
索引操作符类,因为它支持的要求,并在更紧凑和更快的指数结果,而不是默认的索引类型遏制查询@>
。
这里是一个充分的论证:
首先,创建一个表并加载数据:
-> SET enable_seqscan = OFF; -- force postgres to use indices if any
-> create temporary table tmp (data jsonb not null);
-> insert into tmp (data) values ('{"root": [{"name": "item1"}, {"name": "item2"}]}');
查询没有索引:
-> explain select * from tmp where data->'root' @> '[{"name": "item1"}]';
QUERY PLAN
Seq Scan on tmp (cost=10000000000.00..10000000029.65 rows=1 width=32)
Filter: ((data -> 'root'::text) @> '[{"name": "item1"}]'::jsonb)
(2 rows)
查询与索引:
-> CREATE INDEX idx_tmp_data_root ON tmp USING gin ((data->'root') jsonb_path_ops);
-> explain select * from tmp where data->'root' @> '[{"name": "item1"}]';
QUERY PLAN
Bitmap Heap Scan on tmp (cost=8.00..12.02 rows=1 width=32)
Recheck Cond: ((data -> 'root'::text) @> '[{"name": "item1"}]'::jsonb)
-> Bitmap Index Scan on idx_tmp_data_root (cost=0.00..8.00 rows=1 width=0)
Index Cond: ((data -> 'root'::text) @> '[{"name": "item1"}]'::jsonb)
(4 rows)
-> SET enable_seqscan = ON;
'CREATE INDEX ON tmp((dat一个 - >> '根'));'? – Hackerman
@Hackerman你已经接近了:正确的解决方案似乎是'data - >'root''。 – user2740947