How to SELECT "closest" rows from another table?
This would achieve it:

SELECT m1.id1, m2.*
FROM   map1 m1
CROSS  JOIN LATERAL (
   SELECT ST_HausdorffDistance(m1.g1, m2.g2) AS h_dist, m2.id2, m2.g2
   FROM   map2 m2
   WHERE  ST_HausdorffDistance(m1.g1, m2.g2) &lt; 2
   ORDER  BY 1, 2
   LIMIT  2
   ) m2;


Returns 1 or 2 rows for every row in map1, extended with the top 2 corresponding row(s) in map2 (as defined by minimum Hausdorff distance) and the said Hausdorff distance between them. If there is no row with Hausdorff distance &lt; 2 in map2, no row is returned.

Key element is the LATERAL subquery. There are variants of this query, depending on exact (missing) requirements. Related:


OFFSET and LIMIT on complex query
How to make DISTINCT ON faster in PostgreSQL?
How to speed up querying last values in a time series?
Optimise a LATERAL JOIN query on a big table


I wouldn't know of any way to use an index here. So this is going to be an expensive query.