0

I have two Postgres tables: one normal table (20M rows), and one materialized view (2M rows). Both tables have an index on the "time" column. On both tables, I'm running a query which aggregates over a date range. When I run the query on the normal table, Postgres uses an Index Scan, which takes about 1 second. However, on the materialized view, Postgres uses a Bitmap Index Scan, which takes about 7 seconds. I'm not sure why it's not using a normal Index Scan here.

Both tables are roughly similar; the materialized view has 3 extra columns (2 floats and a boolean). The tables both have indices on their id column and time column; in the normal table, the id column is a primary key. Both tables have been VACUUM ANALYZEd.

The query is as follows:

SELECT count(*) as post_count,
    sum(CASE WHEN in_reply_to_post_id IS NULL THEN 0 ELSE 1 END) as replies,
    date_trunc('hour', time) as time_interval
FROM posts_enriched_materialized_2_weeks
WHERE time >= '2019-10-10' AND time < '2019-10-11'
GROUP BY time_interval;

The results of EXPLAIN ANALYZE on the materialized view are as follows:

GroupAggregate  (cost=264262.43..268387.60 rows=158191 width=32) (actual time=7794.743..7893.961 rows=24 loops=1)
  Group Key: (date_trunc('hour'::text, "time"))
  ->  Sort  (cost=264262.43..264691.99 rows=171822 width=46) (actual time=7790.080..7838.184 rows=175691 loops=1)
        Sort Key: (date_trunc('hour'::text, "time"))
        Sort Method: external merge  Disk: 5464kB
        ->  Bitmap Heap Scan on posts_enriched_materialized_2_weeks  (cost=4057.61..244033.53 rows=171822 width=46) (actual time=21.184..7672.166 rows=175691 loops=1)
              Recheck Cond: (("time" >= '2019-10-10 00:00:00'::timestamp without time zone) AND ("time" < '2019-10-11 00:00:00'::timestamp without time zone))
              Heap Blocks: exact=17420
              ->  Bitmap Index Scan on posts_enriched_materialized_2_weeks_time_index  (cost=0.00..4014.65 rows=171822 width=0) (actual time=18.551..18.551 rows=175691 loops=1)
                    Index Cond: (("time" >= '2019-10-10 00:00:00'::timestamp without time zone) AND ("time" < '2019-10-11 00:00:00'::timestamp without time zone))
Planning time: 0.106 ms
Execution time: 7894.874 ms

EDIT: The results of EXPLAIN ANALYZE on the non-MV table are as follows:

GroupAggregate  (cost=193490.77..197635.89 rows=150641 width=32) (actual time=1168.018..1267.225 rows=24 loops=1)
  Group Key: (date_trunc('hour'::text, "time"))
  ->  Sort  (cost=193490.77..193943.19 rows=180969 width=46) (actual time=1163.293..1210.887 rows=175701 loops=1)
        Sort Key: (date_trunc('hour'::text, "time"))
        Sort Method: external merge  Disk: 5472kB
        ->  Index Scan using posts_time_index on tweets  (cost=0.44..172118.80 rows=180969 width=46) (actual time=0.900..1065.469 rows=175701 loops=1)
              Index Cond: (("time" >= '2019-10-10 00:00:00'::timestamp without time zone) AND ("time" < '2019-10-11 00:00:00'::timestamp without time zone))
Planning time: 0.514 ms
Execution time: 1268.219 ms

Below is the correlation of the time column for each table, requested in the comments. I don't exactly know what this value refers to, but it looks incredibly relevant:

posts   0.8844374
posts_enriched_materialized_2_weeks 0.09846322
9
  • The Bitmap Index/Heap Scan isn't what's slowing down your MV query. Rather, it's the external merge Disk: 5464kB that takes most of the time. What's your work_mem setting? Maybe you can increase it to at least 6MB?
    – richyen
    Oct 18, 2019 at 0:05
  • Really? actual time for the sort is 7838msec, and the Bitmap Index Scan only takes 18msec
    – richyen
    Oct 18, 2019 at 0:20
  • Please also show the explain plan on the other table.
    – jjanes
    Oct 18, 2019 at 0:21
  • 1
    This explained everything: cybertec-postgresql.com/en/column-correlation-explained Specifically, it says "The PostgreSQL optimizer will prefer index scans if the correlation is close to 1 or -1." That explains a lot. Looks like I'll need to cluster the materialized view after refreshing it. Oct 18, 2019 at 0:56
  • 1
    Aside: replace sum(CASE WHEN in_reply_to_post_id IS NULL THEN 0 ELSE 1 END) with the equivalent count(in_reply_to_post_id). Simpler and probably a bit faster. Oct 18, 2019 at 3:35

1 Answer 1

4

With the low correlation, the planner thinks that if it does an ordinary index scan, it will be hopping all over the table (materialized view) to get the indicated rows, causing a lot of random IO which is much slower than sequential IO. By doing a bitmap scan, it ameliorates this because the bitmap inherently "sorts" the rows from the index into the order in which it will find them in the table, making the table read more sequential.

With a high correlation, it will naturally read the table more or less in order when doing a regular index scan, because the table and the index are in mostly the same order. Also, it will be reading a smaller part of the table. If the correlation was perfect and you read 1/100 of the index, you would only read about 1/100 of the pages that make up the table, and would do so sequentially. Because you are already getting sequential reads, switching to a bitmap scan doesn't give you any benefit, but it does have a cost.

In your case, this amelioration didn't seem to work very well. It could be that the data you need is sparse enough in the materialized view that reading it in order still looks more random than sequential from the IO system's perspective.

Another issue could be that your table is frequently used, and so "hot" in the cache, while your materialized view is rarely used and so "cold". This would not explain why it chose a bitmap scan, but would explain why the bitmap scan was not very effective.

You can add an "order by time" to the definition of the materialized view to cluster it by the time column.

If that doesn't solve it, then increasing "effective_io_concurrency" could help, particularly if you have RAID or JBOD. By having the bitmap heap scan try to prefetch pages from all the various spindles, it can increase your IO throughput.

6
  • Thanks for the answer! Adding ORDER BY time DESC to the materialized view's definition worked super well at first. However, after refreshing the materialized view a number of times over the weekend, it looks like the correlation on time is back down to almost 0, and the materialized view has gone back to using bitmap index scans. Do you know why that might be? Thanks! Oct 21, 2019 at 23:29
  • Additional update: I tried refreshing the materialized view non-concurrently (as opposed to concurrently, which I usually use), and the correlation became -1. I suppose this has something to do with how refreshing interacts with the order of the rows on disk. Do you know how I might be able to get this behavior with concurrent refreshes? Thanks! Oct 21, 2019 at 23:48
  • I don't think the "concurrently" can strictly adhere to the "order by", but this does surprise me. When it went back to the bitmap scan, did it also go back to the old slow speed? When refreshing concurrently, how much other activity was there on the table?
    – jjanes
    Oct 22, 2019 at 16:08
  • Yes, the bitmap scan was the same speed as it was before. Additionally, when refreshing concurrently, there was no activity on the table. Oct 22, 2019 at 17:53
  • Could you show the definition of the materialized view? Or at least describe it, aggregations, joins, etc.
    – jjanes
    Oct 22, 2019 at 18:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.