How to create complex gin index in postgres db using django

296 views
Skip to first unread message

Максим Родин

unread,
Aug 29, 2018, 7:16:15 AM8/29/18
to Django users
Hello,
I'm trying to make the text search index like this:
"CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));"

I cannot imagine how to do it in django
Here is my table:

from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchQuery
from django.contrib.postgres.search import SearchVector
import django.contrib.postgres.search as pg_search


class Request(models.Model):

    open_date
= models.DateTimeField(verbose_name='Creation Date',
                                     blank
=True)
    close_date
= models.DateTimeField(verbose_name='Closing Date',
                                      blank
=True,
                                     
null=True,
                                     
)


   
def in_work_time(self):
       
return timezone.now() - self.open_date


   
def set_open_time(self):
       
self.open_date = timezone.now()


    subject
= models.CharField(max_length=500,
                               verbose_name
='Request subject')
    author
= models.CharField(max_length=500,
                              verbose_name
='Request author')
    content
= models.TextField(verbose_name='Request content')
    engineer
= models.ForeignKey(User, on_delete=models.PROTECT,
                                 blank
=True,
                                 verbose_name
='Engineer assigned')
    priority
= models.IntegerField(default=10,
                                   verbose_name
='Priority')


   
def __str__(self):
       
return self.subject


And here are my thoughts how it could look like.
(It doesn't work):

    en_sv = pg_search.SearchVectorField(SearchVector(
        '
subject', 'content', config='english'), null=True)
    ru_sv = pg_search.SearchVectorField(SearchVector(
        '
subject', 'content', config='russian'), null=True)


    class Meta:
        indexes = [
            GinIndex(fields=['
ru_sv'],
                     fastupdate=False, name='
gin_search_ru_idx'),
            GinIndex(fields=['
en_sv'],
                     fastupdate=False, name='
gin_search_en_idx'),
     ]


Any thoughts?

Jason

unread,
Aug 29, 2018, 7:35:53 AM8/29/18
to Django users
you need to make a migration to apply the index.


something like 

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0001_initial'),
    ]

    operations = [
        migrations.RunSQL(
            "CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));",
        )
    ]
Reply all
Reply to author
Forward
0 new messages