【问题标题】:PostgreSQL index for jsonb @> search用于 jsonb @> 搜索的 PostgreSQL 索引
【发布时间】:2017-07-11 07:57:09
【问题描述】:

我有以下疑问:

 SELECT "survey_results".* FROM "survey_results" WHERE (raw @> '{"client":{"token":"test_token"}}');

EXPLAIN ANALYZE 返回以下结果:

 Seq Scan on survey_results  (cost=0.00..352.68 rows=2 width=2039) (actual time=132.942..132.943 rows=1 loops=1)
   Filter: (raw @> '{"client": {"token": "test_token"}}'::jsonb)
   Rows Removed by Filter: 2133
 Planning time: 0.157 ms
 Execution time: 132.991 ms
(5 rows)

我想在raw 字段内的client 键上添加索引,这样搜索会更快。我不知道该怎么做。当我像这样为整个raw 列添加索引时:

CREATE INDEX test_index on survey_results USING GIN (raw);

然后一切都按预期进行。我不想为整个raw 添加索引,因为我在数据库中有很多记录,我不想增加它的大小。

【问题讨论】:

    标签: sql postgresql jsonb


    【解决方案1】:

    如果您在示例中使用 JSON 对象作为 atm,那么您可以像这样指定索引 client

    CREATE INDEX test_client_index ON survey_results USING GIN (( raw->'client ));
    

    但由于您在查询中使用@> 运算符,那么在您的情况下,只为该运算符创建索引可能是有意义的:

    CREATE INDEX test_client_index ON survey_results USING GIN (raw jsonb_path_ops);
    

    查看更多关于Postgres JSONB indexing的文档:

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多