0

Which way is correct? Use distance or buffer? I am not sure about this.

Here is how I use distance:

cursor.execute(""" SELECT COUNT(tw.user_id)
               FROM tweets tw, ca_census_tract ce
               WHERE ST_Distance(ST_Transform(tw.location,26986),
               ST_Transform(ce.geom,26986))>=160934 
               AND ce.name10='Alameda'; """)

cursor.fetchall()

and here is how I use buffer:

cursor.execute(""" SELECT COUNT(tw.user_id)
               FROM tweets tw, ca_census_tract ce
               WHERE ST_within(ST_Transform(tw.location,26986),
               ST_Buffer(ST_Transform(ce.geom,26986), 160934))=false
               AND ce.name10='Alameda'; """)

cursor.fetchall()

The tw.location are points.


There was a small difference in the result and a huge difference in running time. The result from distance was 14818 and the result from buffer was 14899. I don't understand why there was a difference. And, the running time of buffer was much longer. By the way, the total number of the dataset was 100K.

2
  • 1
    do you get different answers? or is one faster than the other?
    – Ian Turton
    Commented Oct 5, 2016 at 16:53
  • I don't think they have the same answer. The buffer case seems won't stop once I ran it. Commented Oct 5, 2016 at 17:23

1 Answer 1

2

ST_Distance() or ST_DWithin() are much better in this context.

If you use ST_Buffer(), you add the expensive operation of creating a new geometry. Also, you won't be able to use a spatial index that you may have in place. The other two options avoid this.

You should get the same answer, however.

EDIT: See the important qualifier in the comments below, that the spatial index still won't be used if you are nesting a ST_Transform within ST_DWithin().

3
  • Oh! no wonder why the running time of buffer was so long! Thank you very much! And by the way, the way I use within() was correct for finding points outside the county right? Make it equal to false and set the name to the county. Commented Oct 5, 2016 at 17:36
  • within() should work, but a cleaner way to do it is WHERE ST_DWithin(ST_Transform(tw.location,26986), ST_Transform(ce.geom,26986), 160934)
    – amball
    Commented Oct 5, 2016 at 20:04
  • 1
    All these ST_Transform() nested in the ST_DWithin() mean you're probably getting no help at all from the spatial index, which is built on the bare column. Either transform your data to the working projection in the table itself, or build a functional index on ST_Transform(). Commented Oct 6, 2016 at 13:29

Your Answer

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

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