By default, Django ModelSearch will index into the database configured in DATABASES["default"] and use PostgreSQL FTS, MySQL FTS, MariaDB FTS or SQLite FTS, if available.
If you are using PostgreSQL, you must additionally add django.contrib.postgres to your INSTALLED_APPS setting.
You can change the indexing configuration, or add additional backends with the MODELSEARCH_BACKENDS setting. For example, to configure Elasticsearch:
To index a model, add modelsearch.index.Indexed to the model class and define some search_fields:
from modelsearch import index
from modelsearch.queryset import SearchableQuerySetMixin
# This mixin adds a .search() method to the models QuerySet
class SongQuerySet(SearchableQuerySetMixin, models.QuerySet):
pass
# Create a model that inherits from Indexed
class Song(index.Indexed, models.Model):
name = models.TextField()
lyrics = models.TextField()
release_date = models.DateField()
artist = models.ForeignKey(Artist, related_name='songs')
objects = SongQuerySet.as_manager()
# Define a list of fields to index
search_fields = [
# Index text fields for full-text search
# Boost the important fields
index.SearchField('name', boost=2.0),
index.SearchField('lyrics'),
# Index fields that for filtering
# These get inserted into Elasticsearch for fast filtering
index.FilterField('release_date'),
index.FilterField('artist'),
# Pull in content from related models too
index.RelatedFields('artist', [
index.SearchField('name'),
]),
]
Then run the django-admin rebuild_modelsearch_index to create the indexes, mappings and insert the data. Signals are then used to keep the index in sync with the database.
Searching
Search by calling .search() on the QuerySet!
Song.objects.search("Flying Whales")
Searches also work when reversing ForeignKeys:
opeth.songs.search("Harvest")
You can use Django's .filter(), .exclude() and .order_by() with search too: