在Django模型中使用Trigram(gin_trgm_ops)创建Gin索引

All*_*cor 11 python django postgresql indexing similarity

django.contrib.postgres的新TrigramSimilarity功能非常适合我遇到的问题.我将它用于搜索栏以找到难以拼写的拉丁名字.问题是有超过200万个名字,搜索需要的时间比我想要的要长.

我想在postgres文档https://www.postgresql.org/docs/9.6/static/pgtrgm.html中创建一个关于三元组的索引.

但我不知道如何以Django API使用它的方式来做到这一点.对于postgres文本搜索,有关于如何创建索引的描述.但不是因为三元组的相似性. https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/#performance

这就是我现在所拥有的:

class NCBI_names(models.Model):
    tax_id          =   models.ForeignKey(NCBI_nodes, on_delete=models.CASCADE, default = 0)
    name_txt        =   models.CharField(max_length=255, default = '')
    name_class      =   models.CharField(max_length=32, db_index=True, default = '')

    class Meta:
        indexes = [GinIndex(fields=['name_txt'])]
Run Code Online (Sandbox Code Playgroud)

然后在vieuw的get_queryset中我做:

class TaxonSearchListView(ListView):    
    #form_class=TaxonSearchForm
    template_name='collectie/taxon_list.html'
    paginate_by=20
    model=NCBI_names
    context_object_name = 'taxon_list'

    def dispatch(self, request, *args, **kwargs):
        query = request.GET.get('q')
        if query:
            try:
                tax_id = self.model.objects.get(name_txt__iexact=query).tax_id.tax_id
                return redirect('collectie:taxon_detail', tax_id)
            except (self.model.DoesNotExist, self.model.MultipleObjectsReturned) as e:
                return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)
        else:
            return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        result = super(TaxonSearchListView, self).get_queryset()
        #
        query = self.request.GET.get('q')
        if query:            
            result = result.exclude(name_txt__icontains = 'sp.')
            result = result.annotate(similarity=TrigramSimilarity('name_txt', query)).filter(similarity__gt=0.3).order_by('-similarity')
        return result
Run Code Online (Sandbox Code Playgroud)

编辑将整个视图类放入

Tim*_*imB 12

我遇到了类似的问题,尝试使用pg_tgrm扩展来支持高效containsicontainsDjango字段查找.

可能有更优雅的方式,但定义像这样的新索引类型对我有用:

from django.contrib.postgres.indexes import GinIndex

class TrigramIndex(GinIndex):
    def get_sql_create_template_values(self, model, schema_editor, using):
        fields = [model._meta.get_field(field_name) for field_name, order in self.fields_orders]
        tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
        quote_name = schema_editor.quote_name
        columns = [
            ('%s %s' % (quote_name(field.column), order)).strip() + ' gin_trgm_ops'
            for field, (field_name, order) in zip(fields, self.fields_orders)
        ]
        return {
            'table': quote_name(model._meta.db_table),
            'name': quote_name(self.name),
            'columns': ', '.join(columns),
            'using': using,
            'extra': tablespace_sql,
        }
Run Code Online (Sandbox Code Playgroud)

只需一次修改就get_sql_create_template_values可以复制该方法Index.get_sql_create_template_values():添加+ ' gin_trgm_ops'.

对于您的用例,您将name_txt使用this TrigramIndex而不是a 来定义索引GinIndex.然后运行makemigrations,这将生成一个生成所需CREATE INDEXSQL 的迁移.

更新:

我看到你也在使用icontains以下方法进行查询:

result.exclude(name_txt__icontains = 'sp.')
Run Code Online (Sandbox Code Playgroud)

Postgresql后端将把它变成这样的东西:

UPPER("NCBI_names"."name_txt"::text) LIKE UPPER('sp.')
Run Code Online (Sandbox Code Playgroud)

然后因为这个而不会使用trigram索引UPPER().

我有同样的问题,最后继承数据库后端来解决它:

from django.db.backends.postgresql import base, operations

class DatabaseFeatures(base.DatabaseFeatures):
    pass

class DatabaseOperations(operations.DatabaseOperations):
    def lookup_cast(self, lookup_type, internal_type=None):
        lookup = '%s'

        # Cast text lookups to text to allow things like filter(x__contains=4)
        if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
                           'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
            if internal_type in ('IPAddressField', 'GenericIPAddressField'):
                lookup = "HOST(%s)"
            else:
                lookup = "%s::text"

        return lookup


class DatabaseWrapper(base.DatabaseWrapper):
    """
        Override the defaults where needed to allow use of trigram index
    """
    ops_class = DatabaseOperations

    def __init__(self, *args, **kwargs):
        self.operators.update({
            'icontains': 'ILIKE %s',
            'istartswith': 'ILIKE %s',
            'iendswith': 'ILIKE %s',
        })
        self.pattern_ops.update({
            'icontains': "ILIKE '%%' || {} || '%%'",
            'istartswith': "ILIKE {} || '%%'",
            'iendswith': "ILIKE '%%' || {}",
        })
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过创建 GIN 索引来避免数据库包装,如下所示:`# CREATE INDEX blog_article_title_trigram ON blog_article USING gin (UPPER(title) gin_trgm_ops);` 请参阅 https://gs-9.com/tuning-django-orm-text -查询/ (2认同)

