1

I use mapnik to render map with datasources from a PostGIS database. One query is a join on two table, one with a geometry (a polygon) and the other one with some fields I want to use for rendering. Unfortunately, this query is very slow...

Here is the slow query:

SELECT table1.id, table1.geometry, table2.fk_table1, table2.field FROM table1
INNER JOIN table2 ON (table1.id = table2.fk_table1)
WHERE table1.geometry && SetSRID('BOX3D(x1 y1, x2 y2)'::box3d,900913);

Here is the query plan I got from an EXPLAIN:

Hash Join (cost=118896.94..262210.34 rows=27942 width=1099)
 Hash Cond: (table1.id = table2.fk_table1)
 -> Seq Scan on table2 (cost=0.00..73740.89 rows=4786689 width=16)
 -> Hash (cost=113876.63..113876.63 rows=33865 width=1083)
 -> Bitmap Heap Scan on table1 (cost=1112.15..113876.63 rows=33865 width=1083)

This query can be faster if the bbox is first applied on table1.geometry. However, mapnik does not help me there. Indeed, mapnik builds a query from a table/subquery by adding a WHERE clause on it

 SELECT AsBinary("geometry") AS geom
 FROM subquery 
 WHERE "geometry" && SetSRID('BOX3D(x1 y1,x2 y2)'::box3d,900913)

With the following subquery:

( SELECT table1.id, table1.geometry, table2.fk_table1, table2.field FROM table1
INNER JOIN table2 ON (table1.id = table2.fk_table1) ) as subquery

Basically, I need to enhance the speed of this query knowing that mapnik will add a where clause on the subquery.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 13, 2012 at 15:58
1
  • As Nickas said it, the main issue comes from the seq scan of the table2 even if there is an index on this table. To solve this, I change the parameter random_page_cost to favor the index scan: ALTER TABLESPACE pg_global SET ( random_page_cost = 2, seq_page_cost=1); This solved my performance issue. Commented Feb 14, 2012 at 14:05

1 Answer 1

3

I don't think a bbox anywhere can make the join faster. WHat is needed is a working index on table1.id and table2.fk_table1.

The bbox gist index filter will be more costly than joining on indexed integer columns.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Feb 14, 2012 at 13:10
1
  • You're absolutely right, I just posted an answer here. Commented Feb 14, 2012 at 14:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.