<div class="gmail_quote">On Tue, Jul 23, 2013 at 2:17 AM, Ilia <span dir="ltr"><<a href="mailto:ilia@lobsanov.com" target="_blank">ilia@lobsanov.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">Thanks David for your feedback. I got it down to 4ms or so. Below is the explain analyze. It's 2 subqueries now. Any ideas for simplification of the query?<br><div dir="ltr"><div><br></div><div><div>explain analyze WITH knn_query AS</div>


<div>(</div><div> SELECT</div><div> *</div><div> FROM places</div><div class="im"><div> WHERE "places"."place_category_id" = 10</div></div><div class="im"><div> ORDER by geom <#> 'SRID=4326;POINT(-79.3937393 43.6526704)' LIMIT 50</div>


<div> )</div></div><div class="im"><div>SELECT *,</div><div>ST_Distance_Sphere(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') as distance</div></div><div>FROM (</div><div>SELECT * FROM knn_query</div><div>ORDER BY ST_Distance(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') ASC</div>


<div>LIMIT 5</div><div>) places;</div><div></div></div></div></div></blockquote><div><br></div></div>I thought maybe:<br><br>SELECT *,ST_Distance_Sphere(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') as distance<br>
FROM (SELECT * FROM places<br>      WHERE "places"."place_category_id" = 10<br>      ORDER by geom <#> 'SRID=4326;POINT(-79.3937393 43.6526704)'<br>      LIMIT 50) AS places<br>ORDER BY ST_Distance(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') ASC<br>
LIMIT 5;<br><br><br>I don't think you really need the extra nest level in the sub query for the one you wrote, but I assume you added it because you tried to do ORDER BY distance? and got an error?<br>The good news is that ST_Distance is an immutable function, so PostgreSQL likely won't execute it twice for the same inputs on the same query.<br>
I also noticed you are using both ST_Distance_Sphere and ST_Distance(), is this meant? I'm quite new to postgis, but I think the only difference is ST_Distance_Sphere is faster is it's not working with a complex spheroid shape. So if you're doing this for performance then it's not a good idea as it means 2 functions need executed instead of 1 (at least with my query).<br>
<br>SELECT *,ST_Distance(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') as distance<br>FROM (SELECT * FROM places<br>      WHERE "places"."place_category_id" = 10<br>      ORDER by geom <#> 'SRID=4326;POINT(-79.3937393 43.6526704)'<br>
      LIMIT 50) AS places<br>ORDER BY ST_Distance(geom, 'SRID=4326;POINT(-79.3937393 43.6526704)') ASC<br>LIMIT 5;<br><br>Will likely be slightly faster, though I highly doubt you'll notice much difference on 5 rows. But obviously it will give slightly different results.<br>
<br>I take it you're happy enough with the 4ms from 200ms?<br><br>Regards<br><br>David<br>