【问题标题】:Indexing in PostgreSQLPostgreSQL 中的索引
【发布时间】:2021-06-16 04:24:56
【问题描述】:

我有一个问题要问,以帮助我更好地理解索引。我们对此有何不同:

1
create index insertion_test_timestamp1_idx
on insertion_test (timestamp1);

create index insertion_test2_timestamp1_idx
on insertion_test (id13);

还有这个:

2
create index insertion_test_timestamp1_idx
on insertion_test (timestamp1,id13);

我使用的一些查询如下所示:

select * from timestampdb where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-02 00:05:00' and id13>'5',
select date_trunc('hour',timestamp1) as hour,avg(id13) from timestampdb where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-02 00:05:00' group by hour order by hour ,
select date_trunc('hour',timestamp1) as hour,max(id13) from timestampdb where timestamp1<='2020-01-01 00:05:00' group by hour order by hour desc limit 5,
select date_trunc('hour',timestamp1) as hour,max(id13) from timestamppsql where timestamp1 >='2020-01-01 00:05:00' and timestamp1<='2020-01-01 01:05:00' group by hour order by hour asc

我的版本是这样的:psql (PostgreSQL) 12.6 (Ubuntu 12.6-1.pgdg20.04+1)

【问题讨论】:

  • 第一个创建两个索引。第二个创建一个包含两列的索引。它们非常不同。
  • "psql" 是默认客户端(有自己的版本)。 Postgres 版本在这里是相关的。 (SELECT version())。最佳索引策略还将考虑您提到的hour 列(与timestamp1 相关的混淆)。披露确切的表定义(CREATE TABLE 显示数据类型和约束的语句)、基数、典型读/写活动以及更多关于典型查询的信息。此处的说明:stackoverflow.com/tags/postgresql-performance/info

标签: sql postgresql indexing postgresql-performance


【解决方案1】:

这取决于您的数据库架构和您正在执行的查询。只有在您的情况下同时实施这两种方法才能为您提供关于哪一种对您有好处的最佳答案。

PostgreSQL 能够在单个查询中使用多个索引,这是一个很棒的功能。

通过快速谷歌搜索,我找到了关于这个主题的一些非常好的答案。请检查以下链接: Multiple indexes vs single index on multiple columns in postgresql

【讨论】:

  • 谢谢!我会检查这个
【解决方案2】:

在你的情况下:

其中 timestamp1 = 'sometimestamp' 的查询使用 op 1 where id13 = someid13 的查询使用 op 1

其中 timestamp1 = 'sometimestamp' 和 id13 = someid13 的查询可能使用 op 2

查询 where id13 = someid13 and timestamp1 = 'sometimestamp' ,可以使用 op 1 或 op 2

为什么?因为一个索引选择涉及很多东西,基数、大小、统计、后选择操作等等。

记住,op 2 覆盖了 op 1 的第一个。

【讨论】:

  • 我有大约 50 个查询来测试我的表。只有 2 个有这样的查询,其中 timestamp1 = 'sometimestamp' 和 id13 = someid13,可能使用 op 2 ...其余的只使用 timestamp1在 where 子句中...你认为我应该选择哪个选项?
  • 请分享您的查询解释、统计数据和 pg 版本,以查看更多详细信息。一个小列索引比多列索引好
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 2014-08-06
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多