Meilisearch Integration in Python — Core Concepts
Meilisearch is an open-source search engine written in Rust, designed for instant search experiences. It emphasizes speed (<50ms responses), typo tolerance, and developer-friendly defaults. Python integrates through the official meilisearch SDK.
Getting started
import meilisearch
client = meilisearch.Client('http://localhost:7700', 'your-master-key')
# Create an index and add documents
index = client.index('movies')
documents = [
{"id": 1, "title": "The Matrix", "genre": ["sci-fi", "action"], "year": 1999, "rating": 8.7},
{"id": 2, "title": "Inception", "genre": ["sci-fi", "thriller"], "year": 2010, "rating": 8.8},
{"id": 3, "title": "The Grand Budapest Hotel", "genre": ["comedy", "drama"], "year": 2014, "rating": 8.1},
]
task = index.add_documents(documents)
# Meilisearch processes asynchronously — check task status
client.wait_for_task(task.task_uid)
Searching
results = index.search("matirx") # Note the typo — still works!
# Returns The Matrix thanks to typo tolerance
for hit in results['hits']:
print(f"{hit['title']} ({hit['year']}) — rating: {hit['rating']}")
Meilisearch handles typos by default with no configuration needed. The tolerance scales with word length: short words allow fewer typos, long words allow more.
Filtering and sorting
Configure filterable and sortable attributes first:
index.update_filterable_attributes(['genre', 'year', 'rating'])
index.update_sortable_attributes(['year', 'rating'])
Then use them in queries:
# Filter by genre and year
results = index.search("action", {
'filter': 'genre = "sci-fi" AND year > 2000',
'sort': ['rating:desc']
})
# Faceted search — get counts per genre
results = index.search("", {
'facets': ['genre', 'year'],
'filter': 'rating > 7.0'
})
for facet_name, values in results['facetDistribution'].items():
print(f"\n{facet_name}:")
for value, count in values.items():
print(f" {value}: {count}")
Ranking rules
Meilisearch applies ranking rules in order. The default sequence:
- Words — documents containing all query words rank higher
- Typo — fewer typos rank higher
- Proximity — query words close together rank higher
- Attribute — matches in higher-priority fields rank higher
- Sort — user-specified sort criteria
- Exactness — exact matches rank higher
You can customize the order and the attribute priority:
index.update_ranking_rules([
"words", "typo", "proximity", "attribute", "sort", "exactness"
])
# Title matches matter more than description matches
index.update_searchable_attributes(['title', 'description', 'tags'])
Pagination
# Offset-based (for simple "load more")
results = index.search("python", {'offset': 20, 'limit': 10})
# Page-based (for numbered pagination)
results = index.search("python", {'page': 3, 'hitsPerPage': 10})
print(f"Page {results['page']} of {results['totalPages']}")
Asynchronous task handling
All write operations (add, update, delete) are asynchronous. Meilisearch returns a task ID immediately.
task = index.add_documents(new_docs)
print(f"Task {task.task_uid} enqueued")
# Wait for completion
status = client.wait_for_task(task.task_uid, timeout_in_ms=30000)
print(f"Status: {status.status}") # 'succeeded' or 'failed'
Common misconception
Developers sometimes expect Meilisearch to handle complex aggregations like Elasticsearch (sum, average, histograms over millions of records). Meilisearch is purpose-built for search — finding and ranking documents by text relevance. For analytics workloads, use a dedicated analytics engine alongside it.
One thing to remember: Meilisearch trades configurability for simplicity — it gives you great search out of the box with sensible defaults, making it ideal for user-facing search features that need to “just work.”
See Also
- Python Adaptive Learning Systems How Python builds learning apps that adjust to each student like a personal tutor who knows exactly what you need next.
- Python Airflow Learn Airflow as a timetable manager that makes sure data tasks run in the right order every day.
- Python Altair Learn Altair through the idea of drawing charts by describing rules, not by hand-placing every visual element.
- Python Automated Grading How Python grades homework and exams automatically, from simple answer keys to understanding written essays.
- Python Batch Vs Stream Processing Batch processing is like doing laundry once a week; stream processing is like a self-cleaning shirt that cleans itself constantly.