Postgres 没有使用部分索引

Postgres is not using partial index

我尝试使用部分索引计算 table 中的 id,但性能非常低

SELECT COUNT("refuel_request"."refuel_request_id") as "count" 
FROM "refuel_request" 
WHERE "refuel_request"."refuel_request_status_id" 
IN ('1','2','3')

我创建了索引

CREATE INDEX idx_refuel_request_status_id10 ON refuel_request (refuel_request_status_id)
WHERE "refuel_request"."refuel_request_status_id" 
IN ('1','2','3')

你能解释一下我做错了什么吗?

解释一下

[
 {
"Plan": {
  "Node Type": "Seq Scan",
  "Parallel Aware": false,
  "Relation Name": "refuel_request",
  "Alias": "refuel_request",
  "Startup Cost": 0,
  "Total Cost": 160442.88,
  "Plan Rows": 4700100,
  "Plan Width": 16,
  "Filter": "(refuel_request_status_id = ANY ('{1,2,3}'))"
   }
  }
 ]

解释(分析,缓冲区)

解释(分析、格式化文本)

Finalize Aggregate  (cost=114931.68..114931.69 rows=1 width=8) (actual time=570.019..570.020 rows=1 loops=1)
  ->  Gather  (cost=114931.47..114931.68 rows=2 width=8) (actual time=569.735..575.504 rows=3 loops=1)
        Workers Planned: 2
        Workers Launched: 2
        ->  Partial Aggregate  (cost=113931.47..113931.48 rows=1 idth=8) (actual time=528.094..528.094 rows=1 loops=3)
              ->  Parallel Seq Scan on refuel_request cost=0.00..109035.53 rows=1958375 width=16) (actual time=0.070..452.908 rows=1566700 loops=3)
                    Filter: (refuel_request_status_id = ANY ('{1,2,3}'))
Planning Time: 0.665 ms
Execution Time: 575.538 ms

过滤器在顺序扫描中没有删除任何行,因此 table 中的所有行似乎都具有 refuel_request_status_id 等于 '1''2''3'。所以索引中的 WHERE 条件没有影响。

您可以尝试 enable_seqscan = off 看看 PostgreSQL 是否做出了正确的选择。如果不是,可能 random_page_cost 没有为您的硬件正确设置。

如果事实证明顺序扫描确实是最快的方法,那么您可以做很多事情来加快查询速度:您可以获得更快的存储空间或更多的 RAM 来缓存 table .

Counting is slow business.