这是我的json
jsondata
------------------------------------
{"key1": 1, "keyset": [10, 20, 30]}
{"key1": 1, "keyset": [10, 20]}
{"key1": 1, "keyset": [30]}
{"key1": 1 }
{"key1": 1, "key2": 1}
我尝试使用btreekeyset
为上面的示例
1st索引创建索引
CREATE INDEX test_keyset ON test_table (jsondata->'keyset');
使用杜松子酒的第二索引
CREATE INDEX test_keyset ON test_table USING GIN(jsondata->'keyset');
并查询以选择keyset
值10,
SELECT jsondata
FROM test
JOIN LATERAL jsonb_array_elements_text(jsondata->'keyset') a(v)
ON TRUE
WHERE a.v::integer = 10;
但是它正在执行顺序扫描(检查所有行),任何人都可以建议我哪种索引方法是正确的(btree或gin)以及上述示例中使用索引从json获取数据的有效方法,我是postgres的新手
在表达式上使用gin索引jsondata->'keyset'
:
create index test_keyset on test using gin((jsondata->'keyset'));
您应该在查询中将表达式与@>
运算符结合使用:
select jsondata
from test
where jsondata->'keyset' @> '10'
jsondata
-------------------------------------
{"key1": 1, "keyset": [10, 20, 30]}
{"key1": 1, "keyset": [10, 20]}
(2 rows)
测试计划者是否可以使用索引:
set enable_seqscan to off;
explain analyse
select jsondata
from test
where jsondata->'keyset' @> '10'
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Bitmap Heap Scan on test (cost=8.00..12.02 rows=1 width=55) (actual time=0.024..0.025 rows=2 loops=1)
Recheck Cond: ((jsondata -> 'keyset'::text) @> '10'::jsonb)
Heap Blocks: exact=1
-> Bitmap Index Scan on test_keyset (cost=0.00..8.00 rows=1 width=0) (actual time=0.014..0.014 rows=2 loops=1)
Index Cond: ((jsondata -> 'keyset'::text) @> '10'::jsonb)
Planning time: 0.576 ms
Execution time: 0.066 ms
(7 rows)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句