PostgreSQL时间戳索引未使用

时间:2019-02-19 09:30:06

标签: sql postgresql indexing

我正在尝试通过添加索引来减少此查询的费用,但看来我做错了方法

SELECT associations.virtual_phone_number
FROM associations
WHERE associations.expires_at > '2019-02-15 10:38:25+00'
GROUP BY associations.virtual_phone_number
HAVING COUNT(associations.id) >= 100;

解释/分析结果:

explain analyze SELECT associations.virtual_phone_number FROM associations WHERE associations.expires_at > '2019-02-15 10:38:25+00' GROUP BY associations.virtual_phone_number HAVING COUNT(associations.id) >= 100;

HashAggregate  (cost=3422.26..3443.05 rows=2079 width=12) (actual time=38.583..38.583 rows=0 loops=1)
  Group Key: virtual_phone_number
  Filter: (count(id) >= 100)
  Rows Removed by Filter: 2073
  ->  Seq Scan on associations  (cost=0.00..3174.00 rows=49651 width=28) (actual time=0.011..23.061 rows=49376 loops=1)
        Filter: (expires_at > '2019-02-15 10:38:25+00'::timestamp with time zone)
        Rows Removed by Filter: 50624
Planning time: 0.507 ms
Execution time: 38.637 ms

我已经尝试了以下索引:

CREATE INDEX associations_test_1 ON "associations" (expires_at, virtual_phone_number, id);
CREATE INDEX associations_test_2 ON "associations" (expires_at, id,virtual_phone_number);
CREATE INDEX associations_test_3 ON "associations" (id,virtual_phone_number,expires_at);
CREATE INDEX associations_test_4 ON "associations" (virtual_phone_number,id,expires_at);
CREATE INDEX associations_test_5 ON "associations" (virtual_phone_number,expires_at,id);
CREATE INDEX associations_test_6 ON "associations" (id,expires_at,virtual_phone_number);

这是现有的索引:

CREATE UNIQUE INDEX associations_pkey ON associations(id uuid_ops);
CREATE INDEX associations_retrieve_from_call ON associations(virtual_phone_number text_ops,caller_phone_number text_ops,expires_at timestamptz_ops);
CREATE INDEX associations_caller_expires ON associations(caller_phone_number text_ops,expires_at timestamptz_ops);
CREATE INDEX associations_expires_at ON associations(expires_at timestamptz_ops);
CREATE INDEX associations_callee_expires ON associations(callee_phone_number text_ops,expires_at timestamptz_ops);
CREATE INDEX associations_user_id_expires ON associations(user_id text_ops,expires_at timestamptz_ops);

表架构:

CREATE TABLE associations (
    id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
    ride_id character varying(255) NOT NULL,
    user_id character varying(255) NOT NULL,
    caller_phone_number character varying(255) NOT NULL,
    callee_phone_number character varying(255) NOT NULL,
    virtual_phone_number character varying(255) NOT NULL,
    expires_at timestamp with time zone NOT NULL,
    created_at timestamp with time zone NOT NULL DEFAULT NOW(),
    updated_at timestamp with time zone NOT NULL DEFAULT NOW()
);

我是否缺少有关timestamp上的索引的信息,或者PG的预期行为是?

0 个答案:

没有答案