【问题标题】:Index Creation on Postgresql在 Postgresql 上创建索引
【发布时间】:2020-07-03 10:58:33
【问题描述】:

我在创建索引时遇到困难。

TableName(My_Table)
ColumnName(Repo_id(INT),Data JSONB) 

JSONB 结构:

{
   "Property_1":'1',
   "Property_2":'2',
   "Property_3":'3',
   "Property_4":'4',
   "Property_5":'5'
}

对于一个查询:

select *
from my_table
where repo_id = 1
and Data ->> 'Property_1' = '1'

我添加了 btree 索引 (repo_id,(Data ->> 'Property_1')),它适用于那种情况。

对于其他场景,如

 select *
 from my_table
 where repo_id = 2
 and Data ->> 'Property_2' = '2'

它没有给我最佳计划。为此,我必须将以前的索引修改为覆盖索引 (repo_id,(Data ->> 'Property_1',((Data ->> 'Property_2')) ),这给了我最佳计划。

我在列中有超过 100 个 json 属性,并且对于每个 repo_id,其中的条件 ...json 属性过滤器会有所不同。我认为将所有这些列添加为覆盖索引是不明智的,它会增加索引大小。

请建议我如何有效地在动态 json 属性过滤器上创建索引。

【问题讨论】:

    标签: sql postgresql indexing jsonb postgresql-10


    【解决方案1】:

    使用 GIN 索引并更改 WHERE 子句:

    create index on the_table  using gin (data);
    

    然后使用包含运算符@>

    select *
    from my_table
    where data @> '{"Property_2": 2}';
    

    条件where data ->> 'Property_2' = '2'使用该索引。您必须使用supported operator classes 之一才能使用索引。

    如果@> 运算符将支持您想要做的所有事情,那么使用不同的运算符类会使索引更高效:

    create index on the_table  using gin (data jsonb_path_ops);
    

    使用该运算符类,运算符 ? ?&?| 将不会使用该索引。

    【讨论】:

    • @a_horse_with_no_name..感谢您的回复。我也有带有 repo_id 的过滤器。因此,尝试使用 GIN(repo_id,data jsonb_path_ops) 和 Data ->> 'Property_2' = ?(即用户输入的过滤器)来制作复合索引。
    • @VBAGuy:如果你想在该索引中包含一个整数列,你需要btree_gin 扩展。但是使用Data ->> 'Property_2' = ?不会使用该索引,您必须使用@> 运算符。根据repo_id 上的条件的选择性,尝试分离索引而不是一个组合索引可能是有意义的
    • @a_horse_with_no_name..我启用了 btree_gin 扩展,因为我能够使用 (INT,JSONB) 列创建 GIN 索引
    • @a_horse_with_no_name...我已使用 GIN(REPO_ID,数据 jsonb_path_ops)创建索引。然后尝试使用此查询: select * from my_table where repo_id = 1 and data @> '{"Property_2": "2"}' and data @> '{"Property_8": "8"}' ;它适用于 BITMap Index Scan & Bit Map Heap Scan 。我将两列都包含在索引中。它根本不应该用于 BIT Map Scan。
    猜你喜欢
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2015-06-27
    • 1970-01-01
    • 2017-07-12
    • 2012-09-06
    相关资源
    最近更新 更多