Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

postgresql - How to create GIN index in Django migration

In Django, since version 1.11 we have a class for PostgreSQL GinIndex (https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/indexes/). I'd like to create a migration that constructs such index on a VectorSearchField I added to one of my tables. So far, I've tried to simply add db_index=True to the VectorSearchField, but that fails, because it tries to create a B-Tree index (I think) and the VectorSearchField values are too long.

I managed to create the index I want by running a migrations.RunSQL() migration with:

CREATE INDEX entryline_sv_index ON entryline USING GIN (sv);

However, I guess, since there is a special GinIndex class in Django, maybe there is a way to create such index without executing raw SQL?

Here's a model class:

import django.contrib.postgres.search as pg_search

class EntryLine(models.Model):
    speaker = models.CharField(max_length=512, db_index=True)
    text = models.TextField()
    sv = pg_search.SearchVectorField(null=True)  # I want a GIN index on this field.

Any idea how to properly create an index for sv field in a migration? Or is executing the CREATE INDEX ... query the best way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Haven't yet had a chance to migrate my old manual CREATE INDEX codes to the new system introduced in 1.11 but my understanding is

from django.contrib.postgres.indexes import GinIndex
import django.contrib.postgres.search as pg_search
    
class EntryLine(models.Model):
    speaker = models.CharField(max_length=512, db_index=True)
    text = models.TextField()
    sv = pg_search.SearchVectorField(null=True) 
    class Meta:
        indexes = [GinIndex(fields=['sv'])]

Is what's required. Raw SQL CREATE INDEX statements need not be used any more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...