Very slow bitmap heap scan in Postgres

indexing, performance, postgresql

Solution

The slow part is obviosly fetching the data from the tables, since the index access seems to be very fast. You might either optimize your RAM usage parameters (see http://wiki.postgresql.org/wiki/Performance_Optimization and http://www.varlena.com/GeneralBits/Tidbits/perf.html), or optimize the layout of the data in the table by issuing a CLUSTER command (see http://www.postgresql.org/docs/8.3/static/sql-cluster.html).

CLUSTER "TrafficData" USING "RoadDate_Idx";

should do it.

Problem

I have the following simple table that contains traffic measurement data: ``` CREATE TABLE "TrafficData" ( "RoadID" character varying NOT NULL, "DateID" numeric NOT NULL, "ExactDateTime" timestamp NOT NULL, "CarsSpeed" numeric NOT NULL, "CarsCount" numeric NOT NULL ) CREATE INDEX "RoadDate_Idx" ON "TrafficData" USING btree ("RoadID", "DateID"); ``` The column RoadID uniquely identifies the road whose data is being recorded, while DateID identifies the day of the year (1..365) of the data - basically a rounded off representation of ExactDateTime. I have about 100.000.000 rows; there are 1.000 distinct values in the column "RoadID" and 365 distinct values in the column "DateID". I then run the following query: ``` SELECT * FROM "TrafficData" WHERE "RoadID"='Station_1' AND "DateID">20100610 AND "DateID"<20100618; ``` This takes up to three mind-boggling seconds to finish, and I cannot for the life of me figure out WHY. EXPLAIN ANALYZE gives me the following output: ``` Bitmap Heap Scan on "TrafficData" (cost=104.84..9743.06 rows=2496 width=47) (actual time=35.112..2162.404 rows=2016 loops=1) Recheck Cond: ((("RoadID")::text = 'Station_1'::text) AND ("DateID" > 20100610::numeric) AND ("DateID" < 20100618::numeric)) -> Bitmap Index Scan on "RoadDate_Idx" (cost=0.00..104.22 rows=2496 width=0) (actual time=1.637..1.637 rows=2016 loops=1) Index Cond: ((("RoadID")::text = 'Station_1'::text) AND ("DateID" > 20100610::numeric) AND ("DateID" < 20100618::numeric)) Total runtime: 2163.985 ms ``` My specs: - Windows 7 - Postgres 9.0 - 4GB RAM I'd greatly appreciate any helpful pointers!

Original source