<div dir="ltr">Hi,<div><br></div><div>Put the KNN operator in a LATERAL subquery, using LIMIT x to limit NN to x elements:</div><div><br></div><div><div>SELECT</div><div>  <a href="http://p1.id">p1.id</a>,</div><div>  <a href="http://t.id">t.id</a> AS id2,</div><div>  t.dist</div><div>FROM parc p1</div><div>  CROSS JOIN LATERAL</div><div>             (SELECT</div><div>                <a href="http://p2.id">p2.id</a>,</div><div>                st_distance(p1.geom, p2.geom) AS dist</div><div>              FROM parc p2</div><div>              WHERE <a href="http://p1.id">p1.id</a> <> <a href="http://p2.id">p2.id</a></div><div>              ORDER BY p1.geom <-> p2.geom</div><div>              LIMIT 1) AS t</div><div>ORDER BY <a href="http://p1.id">p1.id</a>, t.dist;</div></div><div><br></div><div>Nicolas</div></div><div class="gmail_extra"><br><div class="gmail_quote">On 30 May 2018 at 23:07, Vispo Leblanc <span dir="ltr"><<a href="mailto:vispoleblanc@gmail.com" target="_blank">vispoleblanc@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr"><div>Hello PostGIS users, <br></div><div><br></div><div>I am looking for a way to increase the speed of my query with KNN. <br></div><div><br></div><div>I have two tables with millions of points in each table. I would like to find the nearest neighbor (only one) of my points in table A with my points in table B.</div><div><br></div><div>I wrote the following query: <br></div><div><br></div><div>WITH index_query as (<br>  SELECT<br>    <a href="http://t1.id" target="_blank">t1.id</a>,<br>    t1.geom AS geom,<br>    t2.geom AS geom2, <br>    t1.geom <-> t2.geom AS distance<br>  FROM research_scrapper.table1 t1, <br>      research_scrapper.table2 t2<br>  ORDER BY t1.geom <-> t2.geom<br>)<br>SELECT tbl.cas_id, tbl.geom <br>FROM index_query tbl<br>INNER JOIN<br>    (<br>        SELECT geom2, <br>               MIN(distance) as distance<br>        FROM index_query <br>        GROUP BY geom2<br>    )tbl1<br>    ON tbl1.geom_generated=tbl.geom_<wbr>generated<br>    AND tbl1.distance = tbl.distance<br></div><div><br></div><div>This is taking forever, would you have any suggestions on how to increase the efficiency?</div><div><br></div><div>Thanks for your help,</div><div><br></div></div>
<br>______________________________<wbr>_________________<br>
postgis-users mailing list<br>
<a href="mailto:postgis-users@lists.osgeo.org">postgis-users@lists.osgeo.org</a><br>
<a href="https://lists.osgeo.org/mailman/listinfo/postgis-users" rel="noreferrer" target="_blank">https://lists.osgeo.org/<wbr>mailman/listinfo/postgis-users</a><br></blockquote></div><br></div>