From fd24117c27f330bef0e6912e366f4b84df714c99 Mon Sep 17 00:00:00 2001 From: smilerz Date: Sun, 11 Apr 2021 19:07:50 -0500 Subject: [PATCH] command line to rebuild index --- cookbook/management/commands/rebuildindex.py | 27 ++++++++++++++++++++ cookbook/managers.py | 9 ++++--- 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 cookbook/management/commands/rebuildindex.py diff --git a/cookbook/management/commands/rebuildindex.py b/cookbook/management/commands/rebuildindex.py new file mode 100644 index 00000000..d123e9d5 --- /dev/null +++ b/cookbook/management/commands/rebuildindex.py @@ -0,0 +1,27 @@ +from django.conf import settings +from django.contrib.postgres.search import SearchVector +from django.core.management.base import BaseCommand, CommandError +from django_scopes import scopes_disabled +from django.utils.translation import gettext_lazy as _ + +from cookbook.models import Recipe + + +# can be executed at the command line with 'python manage.py rebuildindex' +class Command(BaseCommand): + help = _('Rebuilds full text search index on Recipe') + + def handle(self, *args, **options): + if settings.DATABASES['default']['ENGINE'] not in ['django.db.backends.postgresql_psycopg2', 'django.db.backends.postgresql']: + self.stdout.write(self.style.WARNING(_('Only Postgress databases use full text search, no index to rebuild'))) + + try: + with scopes_disabled(): + search_vector = ( + SearchVector('name', weight='A') + + SearchVector('description', weight='B')) + Recipe.objects.all().update(search_vector=search_vector) + + self.stdout.write(self.style.SUCCESS(_('Recipe index rebuild complete.'))) + except: + self.stdout.write(self.style.ERROR(_('Recipe index rebuild failed.'))) diff --git a/cookbook/managers.py b/cookbook/managers.py index 5650d073..64addf4d 100644 --- a/cookbook/managers.py +++ b/cookbook/managers.py @@ -20,9 +20,12 @@ class RecipeSearchManager(models.Manager): + SearchVector(StringAgg('steps__ingredients__food__name', delimiter=' '), weight='B', config='english') + SearchVector(StringAgg('keywords__name', delimiter=' '), weight='B', config='english')) search_rank = SearchRank(search_vectors, search_query) - # trigram_similarity = TrigramSimilarity( - # 'headline', search_text - # ) + # the results from trigram were really, really bad + # trigram = ( + # TrigramSimilarity('name', search_text) + # + TrigramSimilarity('description', search_text) + # + TrigramSimilarity('steps__ingredients__food__name', search_text) + # + TrigramSimilarity('keywords__name', search_text)) return ( self.get_queryset() .annotate(search=search_vectors, rank=search_rank)