【问题标题】:Postgres jsonb index on nested integer field嵌套整数字段上的 Postgres jsonb 索引
【发布时间】:2018-08-27 12:49:33
【问题描述】:

我的 postgres 数据库中有以下数据结构 - 一个名为 customer 的 jsonb 列

{
    "RequestId": "00000000-0000-0000-0000-000000000000",
    "Customer": {
        "Status": "A",
        "AccountId": 14603582,
        "ProfileId": 172,
        "ReferralTypeId": 15
    }
    "Contact": {
        "Telephone": "",
        "Email": ""
    }   
}

我想在ProfileId 字段上创建一个索引,它是一个整数。

我一直找不到如何在嵌套字段上创建索引的示例。

我正在执行的查询(大约需要 300 秒)是:

select id, customer from where customer @> '{"Customer":{"ProfileId": 172}}'

【问题讨论】:

    标签: postgresql indexing jsonb


    【解决方案1】:

    用于 GIN 索引 support the @> operator 的运算符类 jsonb_path_opsjsonb_ops

    所以您的查询应该能够使用以下索引

    create index on the_table using gin (customer);
    

    它使用默认的jsonb_ops 运算符。

    根据手册,jsonb_path_ops 运算符速度更快,但仅支持 @> 运算符。因此,如果这是您拥有的唯一条件类型(对于该列),使用 jsonb_path_ops 可能更有效:

    create index on the_table using gin (customer jsonb_path_ops);
    

    【讨论】:

    • 因为我只想按一两个字段索引,是否可以将索引隔离到特定字段?例如CREATE INDEX on the_table USING GIN ((customer -> 'Customer' -> 'ProfileId') jsonb_path_ops);
    • 对于该表达式,您不需要 GIN 索引。 btree 索引会更有效。 GIN 索引适用于您不知道条件将包含 JSON 中哪些键(或路径)的情况
    • 这样的东西行不通? CREATE INDEX idx_content_metadata_pn_qwire_id ON your_table((customer->>'Customer'->> 'ProfileId'));
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多