Login

Enhance django postgresql orm for trigram search

Author:
ftri
Posted:
April 3, 2015
Language:
Python
Version:
1.6
Tags:
django orm postgresql trgm
Score:
0 (after 0 ratings)

This is a quite simple snippet to integrate postgresql trgm search in django 1.6.10

This snippet is easy to adapt to other special operators by changing the trgm_search function. This example uses the operator %% but you could use ts_vector(fieldname) @@ to_tsquery(%s)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# tested with django 1.6.10

# 1. Activate pg_trgm
# Create an empty migration (South) and add:
    def forwards(self, orm):
        db.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
        db.execute("CREATE INDEX model_field_trgm_idx ON app_model USING gin (field gin_trgm_ops)")

    def backwards(self, orm):
        db.execute("DROP INDEX IF EXISTS model_field_trgm_idx")
# Of course, replace *app*, *model* and *field* by your application, modelname and fieldname

# 2. Add the following code in your application __init__
    # -*- coding: utf-8 -*-
    from django.db.backends.postgresql_psycopg2.operations import DatabaseOperations

    def trgm_search(self, fieldname):
        t = "{0} %% %s".format(fieldname)
        return t

    DatabaseOperations.fulltext_search_sql = trgm_search

# 3. Now, you can simply use:
model.objects.filter(field__search="abc")

More like this

Comments

Please login first before commenting.