问题描述
在 Django 中,从 1.11 版开始,我们有一个用于 PostgreSQL 的类 GinIndex
(https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/indexes/).我想创建一个迁移,在我添加到我的一个表中的 VectorSearchField
上构建这样的索引.到目前为止,我尝试简单地将 db_index=True
添加到 VectorSearchField
,但是失败了,因为它试图创建一个 B-Tree 索引(我认为)和VectorSearchField
值太长.
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.
我设法通过运行 migrations.RunSQL()
迁移来创建我想要的索引:
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);
但是,我想,既然 Django 中有一个特殊的 GinIndex
类,也许有一种方法可以在不执行原始 SQL 的情况下创建这样的索引?
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?
这是一个模型类:
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.
知道如何在迁移中为 sv
字段正确创建索引吗?还是执行 CREATE INDEX ...
查询是最好的方式?
Any idea how to properly create an index for sv
field in a migration? Or is executing the CREATE INDEX ...
query the best way?
推荐答案
还没有机会将我的旧手动 CREATE INDEX
代码迁移到 1.11 中引入的新系统中
但我的理解是
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'])]
是必需的.不再需要使用原始 SQL CREATE INDEX
语句.
Is what's required. Raw SQL CREATE INDEX
statements need not be used any more.
这篇关于如何在 Django 迁移中创建 GIN 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!