Quickstart: create and query an index
In this quickstart, you create a search index, ingest three short articles, and run a filtered hybrid query. The index is then ready to use from an agent or a workflow.
Before you start, you need:
- A Mistral API key.
- Python 3.12 to 3.14. The Search Toolkit doesn't support Python 3.15.
- uv.
- A workspace with search indexes enabled.
Get an API key
Get an API key
Create an API key in the Mistral Console and copy it: the full key appears only once. Then export it:
export MISTRAL_API_KEY=your-api-keyTo create an index, you need the workspace create_search_indexes permission. Without it, creation returns 403. As the creator, you own the index and can see, query, ingest into, modify, and delete it. If you don't have access to an existing index, the API returns 404, not 403.
Install the Search Toolkit
Install the Search Toolkit
Create a project and add the Search Toolkit, the Python client for search indexes. --python 3.12 keeps uv from picking an interpreter that the toolkit doesn't support:
uv init --python 3.12 search-index-quickstart && cd search-index-quickstart
uv add "mistralai-search-toolkit>=0.1.0"Create, ingest, and query
Create, ingest, and query
Build quickstart.py from the following six blocks, in order. Together, they declare the schema as Document and DocumentChunk subclasses, create the index, ingest three articles, run two hybrid queries, and delete the index.
1. Add the imports and sample data. MistralSearchIndexService manages the index lifecycle. The retriever imports are for the hybrid query in step 5. Index names are unique per workspace, so the random suffix lets you rerun the quickstart in a shared workspace. Each sample article has a source ID, a title, a product, and a text.
import asyncio
import secrets
from typing import Annotated
from mistralai.search.toolkit.document import Document, DocumentChunk, SourceId
from mistralai.search.toolkit.embedding import MistralEmbedder, MistralEmbeddingPreset
from mistralai.search.toolkit.mistral_search_index import MistralSearchIndex, MistralSearchIndexService
from mistralai.search.toolkit.mistral_search_index.models import MistralSearchIndexStatus
from mistralai.search.toolkit.mistral_search_index.retriever import (
Equal,
KeywordRetriever,
NearestNeighbourRetriever,
RRFRetriever,
)
from mistralai.search.toolkit.mistral_search_index.schema import (
MistralSearchIndexCollectionSchema,
MistralSearchIndexField,
MistralSearchIndexFieldType,
)
from mistralai.search.toolkit.search import SearchResult
# Index names are unique per workspace, so a shared workspace needs a unique name.
INDEX = f"support_articles_{secrets.token_hex(4)}"
EMBEDDING = MistralEmbeddingPreset.MISTRAL_EMBED_DIM_1024
ARTICLES = [
# (source_id, title, product, text)
("s3://docs/api-keys.md", "Managing API keys", "console",
"Rotate an API key from the console under Workspace > API keys."),
("s3://docs/billing.md", "Invoices and billing", "billing",
"Download monthly invoices and update your card on the billing page."),
("s3://docs/members.md", "Inviting members", "console",
"Invite teammates to your workspace from the Members tab and assign roles."),
]2. Declare the schema. Every field that you add to the base models becomes an index field. The toolkit infers the wire type from the Python annotation, and MistralSearchIndexField overrides it. page_number is an indexed INT. product is a KEYWORD, so queries can filter on its exact value.
# Every field added on top of the base models becomes an index field. The wire
# type is inferred from the annotation; MistralSearchIndexField overrides it.
class ArticleChunk(DocumentChunk):
page_number: Annotated[int, MistralSearchIndexField(type=MistralSearchIndexFieldType.INT, indexed=True)]
class Article(Document):
title: str
product: Annotated[str, MistralSearchIndexField(type=MistralSearchIndexFieldType.KEYWORD)]
chunks: list[ArticleChunk]3. Create the index. from_document_type derives the collection schema from the Article model. Creation reserves the name and provisions storage asynchronously, so the function polls until the index is READY. You can't change the embedding model after creation: it determines the vector column type and the vector operator class.
async def create_index(service: MistralSearchIndexService) -> None:
schema = MistralSearchIndexCollectionSchema.from_document_type(
collection_name=INDEX,
document_type=Article,
embedding_model=EMBEDDING,
)
info = await service.create_index(schema)
while info.status == MistralSearchIndexStatus.PROVISIONING:
await asyncio.sleep(1)
info = await service.get_index_info(INDEX)
if info.status != MistralSearchIndexStatus.READY:
raise RuntimeError(f"provisioning failed: {info.status_message}")4. Ingest the articles. Ingestion doesn't compute embeddings, so embed the texts first, in one call. Then write each article as a single chunk that carries its embedding. If you ingest the same source_id again, the new version replaces the document: its chunks are deleted and the new ones inserted in one transaction.
async def ingest(index: MistralSearchIndex, embedder: MistralEmbedder) -> None:
texts = [text for *_, text in ARTICLES]
embeddings = (await embedder.embed(texts)).embeddings
for (source_id, title, product, text), embedding in zip(ARTICLES, embeddings, strict=True):
await index.index_document(
Article(
source_id=SourceId(source_id),
content=text,
title=title,
product=product,
chunks=[
ArticleChunk(
source_id=SourceId(source_id),
locator=f"char:0-{len(text)}",
start_offset=0,
end_offset=len(text),
content=text,
embedding=embedding,
page_number=1,
)
],
)
)5. Run a hybrid query. RRFRetriever fuses the keyword and vector rankings with reciprocal rank fusion (RRF). With a Mistral embedding model, the server embeds the query for you. The Equal filter on product applies to both retrievers.
async def search(index: MistralSearchIndex, query: str, product: str | None = None) -> list[SearchResult]:
return await index.retrieve(
RRFRetriever(
top_k=5,
filter=Equal(field="product", value=product) if product else None,
retrievers=[
KeywordRetriever(query=query, top_k=5),
NearestNeighbourRetriever(query=query, top_k=5),
],
)
)6. Tie it together. main creates the index, gets a handle to it, and ingests the articles with an embedder that matches the index preset. It prints the hits of an unfiltered query and of a query filtered to console articles. The finally block deletes the index. Deletion is also asynchronous: the index moves to deleting, then disappears.
async def main() -> None:
service = MistralSearchIndexService()
await create_index(service)
try:
index = await service.get_search_index(INDEX)
await ingest(index, MistralEmbedder(model_name=EMBEDDING.full_model_name))
for hit in await search(index, "how do I rotate an api key"):
print(f"{hit.score:.4f} {hit.chunk.source_id}")
for hit in await search(index, "add a colleague", product="console"):
print(f"{hit.score:.4f} {hit.chunk.source_id}")
finally:
# Deleting is asynchronous too: the index goes to deleting, then disappears.
await service.delete_index(INDEX)
if __name__ == "__main__":
asyncio.run(main())Run it:
uv run quickstart.pyYou should see
You should see
The script prints one score source_id line per hit. The first query searches all products and returns the three articles. The second query filters on product="console", so only the two console articles appear. Your scores can differ:
0.0328 s3://docs/api-keys.md
0.0161 s3://docs/billing.md
0.0159 s3://docs/members.md
0.0164 s3://docs/members.md
0.0161 s3://docs/api-keys.mdGoing further
Going further