【问题标题】:PostgreSQL indexing JSONB arrayPostgreSQL 索引 JSONB 数组
【发布时间】:2017-09-11 18:47:59
【问题描述】:

这是我的json

jsondata
------------------------------------
{"key1": 1, "keyset": [10, 20, 30]}
{"key1": 1, "keyset": [10, 20]}
{"key1": 1, "keyset": [30]}
{"key1": 1 }
{"key1": 1, "key2": 1}

我尝试为上述示例创建索引keyset
使用 btree 的第一个索引

CREATE INDEX test_keyset ON test_table (jsondata->'keyset');

使用 gin 的第二个索引

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 的新手

【问题讨论】:

标签: json postgresql indexing


【解决方案1】:

在表达式 jsondata->'keyset' 上使用 gin 索引:

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)    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2020-12-08
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2021-07-22
    • 2021-04-23
    相关资源
    最近更新 更多