我在文件中找不到这个问题的确切答案.如果列是数组类型,是否会对所有输入的值进行单独索引?

我创建了一个包含int[]列的简单表,并在其上放置了一个唯一的索引.我注意到我不能添加相同的int数组,这让我相信索引是数组项的组合,而不是每个项的索引.

INSERT INTO "Test"."Test" VALUES ('{10, 15, 20}');
INSERT INTO "Test"."Test" VALUES ('{10, 20, 30}');

SELECT * FROM "Test"."Test" WHERE 20 = ANY ("Column1");

索引是否有助于此查询?

推荐答案

是的,你可以索引一个数组,但是你必须使用array operatorsGIN-index type.

例子:

    CREATE TABLE "Test"("Column1" int[]);
    INSERT INTO "Test" VALUES ('{10, 15, 20}');
    INSERT INTO "Test" VALUES ('{10, 20, 30}');

    CREATE INDEX idx_test on "Test" USING GIN ("Column1");

    -- To enforce index usage because we have only 2 records for this test... 
    SET enable_seqscan TO off;

    EXPLAIN ANALYZE
    SELECT * FROM "Test" WHERE "Column1" @> ARRAY[20];

结果:

Bitmap Heap Scan on "Test"  (cost=4.26..8.27 rows=1 width=32) (actual time=0.014..0.015 rows=2 loops=1)
  Recheck Cond: ("Column1" @> '{20}'::integer[])
  ->  Bitmap Index Scan on idx_test  (cost=0.00..4.26 rows=1 width=0) (actual time=0.009..0.009 rows=2 loops=1)
        Index Cond: ("Column1" @> '{20}'::integer[])
Total runtime: 0.062 ms
Note

似乎在许多情况下,gin__int_ops选项是必需的

create index <index_name> on <table_name> using GIN (<column> gin__int_ops)

I have not yet seen a case where it would work with the && and @> operator without the gin__int_ops options

Postgresql相关问答推荐

如何在PSQL中查询jsonb列包含字符串的嵌套数组

Pogresql性能中的枚举与文本数据类型

Postgres 函数 now() 返回不正确的时区偏移量

将数组插入 Postgresql 数据库

Postgres 会话处于空闲状态,query = COMMIT 或 ROLLBACK

运算符不存在:integer = integer[] 在使用 ANY 的查询中

SELECT INTO 具有多个归因

使用 try/except 与 psycopg2 或with closing?

datagrip 无法应用更改 此表是只读的

判断值是否存在于列中

如何在 Postgresql 中正确使用 FETCH FIRST?

Sidekiq - 无法在 5.000 秒内获得数据库连接

H2 postgresql mode模式似乎不起作用

如何使用 Django Migrations 重新创建已删除的表?

错误:表tablename上的更新或删除违反外键约束

根据 Helm 图表设置值

psql 将默认 statement_timeout 设置为 postgres 中的用户

PostgreSQL regexp_replace() 只保留一个空格

使用python将数据从csv复制到postgresql

PostgreSQL:如何解决numeric field overflow问题