From 0cf8fae70bf4aa36843d90764ad8fb341006e954 Mon Sep 17 00:00:00 2001 From: Schuyler Erle Date: Tue, 28 Feb 2012 18:55:35 +0530 Subject: [PATCH] Somewhat re-thought TrigramSearchManager. --- chaloBEST/mumbai/models.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/chaloBEST/mumbai/models.py b/chaloBEST/mumbai/models.py index e5e81a4..da00dc0 100644 --- a/chaloBEST/mumbai/models.py +++ b/chaloBEST/mumbai/models.py @@ -43,26 +43,32 @@ SCHED = { } class TrigramSearchManager(models.Manager): + def __init__(self, trigram_columns, *args, **kwargs): + super(models.Manager, self).__init__(*args, **kwargs) + self.trigram_columns = trigram_columns + def set_threshold(self, threshold): """Set the limit for trigram similarity matching.""" cursor = connection.cursor() cursor.execute("""SELECT set_limit(%f)""" % threshold) - def find_approximate(self, match=0.5, **kwargs): + def find_approximate(self, text, match=0.5): self.set_threshold(match) - assert(len(kwargs) == 1) - column, value = kwargs.items()[0] + similarity_measure = "max(%s)" % ",".join(["similarity(%s, %%s)" % col for col in self.trigram_columns]) + similarity_filter = " OR ".join(["%s %%%% %%s" % col for col in self.trigram_columns]) + text_values = [text] * len(self.trigram_columns) + qset = self.get_query_set() # use the pg_trgm index via the % operator - qset = qset.extra(select={"similarity":"similarity(" + column + ", %s)"}, - select_params=[value], - where=[column + " %% %s"], - params=[value], + qset = qset.extra(select={"similarity":similarity_measure, + select_params=text_values, + where=similarity_filter, + params=text_values, order_by=["-similarity"]) return qset class Area(models.Model): - objects = TrigramSearchManager() # name, name_mr + objects = TrigramSearchManager("name", "name_mr", "display_name") code = models.IntegerField() #primary_key=True) slug = models.SlugField(null=True) name = models.TextField(blank=True, max_length=255) @@ -111,9 +117,8 @@ class Fare(models.Model): def __unicode__(self): return str(self.slab) - class Stop(models.Model): - objects = TrigramSearchManager() # name, display, name_mr + objects = TrigramSearchManager("name", "name_mr", "display_name") code = models.IntegerField() slug = models.SlugField(null=True) name = models.TextField(blank=True, max_length=255)