postgresql - postgres - 估计时间戳列的索引大小

标签 postgresql indexing

有一个 postgres 表 ENTRIES,其中有一个类型为 timestamp without time zone 的 'made_at' 列。

该表在该列和另一列(USER_ID,外键)上都有一个 btree 索引:

btree (user_id, date_trunc('day'::text, made_at))

如您所见,日期在“天”处被截断。以这种方式构建的索引的总大小为 130 MB -- ENTRIES 表中有 4,000,000 行。

问题:如果我希望时间精确到秒,我该如何估计索引的大小?基本上,在秒而不是天截断时间戳(我希望应该很容易做到)。

最佳答案

有趣的问题!根据我的调查,它们的大小相同。

我的直觉告诉我,你的两个索引的大小应该没有区别,因为 PostgreSQL 中的时间戳类型是固定大小的 ( 8 bytes ),而且我认为截断函数只是简单地清零了最小的适当数量重要的时间,但我想我最好用一些事实来支持我的猜测。

我在 heroku PostgreSQL 上启动了一个免费的开发数据库,​​并生成了一个包含 4M 随机时间戳的表,截断为日期和秒值,如下所示:

test_db=> SELECT * INTO ts_test FROM 
                        (SELECT id, 
                                ts, 
                                date_trunc('day', ts) AS trunc_day, 
                                date_trunc('second', ts) AS trunc_s 
                         FROM (select generate_series(1, 4000000) AS id, 
                               now() - '1 year'::interval * round(random() * 1000) AS ts) AS sub) 
                         AS subq;
SELECT 4000000

test_db=> create index ix_day_trunc on ts_test (id, trunc_day);
CREATE INDEX
test_db=> create index ix_second_trunc on ts_test (id, trunc_s);
CREATE INDEX
test_db=> \d ts_test
           Table "public.ts_test"
  Column   |           Type           | Modifiers 
-----------+--------------------------+-----------
 id        | integer                  | 
 ts        | timestamp with time zone | 
 trunc_day | timestamp with time zone | 
 trunc_s   | timestamp with time zone | 
Indexes:
    "ix_day_trunc" btree (id, trunc_day)
    "ix_second_trunc" btree (id, trunc_s)

test_db=> SELECT pg_size_pretty(pg_relation_size('ix_day_trunc'));
          pg_size_pretty 
          ----------------
          120  MB
          (1 row)

test_db=> SELECT pg_size_pretty(pg_relation_size('ix_second_trunc'));
          pg_size_pretty 
          ----------------
          120 MB
          (1 row)

关于postgresql - postgres - 估计时间戳列的索引大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452895/

相关文章:

performance - MongoDB 插入第二个索引的性能

sql - Postgres 不使用索引,即使返回的行少于 5%

sql - postgresql中的连接索引

postgresql - 使用KML生成几何图形

sql - 选择连接表中多个值与给定集合匹配的位置

sql - Postgres 连接所有

python - numpy 数组类型错误 : only integer scalar arrays can be converted to a scalar index

vba - 将一个单元格中的字符串放入我的索引匹配 VBa 脚本的中间

sql - 如何获取整个数据库中的表名和特定列的序号位置

python - 从 Django 中的死数据库连接中恢复