Adding a New Model to the Build Index
This guide explains how to add a new model to the build index system, which is used for search functionality in the application.
Overview
The build index system uses Meilisearch to create searchable indexes for various models in the application. To add a new model to this system, you'll need to:
- Create a search serializer for your model
- Add the model to the build index command
- Configure the search settings
Step 1: Create a Search Serializer
Create a new serializer in your app's serializers.py file that inherits from the appropriate base serializer. The serializer should include all fields you want to be searchable and filterable.
Example:
python
from rest_framework import serializers
from myapp.models import MyModel
class MyModelSearchSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = [
'id',
'name',
'description',
# Add other fields you want to be searchable
]
# Optional: Define which fields can be used for filtering
filterableAttributes = [
'id',
'name',
# Add other filterable fields
]
# Optional: Define which fields can be used for sorting
sortableAttributes = [
'name',
# Add other sortable fields
]Step 2: Add Model to Build Index Command
In api/mzansi/management/commands/build_index.py, you need to:
- Import your model and serializer
- Add your model to the appropriate section in the command
Example:
python
from myapp.models import MyModel
from myapp.serializers import MyModelSearchSerializer
# In the Command.handle method:
if should_run("mymodel", tags):
result = create_index("mymodel", MyModelSearchSerializer, MyModel.objects.all())
task_ids["mymodel"] = result.task_uidStep 3: Configure Search Settings
In your model's search serializer, you can configure various search settings:
filterableAttributes: Fields that can be used for filtering search resultssortableAttributes: Fields that can be used for sorting search results
These settings are automatically applied when the index is created.
Testing
To test your new index:
- Run the build index command:
bash
python manage.py build_index- You can also test specific indexes:
bash
python manage.py build_index -t mymodelBest Practices
- Only include fields that are necessary for search functionality
- Consider adding appropriate filterable and sortable attributes
- Test the search functionality thoroughly after adding a new model
- Consider adding appropriate indexes to your database for frequently searched fields
Troubleshooting
If you encounter issues:
- Check that all required fields are included in the serializer
- Verify that the model is properly imported in the build_index command
- Ensure that the index name matches the model name (lowercase)
- Check the Meilisearch logs for any indexing errors