---
title: "Mistral"
description: "End-to-end guide for building a fast semantic-search stack with Mistral-Embed vectors stored in SurrealDB’s native HNSW index."
canonical_url: "https://surrealdb.com/docs/integrate/integrations/embeddings-providers/mistral"
section: "Embeddings providers"
surrealdb_version: "4.x"
last_modified: "2026-11-18T02:09:16Z"
---

> Full SurrealDB documentation index: https://surrealdb.com/docs/llms.txt

# Mistral

End-to-end guide for building a fast semantic-search stack with Mistral-Embed vectors stored in SurrealDB’s native HNSW index.

**Python**

Modern open-source RAG pipelines need two things:

1. **High-quality embeddings** - *Mistral-Embed* (`mistral-embed`) returns 1 024-dimensional float vectors that rival OpenAI + Cohere.
2. **Fast vector storage** - **SurrealDB** (≥ v1.5) ships an in-memory HNSW index, queried with the `<|K,EF|>` operator in SurrealQL.

The sections below connect the two, from installation through ingestion and search to a complete script.

## Prerequisites

```bash
pip install mistralai surrealdb
````

Set two environment variables (or hard-code them if you must):

```bash
export SDB_URL="http://localhost:8000/rpc"   # ← SurrealDB RPC endpoint
export MISTRAL_API_KEY="sk-…"                # ← your Mistral key
```

## Connect and create the schema

```python
from mistralai.client import MistralClient
from surrealdb import Surreal
import os, asyncio

# ----- 1.1 · Config -----------------------------------------------------------------
SDB_URL  = os.getenv("SDB_URL", "http://localhost:8000/rpc")
SDB_USER = os.getenv("SDB_USER", "root")
SDB_PASS = os.getenv("SDB_PASS", "secret")
NS, DB   = "demo", "demo"
TABLE    = "mistral_docs"
MODEL    = "mistral-embed"

# ----- 1.2 · Clients ----------------------------------------------------------------
sdb   = Surreal(SDB_URL)
mistr = MistralClient(api_key=os.environ["MISTRAL_API_KEY"])

async def init_db():
    await sdb.signin({"user": SDB_USER, "pass": SDB_PASS})
    await sdb.use(NS, DB)

    # one quick embedding → get true vector dimension
    dim = len(mistr.embeddings(model=MODEL, input=["ping"]).data[0].embedding)

    schema = """
    DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
    DEFINE FIELD text      ON $tb TYPE string;
    DEFINE FIELD embedding ON $tb TYPE array;

    DEFINE INDEX hnsw_idx ON $tb
      FIELDS embedding
      HNSW DIMENSION {dim}
      DIST   COSINE;
    """
    await sdb.query(schema, {"tb": TABLE})

asyncio.run(init_db())
```

### Why detect the dimension dynamically?

*Future-proofing:* if Mistral introduces a **small** or **large** Embed model with a different dimension, the code auto-adapts.

## Embed and bulk-insert documents

```python
DOCS = [
    "SurrealDB offers an in-memory HNSW vector index for low-latency search.",
    "Mistral-Embed produces 1 024-dimensional embeddings.",
    "You can build a completely open-source RAG stack with these two tools.",
]

async def insert_docs(docs, batch=64):
    rows = []
    for i in range(0, len(docs), batch):
        chunk = docs[i : i + batch]
        vecs  = mistr.embeddings(model=MODEL, input=chunk).data
        rows += [
            {
                "id":        f"{TABLE}:{i+j}",
                "text":      chunk[j],
                "embedding": vec.embedding,
            }
            for j, vec in enumerate(vecs)
        ]
    await sdb.query(f"INSERT INTO {TABLE} $data", {"data": rows})

asyncio.run(insert_docs(DOCS))
```

Bulk-inserting sends every document in one SurrealQL call and one network round trip, which is **much faster** than inserting records one at a time.

## Search with a natural-language query

```python
async def search(query: str, k: int = 3, ef: int = 64):
    q_vec = mistr.embeddings(model=MODEL, input=[query]).data[0].embedding
    surql = """
    LET $q := $vec;
    SELECT id, text, vector::distance::knn() AS score
    FROM $tb
    WHERE embedding <|{k},{ef}|> $q
    ORDER BY score;
    """
    res = await sdb.query(surql, {"vec": q_vec, "tb": TABLE})
    return res[0].result

hits = asyncio.run(search("Which database supports native vector search?"))
for h in hits:
    print(f"⭐ {h['text']}  (score={h['score']:.4f})")
```

`<|K,EF|>` activates the HNSW **K-nearest-neighbour** operator (`K=3`, `efSearch=64`).
`vector::distance::knn()` exposes the cosine distance already computed inside the index, no post-processing needed.

## Full script (ready to run)

```python
# mistral_surreal_demo.py
from __future__ import annotations
import os, asyncio
from mistralai.client import MistralClient
from surrealdb import Surreal

SDB_URL  = os.getenv("SDB_URL", "http://localhost:8000/rpc")
SDB_USER = os.getenv("SDB_USER", "root")
SDB_PASS = os.getenv("SDB_PASS", "secret")
NS, DB, TABLE = "demo", "demo", "mistral_docs"
MODEL   = "mistral-embed"
KEY     = os.environ["MISTRAL_API_KEY"]  # export first!

sdb, mistr = Surreal(SDB_URL), MistralClient(api_key=KEY)

DOCS = [
    "SurrealDB's vector index is built on HNSW.",
    "Mistral-Embed vectors offer strong semantic quality.",
    "Together they form a fast, open-source search stack.",
]

