Create a Full-Text Index in Migration Files with Django 1.7

Django
2015-09-03 11:48 (10 years ago)
Create a Full-Text Index in Migration Files with Django 1.7

This is a method to create a full-text index in MySQL using the DB migration feature in Django 1.7 and above.

By the way, MySQL 5.6 and above allows you to create full-text indexes in InnoDB as well.

First, you need to install the sqlparse module.

$ pip install sqlparse

In advance, create a text field in your model for applying the full-text index.

class HogeSearch(models.Model):
    ...
    search_text = models.TextField(default='', blank=True)

Then, generate a normal migration file first.

$ ./manage.py makemigrations hogeapp

Next, create an empty migration file.

$ ./manage.py makemigrations hogeapp --empty

When you look at the created migration file, you will see a list called operations. Insert a migrations.RunSQL instance into this list.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

dependencies = [
    ('hogeapp', '0001_initial'),
]

operations = [
    migrations.RunSQL(
        "CREATE FULLTEXT INDEX i_search_text ON hogeapp_hogemodel (search_text)",
        "DROP INDEX i_search_text ON hogeapp_hogemodel"),
]

The second argument of migrations.RunSQL is SQL for reverse migration, so it is not mandatory. (However, if it is not provided, attempting reverse migration (e.g., ./manage.py migrate hogeapp 0001) will cause a Migration.IrreversibleError exception and fail.)

When you execute the created migration, the full-text index will be applied.

$ ./manage.py migrate hogeapp
Please rate this article (No signup or login required)
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive