多列上的PostgreSQL索引,什么时候太多了?

时间:2018-03-15 09:51:42

标签: sql postgresql indexing composite-index b-tree-index

使用PostgreSQL 9.6

我有一个表格,其中包含一些我希望过滤的值,并按时间排序:

  • 时间戳(可能是在UI中选择的范围)
  • 状态字符串(目前只有几个已知值,也可在UI中选择)
  • 上下文(UI中的数据范围)

我想知道我是否应该:

  1. 关于(上下文,状态)的btree索引+单独的时间索引
  2. 或(上下文,状态,时间)上的btree索引
  3. 每个都是btree索引?
  4. OR小时间范围内的btree索引(时间,状态,上下文)?
  5. 我怀疑数字1是最佳选项,上下文+状态将允许过滤掉值,然后它将扫描时间索引。 我在我的数据上同时创建了1号并看到了一些改进,但是你如何决定每种方法,是否有一些指导原则?

    其中一个查询看起来或多或少像:

    select * from event
    where severity = 'WARNING' and 
    fk_context = 1359544
    order by timestamp LIMIT 30; // Other one has timestamp > ...
    

    另一个人正在寻找时间范围。 我看起来像postgres使用多个索引,一个使用(fk_context,severity,timestamp)然后使用(严重性,时间)索引,但它也取决于限制。

1 个答案:

答案 0 :(得分:1)

你的问题不清楚。如果您有三个潜在条件:

where timestamp between @a and @b order by time
where status = @s order by time
where context = @c order by time

然后你需要三个索引:(timestamp, time)(status, time)(context, time)

如果条件是:

where timestamp between @a and @b and
      status = @s and
      context = @c
order by time 

然后你想要一个索引(status, context, timestamp, time)

还有其他可能与您的描述一致。

相关问题