async def main():
    await sdb.signin({"user": SDB_USER, "pass": SDB_PASS})
    await sdb.use(NS, DB)

    dim = len(mistr.embeddings(model=MODEL, input=["x"]).data[0].embedding)
    await sdb.query("""
        DEFINE TABLE $tb SCHEMALESS PERMISSIONS NONE;
        DEFINE FIELD text ON $tb TYPE string;
        DEFINE FIELD embedding ON $tb TYPE array;
        DEFINE INDEX hnsw_idx ON $tb FIELDS embedding
               HNSW DIMENSION {dim} DIST COSINE;
    """, {"tb": TABLE})

    # ingest if empty
    if (await sdb.query(f"SELECT count() FROM {TABLE};"))[0].result[0]["count"] == 0:
        rows = []
        vecs = mistr.embeddings(model=MODEL, input=DOCS).data
        rows = [
            {"id": f"{TABLE}:{i}", "text": DOCS[i], "embedding": v.embedding}
            for i, v in enumerate(vecs)
        ]
        await sdb.query(f"INSERT INTO {TABLE} $data", {"data": rows})

    # search
    q_vec = mistr.embeddings(model=MODEL,
                             input=["open-source vector database"] ).data[0].embedding
    res = await sdb.query("""
        LET $q := $vec;
        SELECT text, vector::distance::knn() AS score
        FROM {TABLE}
        WHERE embedding <|3,64|> $q
        ORDER BY score;
    """, {"vec": q_vec})
    print(res[0].result)

if __name__ == "__main__":
    asyncio.run(main())
```

## About quantisation

SurrealDB currently stores vectors as `float32` / `float64` arrays and does **not** ship built-in binary or int8 quantisation.
If memory is critical you can:

1. Quantise offline to int8 (e.g. with *faiss* or *sentence-transformers*).
2. Store the int8 arrays in **another field** (SurrealQL’s array type is agnostic).
3. Execute a **two-stage search**: coarse K-NN on the int8 field, then rescore on the full-precision field.

### You’re done 🚀

You now have a clean, fully-async SurrealDB setup that stores **Mistral-Embed** vectors, supports **fast HNSW search**, and can be dropped into any RAG or semantic-search workflow.

**Rust**

In Rust, the [mistralai-client](https://crates.io/crates/mistralai-client) crate generates the embeddings and the SurrealDB Rust SDK stores and searches them. This section covers the parts that are specific to Mistral AI. The tutorial [Implement semantic search in Rust](/docs/learn/tutorials/tutorials/semantic-search-in-rust.md#using-mistral) builds the complete program around them: the `document` table and its index, a function that stores a batch of texts with their embeddings, and a KNN query that answers questions against them.

## Setup

Create a new Cargo project with `cargo new project_name`, go into the project folder, and add the dependencies:

```bash
cargo add anyhow mistralai-client tokio surrealdb --features surrealdb/kv-mem,tokio/macros,tokio/rt-multi-thread
```
<br />

You need an [API key](https://console.mistral.ai/api-keys) from Mistral AI's platform. Set it in the `MISTRAL_API_KEY` environment variable rather than in the code, and run the program like this:

```bash
MISTRAL_API_KEY=whateverthekeyis cargo run
```
<br />

Or like this if you are using PowerShell on Windows:

```powershell
$env:MISTRAL_API_KEY = "whateverthekeyis"
cargo run
```
<br />

## Generate an embedding

The program below reads the key once through a `LazyLock`, [creates a client](https://docs.rs/mistralai-client/0.14.0/mistralai_client/v1/client/struct.Client.html#method.new) and asks the `mistral-embed` model for the embedding of one sentence. SurrealDB uses the tokio runtime, so the program calls the async `.embeddings_async()` method, which takes a `Vec<String>` and returns one embedding for each string.

```rust
use std::sync::LazyLock;

use anyhow::Error;
use mistralai_client::v1::{client::Client, constants::EmbedModel};

static KEY: LazyLock<String> = LazyLock::new(|| std::env::var("MISTRAL_API_KEY").unwrap());

const MODEL: EmbedModel = EmbedModel::MistralEmbed;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let client = Client::new(Some(KEY.to_string()), None, None, None)?;

    let input = vec!["Joram is the main character in the Darksword Trilogy.".to_string()];
    let mut result = client.embeddings_async(MODEL, input, None).await?;

    let embedding: Vec<f32> = result.data.remove(0).embedding;
    println!("{}", embedding.len());
    Ok(())
}
```

```text title="Output"
1024
```

`Client::new()` looks for the `MISTRAL_API_KEY` variable by default. To read the key from a variable with another name, pass the name as the second argument:

```rust
let client = Client::new(Some(KEY.to_string()), Some("OTHER_ENV_VAR".to_string()), None, None)?;
```
<br />

The [response](https://docs.rs/mistralai-client/0.14.0/mistralai_client/v1/embedding/struct.EmbeddingResponse.html) holds one `EmbeddingResponseDataItem` for each input string, in the same order, and each item's `embedding` field is a `Vec<f32>`. That type can be stored in SurrealDB as it is, as an `array<float>` field.

## Match the index to the model

The `mistral-embed` model returns vectors of [1024 dimensions](https://docs.mistral.ai/getting-started/models/models_overview/#premier-models), so a vector index on the field that stores them must use `DIMENSION 1024`. The tutorial defines the table, the field and an HNSW index with that dimension, then stores 16 short facts and asks four questions against them.
