From 5f1824742d5adc2968532f67b9084974e995708c Mon Sep 17 00:00:00 2001 From: Schuyler Erle Date: Sat, 27 Aug 2011 18:26:00 -0700 Subject: [PATCH] Add .similar_features() method to Feature --- gazetteer/places/models.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/gazetteer/places/models.py b/gazetteer/places/models.py index 1257507..e5057fc 100644 --- a/gazetteer/places/models.py +++ b/gazetteer/places/models.py @@ -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'),