Skip to main content

Custom object IDs

You can choose which field is used as the object ID. The field should be unique and can be a string or integer. By default, we use the pk field of the model.
Python
class ArticleIndex(AlgoliaIndex):
    custom_objectID = "post_id"

Custom index name

You can customize the index name. By default, the index name will be the name of the model class.
Python
class ContactIndex(algoliaindex):
    index_name = "Enterprise"
If you want to process a field before indexing it, for example, capitalizing a contact’s name, or if you want to index an attribute of a related object, you need to define proxy methods for these fields.

Models

Python
class Account(models.Model):
    username = models.CharField(max_length=40)
    service = models.CharField(max_length=40)


class Contact(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField(max_length=60)
    accounts = models.ManyToManyField(Account)

    def account_names(self):
        return [str(account) for account in self.accounts.all()]

    def account_ids(self):
        return [account.id for account in self.accounts.all()]

Index

Python
from algoliasearch_django import AlgoliaIndex


class ContactIndex(AlgoliaIndex):
    fields = (
        "name",
        "email",
        "company",
        "address",
        "city",
        "county",
        "state",
        "zip_code",
        "phone",
        "fax",
        "web",
        "followers",
        "account_names",
        "account_ids",
    )

    settings = {
        "searchableAttributes": [
            "name",
            "email",
            "company",
            "city",
            "county",
            "account_names",
        ]
    }
With this configuration, you can search for a Contact using its Account names. You can use the associated account_ids at search-time to fetch more data from your model. Only proxy the fields relevant for search to keep your records’ size as small as possible.

Index settings

You can configure your index, using all of Algolia’s index settings.
Python
class ArticleIndex(AlgoliaIndex):
    settings = {
        "searchableAttributes": ["name", "description", "url"],
        "customRanking": ["desc(vote_count)", "asc(name)"],
    }

Restrict indexing to a subset of your data

You can add constraints controlling if a record must be indexed or not. should_index should be a callable that returns a boolean.
Python
class Contact(models.model):
    name = models.CharField(max_length=20)
    age = models.IntegerField()

    def is_adult(self):
        return self.age >= 18


class ContactIndex(AlgoliaIndex):
    should_index = "is_adult"

Multiple indices per model

You can have to several indices for a single model. First, define the indices you want for a model:
Python
from django.contrib.algoliasearch import AlgoliaIndex


class MyModelIndex1(AlgoliaIndex):
    name = "MyModelIndex1"
    # ...


class MyModelIndex2(AlgoliaIndex):
    name = "MyModelIndex2"
    # ...
Then, define a meta model which aggregates these indices:
Python
class MyModelMetaIndex(AlgoliaIndex):
    def __init__(self, model, client, settings):
        self.indices = [
            MyModelIndex1(model, client, settings),
            MyModelIndex2(model, client, settings),
        ]

    def raw_search(self, query="", params=None):
        res = {}
        for index in self.indices:
            res[index.name] = index.raw_search(query, params)
        return res

    def update_records(self, qs, batch_size=1000, **kwargs):
        for index in self.indices:
            index.update_records(qs, batch_size, **kwargs)

    def reindex_all(self, batch_size=1000):
        for index in self.indices:
            index.reindex_all(batch_size)

    def set_settings(self):
        for index in self.indices:
            index.set_settings()

    def clear_objects(self):
        for index in self.indices:
            index.clear_objects()

    def save_record(self, instance, update_fields=None, **kwargs):
        for index in self.indices:
            index.save_record(instance, update_fields, **kwargs)

    def delete_record(self, instance):
        for index in self.indices:
            index.delete_record(instance)
Finally, register this AlgoliaIndex with your Model:
Python
import algoliasearch_django as algoliasearch

algoliasearch.register(MyModel, MyModelMetaIndex)

Temporarily turn off the auto-indexing

To temporarily turn off the auto-indexing feature, use the disable_auto_indexing context decorator:
Python
from algoliasearch_django.decorators import disable_auto_indexing

# Used as a context manager
with disable_auto_indexing():
    MyModel.save()

# Used as a decorator
@disable_auto_indexing():
my_method()

# You can also specifiy for which model you want to disable the auto-indexing
with disable_auto_indexing(MyModel):
    MyModel.save()
    MyOtherModel.save()
I