Я пытаюсь снизить стоимость этого запроса путем добавления индексов, но, похоже, я делаю это неправильно
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?