Add .similar_features() method to Feature

This commit is contained in:
Schuyler Erle 2011-08-27 18:26:00 -07:00
parent 195e8b3931
commit 5f1824742d

View File

@ -22,7 +22,7 @@ class FeatureSearchManager(manager.GeoManager):
if text:
text = text.replace("'", "''") # escape the '
# use the pg_trgm index
qset = qset.extra(where=["preferred_name %% '%s']" % text)
qset = qset.extra(where=["preferred_name %% '%s'" % text])
return qset
class Feature(models.Model):
@ -65,6 +65,34 @@ class Feature(models.Model):
return ''
time_end.short_description = "End Date"
def similar_features(self, max_distance=15000, scale_factor=2000):
cursor = connection.cursor()
name = unicode(self).replace("'", "''") # escape '
cursor.execute("""
SELECT *, %f * similarity / distance AS score FROM (
SELECT url, preferred_name, feature_type,
admin1, admin2, is_primary,
similarity(preferred_name, '%s') AS similarity,
st_distance_sphere(geometry, '%s') AS distance
FROM places_feature
WHERE geometry && st_buffer('%s', %f)
AND preferred_name % '%s'
) AS whatever
WHERE %f * similarity / distance >= 1.0
ORDER BY similarity / distance DESC"""
% (scale_factor, name, self.geometry, self.geometry,
max_distance*0.00001, name, scale_factor)
)
result_list = []
fields = ('url', 'preferred_name', 'feature_type', 'admin1', 'admin2', 'is_primary')
for row in cursor.fetchall():
vals = dict(zip(fields, row[:len(fields)]))
p = type(self)(**vals)
p.similarity = row[-3]
p.distance = row[-2]
p.score = row[-1]
result_list.append(p)
return result_list
LANGUAGE_CHOICES = (
('en', 'English'),