Creating a Gin Index with Trigram (gin_trgm_ops) in Django model

后端 未结 5 1753
轻奢々
轻奢々 2021-02-02 01:29

The new TrigramSimilarity feature of the django.contrib.postgres was great for a problem I had. I use it for a search bar to find hard to spell latin names. The problem is that

5条回答
  •  爱一瞬间的悲伤
    2021-02-02 02:02

    In case someone want to have index on multiple columns joined (concatenated) with space you can use my modicitaion of built-in index.

    Creates index like 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,
            }
    

提交回复
热议问题