这是我的查询:
SELECT
i::date AS day,
(SELECT COUNT(*) FROM genericevent WHERE event = 'chat_message' AND eventDate::date = i::date AND extra1 = 'public') AS message_public_total,
(SELECT COUNT(*) FROM genericevent WHERE event = 'chat_message' AND eventDate::date = i::date AND extra1 = 'public' AND extra2 = 'clean') AS message_public_clean
FROM generate_series('2013-08-01', '2013-08-27', INTERVAL '1 day') i
我有一个索引,作为人类,我认为它完全可用于此查询(实际上它应该导致仅索引扫描):
CREATE INDEX idx__genericevent__event__extra1__date
ON genericevent
USING btree
(event COLLATE pg_catalog."default", extra1 COLLATE pg_catalog."default", eventDate);
然而,正如EXPLAIN
ed 所说,PostgreSQL 并不这么认为。它使用event
和extra1
来自这个索引,但不是eventDate
(见Index Cond
行):
"Function Scan on generate_series i (cost=0.00..145219698.17 rows=1000 width=8)"
" SubPlan 1"
" -> Aggregate (cost=72274.87..72274.88 rows=1 width=0)"
" -> Bitmap Heap Scan on genericevent (cost=11367.74..72271.51 rows=1345 width=0)"
" Recheck Cond: (((event)::text = 'chat_message'::text) AND ((extra1)::text = 'public'::text))"
" Filter: ((eventDate)::date = (i.i)::date)"
" -> Bitmap Index Scan on idx__genericevent__event__extra1__date (cost=0.00..11367.40 rows=269012 width=0)"
" Index Cond: (((event)::text = 'chat_message'::text) AND ((extra1)::text = 'public'::text))"
" SubPlan 2"
" -> Aggregate (cost=72944.79..72944.80 rows=1 width=0)"
" -> Bitmap Heap Scan on genericevent (cost=11367.50..72943.80 rows=396 width=0)"
" Recheck Cond: (((event)::text = 'chat_message'::text) AND ((extra1)::text = 'public'::text))"
" Filter: (((extra2)::text = 'clean'::text) AND ((eventDate)::date = (i.i)::date))"
" -> Bitmap Index Scan on idx__genericevent__event__extra1__date (cost=0.00..11367.40 rows=269012 width=0)"
" Index Cond: (((event)::text = 'chat_message'::text) AND ((extra1)::text = 'public'::text))"
eventDate::date
我认为这可能需要演员做点什么。如何更改查询或索引以提高性能?
为了完整起见,下表是:
CREATE TABLE genericevent
(
id bigint NOT NULL,
eventDate timestamp with time zone NOT NULL,
event character varying(50) NOT NULL,
extra1 character varying(100),
extra2 character varying(100),
CONSTRAINT genericevent_pkey PRIMARY KEY (id)
)