Ris*_*nha 6

要使 Django 2.2 使用索引进行icontains类似搜索:

子类 GinIndex 使索引不区分大小写(将所有字段值大写):

from django.contrib.postgres.indexes import GinIndex

class UpperGinIndex(GinIndex):

    def create_sql(self, model, schema_editor, using=''):
        statement = super().create_sql(model, schema_editor, using=using)
        quote_name = statement.parts['columns'].quote_name

        def upper_quoted(column):
            return f'UPPER({quote_name(column)})'
        statement.parts['columns'].quote_name = upper_quoted
        return statement
Run Code Online (Sandbox Code Playgroud)

像这样将索引添加到您的模型中,包括name使用时所需的kwarg opclasses

class MyModel(Model):
    name = TextField(...)

    class Meta:
        indexes = [
            UpperGinIndex(fields=['name'], name='mymodel_name_gintrgm', opclasses=['gin_trgm_ops'])
        ]
Run Code Online (Sandbox Code Playgroud)

生成迁移并编辑生成的文件:

# Generated by Django 2.2.3 on 2019-07-15 10:46
from django.contrib.postgres.operations import TrigramExtension  # <<< add this
from django.db import migrations
import myapp.models


class Migration(migrations.Migration):

    operations = [
        TrigramExtension(),   # <<< add this
        migrations.AddIndex(
            model_name='mymodel',
            index=myapp.models.UpperGinIndex(fields=['name'], name='mymodel_name_gintrgm', opclasses=['gin_trgm_ops']),
        ),
    ]
Run Code Online (Sandbox Code Playgroud)


Ale*_*kop 6

这已经有了答案,但在 Django 2.2 中,您可以更轻松地做到这一点:

class MyModel(models.Model):
   name = models.TextField()
   class Meta:
       indexes = [GistIndex(name="gist_trgm_idx", fields=("name",), opclasses=("gist_trgm_ops",))]

Run Code Online (Sandbox Code Playgroud)

或者,您可以使用GinIndex.


n1_*_*n1_ 5

如果有人想要将多个列上的索引与空间连接(连接),您可以使用我对内置索引的修改。

创建索引,如 gin (("column1" || ' ' || "column2" || ' ' || ...) gin_trgm_ops)

class GinSpaceConcatIndex(GinIndex):

    def get_sql_create_template_values(self, model, schema_editor, using):

        fields = [model._meta.get_field(field_name) for field_name, order in self.fields_orders]
        tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
        quote_name = schema_editor.quote_name
        columns = [
            ('%s %s' % (quote_name(field.column), order)).strip()
            for field, (field_name, order) in zip(fields, self.fields_orders)
        ]
        return {
            'table': quote_name(model._meta.db_table),
            'name': quote_name(self.name),
            'columns': "({}) gin_trgm_ops".format(" || ' ' || ".join(columns)),
            'using': using,
            'extra': tablespace_sql,
        }
Run Code Online (Sandbox Code Playgroud)


rar*_*iru 5

受到有关该主题的旧文章的启发,我进入了当前文章,该文章为a 提供了以下解决方案GistIndex

更新:从Django-1.11开始,事情似乎更简单了,因为这个答案Django文档很简单:

from django.contrib.postgres.indexes import GinIndex

class MyModel(models.Model):
    the_field = models.CharField(max_length=512, db_index=True)

    class Meta:
        indexes = [GinIndex(fields=['the_field'])]
Run Code Online (Sandbox Code Playgroud)

Django-2.2开始,为此opclasses可以使用属性class Index(fields=(), name=None, db_tablespace=None, opclasses=())


from django.contrib.postgres.indexes import GistIndex

class GistIndexTrgrmOps(GistIndex):
    def create_sql(self, model, schema_editor):
        # - this Statement is instantiated by the _create_index_sql()
        #   method of django.db.backends.base.schema.BaseDatabaseSchemaEditor.
        #   using sql_create_index template from
        #   django.db.backends.postgresql.schema.DatabaseSchemaEditor
        # - the template has original value:
        #   "CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s"
        statement = super().create_sql(model, schema_editor)
        # - however, we want to use a GIST index to accelerate trigram
        #   matching, so we want to add the gist_trgm_ops index operator
        #   class
        # - so we replace the template with:
        #   "CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s gist_trgrm_ops)%(extra)s"
        statement.template =\
            "CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s gist_trgm_ops)%(extra)s"

        return statement
Run Code Online (Sandbox Code Playgroud)

然后可以在模型类中使用以下代码:

class YourModel(models.Model):
    some_field = models.TextField(...)

    class Meta:
        indexes = [
            GistIndexTrgrmOps(fields=['some_field'])
        ]
Run Code Online (Sandbox Code Playgroud)