Algolia Search integration for Django

raw JSON →
4.0.0 verified Fri May 15 auth: no python

This package provides seamless integration of the Algolia Search API into Django projects. It is currently at version 4.0.0 and is actively maintained, with a focus on compatibility with modern Python and Django versions, built upon the `algoliasearch-client-python` library.

pip install algoliasearch-django
error ModuleNotFoundError: No module named 'algoliasearch_django'
cause The 'algoliasearch-django' package is not installed or not properly added to the Python environment.
fix
Install the package using 'pip install --upgrade "algoliasearch-django>=4.0,<5.0"'.
error ImportError: cannot import name 'clear_index' from 'algoliasearch_django'
cause The 'clear_index' method has been deprecated and removed in version 4.0.0 of 'algoliasearch-django'.
fix
Replace 'clear_index' with 'clear_objects' in your code.
error ERROR: algoliasearch-django 1.7.1 has requirement algoliasearch<2.0,>=1.0, but you'll have algoliasearch 2.0.4 which is incompatible.
cause Version 1.7.1 of 'algoliasearch-django' is incompatible with 'algoliasearch' version 2.0.4.
fix
Upgrade 'algoliasearch-django' to a compatible version using 'pip install --upgrade "algoliasearch-django>=4.0,<5.0"'.
error TypeError: float() argument must be a string or a number, not 'tuple'
cause An incompatibility between 'urllib3' and 'requests' versions causes this error during the 'algolia_reindex' command.
fix
Upgrade 'urllib3' and 'requests' packages using 'pip install --upgrade urllib3 requests'.
error AttributeError: module 'algoliasearch_django' has no attribute 'register'
cause The 'register' function is not directly available in 'algoliasearch_django' and should be imported from 'algoliasearch_django.decorators'.
fix
Import 'register' using 'from algoliasearch_django.decorators import register'.
breaking Version 4.0.0 drops support for Python versions older than 3.8 and Django versions older than 4.0. Ensure your project meets these minimum requirements before upgrading.
fix Upgrade Python to 3.8+ and Django to 4.0+. Refer to Django's own upgrade guides for framework-specific changes.
breaking The `clear_index` method has been removed in favor of `clear_objects` for improved clarity and consistency with the underlying Algolia API client.
fix Replace all calls to `algoliasearch.clear_index(Model)` with `algoliasearch.clear_objects(Model)`.
breaking The configuration for Algolia in `settings.py` has changed. Instead of `ALGOLIA_APPLICATION_ID` and `ALGOLIA_API_KEY` as top-level settings, they are now nested within a single `ALGOLIA` dictionary.
fix Update your `settings.py` to use `ALGOLIA = {'APPLICATION_ID': 'YOUR_APP_ID', 'API_KEY': 'YOUR_API_KEY'}`.
gotcha When performing searches from the frontend, use the dedicated 'Search-Only API Key' rather than the 'Admin API Key'. The Admin API Key has full write access and should never be exposed client-side.
fix Distinguish between 'API_KEY' (Admin) for backend operations and 'SEARCH_API_KEY' (Search-Only) for frontend search queries.
gotcha Records exceeding Algolia's size limit (typically 10KB) will cause indexing errors. This often occurs when indexing too many fields or large related objects.
fix Carefully select which fields to index using the `fields` attribute in `AlgoliaIndex`. Consider using `get_extra_attributes` or `get_raw_record` to preprocess and limit the data sent to Algolia, only indexing data relevant for search.
gotcha Issues can arise with Many-to-Many relationships not updating correctly in the Algolia index, particularly on model saves. Sometimes manual re-indexing is required.
fix Ensure that related objects are correctly handled, potentially by overriding `save_record` or using custom signals to trigger updates to the main model's index entry when M2M relationships change. Manual re-indexing (`python manage.py algolia_reindex`) might be necessary in some cases.
python os / libc status wheel install import disk mem side effects
3.10 alpine (musl) wheel - - 66.4M - broken
3.10 slim (glibc) wheel 3.4s - 67M - broken
3.11 alpine (musl) wheel - - 70.8M - broken
3.11 slim (glibc) wheel 3.3s - 71M - broken
3.12 alpine (musl) wheel - - 62.4M - broken
3.12 slim (glibc) wheel 3.2s - 63M - broken
3.13 alpine (musl) wheel - - 62.2M - broken
3.13 slim (glibc) wheel 3.4s - 63M - broken
3.9 alpine (musl) wheel - - 64.4M - broken
3.9 slim (glibc) wheel 3.7s - 65M - broken

To get started, first configure your Algolia credentials in your Django `settings.py` under an `ALGOLIA` dictionary. Then, define your Django models. Finally, create an `index.py` file within your app and register your models for indexing using either `algoliasearch.register()` or the `@register` decorator with a subclass of `AlgoliaIndex` to specify index settings and fields. Remember to add `algoliasearch_django` to your `INSTALLED_APPS`.

import os
import django
from django.conf import settings
from django.db import models

# Configure Django settings minimally for standalone execution
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'myapp',
            'algoliasearch_django'
        ],
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
        ALGOLIA={
            'APPLICATION_ID': os.environ.get('ALGOLIA_APPLICATION_ID', 'YOUR_APP_ID'),
            'API_KEY': os.environ.get('ALGOLIA_API_KEY', 'YOUR_API_KEY'),
            'INDEX_PREFIX': 'dev_',
        },
        DEFAULT_AUTO_FIELD='django.db.models.AutoField',
        SECRET_KEY='a-very-secret-key',
        DEBUG=True
    )
django.setup()

# models.py (example in a fictional 'myapp')
class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        app_label = 'myapp'

# index.py (example in 'myapp')
from algoliasearch_django import AlgoliaIndex
from algoliasearch_django.decorators import register

@register(Product)
class ProductIndex(AlgoliaIndex):
    fields = ('name', 'description', 'price', 'created_at')
    settings = {'searchableAttributes': ['name', 'description'], 'attributesForFaceting': ['price']}
    # You can customize `get_attribute_name` or `get_extra_attributes` for more complex indexing

# --- Example Usage (after defining models and index, typically run via manage.py) ---

# This part would typically be run via `python manage.py shell` or a management command.
# For demonstration, we simulate creating and saving an object.
# In a real Django app, signals handle auto-indexing on save.

# Create a product (this would automatically index if AUTO_INDEXING is True, which is default)
# from myapp.models import Product
# p1 = Product.objects.create(name="Wireless Headphones", description="High-quality audio experience.", price=199.99)
# p2 = Product.objects.create(name="Bluetooth Speaker", description="Portable and powerful sound.", price=79.99)
# print("Products created and indexed.")

# To manually reindex all: python manage.py algolia_reindex
# To apply settings: python manage.py algolia_applysettings

print("Algolia Django integration configured. To index data, run 'python manage.py algolia_reindex' or save model instances.")