简体   繁体   English

PostgreSQL 索引未用于查询

[英]PostgreSQL Index Isn't Used on Query

so I have PostgreSQL database with table that track the movement and fuel level of equipment with millions of rows所以我有 PostgreSQL 数据库,其中包含数百万行跟踪设备的运动和燃料水平的表

记录

and to make query faster when I create index on time column with this command:并在使用此命令在time列上创建索引时使查询更快:

create index gpsapi__index__time on gpsapi (time);

When I tried to run simple command with "EXPLAIN ANALYZE" like this当我尝试像这样使用“EXPLAIN ANALYZE”运行简单命令时

EXPLAIN ANALYZE
SELECT *
FROM gpsapi g
WHERE g.time >= NOW() - '1 months'::interval;

it doesn't show that the query uses the index I created它没有显示查询使用我创建的索引输出

Do you know how to solve this?你知道如何解决这个问题吗? Thanks!谢谢!

If you read the execution plan closely, you'll see that Postgres is telling you that out of about 6 million records, 5.5 million matched (> 90%).如果您仔细阅读执行计划,您会发现 Postgres 告诉您,在大约 600 万条记录中,有 550 万条匹配(> 90%)。 Based on statistics, it is likely that Postgres realized that it would be returning a large percentage of total records in the table, and that it would be faster to just forgo using the index and scan the entire table.根据统计数据,Postgres 很可能意识到它将返回表中总记录的很大一部分,并且放弃使用索引并扫描整个表会更快。

The concept to understand here is that, while the index you defined does potentially let Postgres throw away non matching records very quickly, it actually increases the time needed to lookup the values in SELECT * .这里要理解的概念是,虽然您定义的索引确实可能让 Postgres 很快丢弃不匹配的记录,但它实际上增加了查找SELECT *中的值所需的时间。 The reason for this is that, upon hitting the leaf node in the index, Postgres must then do a seek back to the clustered index/table to find the column values.这样做的原因是,在命中索引中的叶节点时,Postgres 必须然后回溯到聚集索引/表以查找列值。 Assuming your query would return most of the table, it would be faster to just scan the table directly.假设您的查询将返回大部分表,那么直接扫描表会更快。

This being said , there is nothing at all inherently wrong with your index.话虽如此,您的索引本质上没有任何问题。 If your query used a more narrow range, or searched for a specific timestamp, such that the expected result set were sufficiently small, then Postgres likely would have used the index.如果您的查询使用了更窄的范围,或者搜索了特定的时间戳,使得预期的结果集足够小,那么 Postgres 可能会使用该索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM