Skip to content

Your own document types

The typed document layer, oxsearch::document, makes a struct of your own the document type: its fields define the index’s mapping, its field handles build queries that suit each field, and an Index<T> reads, writes and searches it. The derive feature turns it on, with its derive macro.

Cargo.toml
[dependencies]
oxsearch = { version = "0.2", features = ["derive", "transport-reqwest"] }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt"] }
crates/oxsearch/examples/documents.rs
/// An article. Each field's mapped type comes from an attribute, or else
/// from its Rust type: `title` is text, being a `String`.
#[derive(Document, Serialize, Deserialize, Debug, Clone, PartialEq)]
#[index("oxsearch-example-articles")]
struct Article {
/// The document's id in the index.
#[id]
slug: String,
title: String,
#[keyword]
tags: Vec<String>,
#[dense_vector(dims = 3, similarity = "cosine")]
embedding: Vec<f32>,
}

Field attributes choose a field’s mapped type: #[keyword], #[text], #[date], #[semantic_text(inference_id = "…")], #[dense_vector(dims = …, similarity = "…", element_type = "…")] and #[sparse_vector]. Without one, the Rust type decides: strings are text, numbers and booleans their own types, date and time types date, and a struct that derives Document an object.

#[id] marks the field that gives a document’s id, and #[routing] the one that gives its routing. serde’s rename, rename_all and skip are followed, so the mapping names fields as they are stored.

crates/oxsearch/examples/documents.rs
let articles = client.index::<Article>().refresh(Refresh::WaitFor);
let _ = articles.delete_index().await;
let report = articles.ensure_mapping().await?;
println!(
"created: {}, fields added: {:?}",
report.created, report.added
);
for one in [
article(
"hnsw",
"Tuning HNSW graphs",
&["vectors", "rust"],
[0.9, 0.1, 0.1],
),
article(
"bulk",
"Bulk loading at speed",
&["ingest"],
[0.1, 0.9, 0.1],
),
article("shards", "Sizing shards", &["operations"], [0.1, 0.1, 0.9]),
] {
articles.put(&one).await?;
}

client.index::<Article>() is the index the type names. ensure_mapping creates it with the type’s mapping if it doesn’t exist, adds the fields an existing one lacks, and reports fields mapped differently, which it never changes. A new index for a type with vector fields keeps the vectors in the sources it returns, so documents read back whole.

refresh(Refresh::WaitFor) makes each write wait until searches can see it; leave it off for throughput.

crates/oxsearch/examples/documents.rs
let hnsw = articles
.get("hnsw")
.await?
.expect("the article was written");
println!(
"{} at version {:?}: {}",
hnsw.id, hnsw.version, hnsw.document.title
);

A document reads back with its id and its version, Versioned<Article>. put_versioned writes one back only if nobody changed it in the meantime; if somebody did, it fails with Error::Conflict.

crates/oxsearch/examples/documents.rs
// A term query on a keyword field, built from the field's handle.
let tagged = articles
.search(Retriever::standard(Article::TAGS.term("vectors")))
.await?;
// Nearest neighbours of a vector: 2 of them, from 10 candidates.
let near = articles
.search(Article::EMBEDDING.knn(vec![0.8, 0.2, 0.1], 2, 10))
.await?;
// Both fused with RRF, on the server if the license includes it, and
// on the client if it doesn't.
let fused = articles
.fuse(&Fusion::rrf([
Retriever::standard(Article::TITLE.r#match("graphs")),
Article::EMBEDDING.knn(vec![0.8, 0.2, 0.1], 2, 10),
]))
.await?;

Each field has a handle, Article::TAGS, Article::EMBEDDING, typed by its mapping, which offers only the queries that suit it: term and terms on a keyword field, r#match and match_phrase on text, semantic on semantic_text, knn on a dense vector. A query on the wrong kind of field doesn’t compile.

search takes a retriever, or a query wrapped in Retriever::standard, and returns the best ten hits with their sources read as the type. search_request sends any search request, and fuse fuses retrievers, on the client when the cluster’s license doesn’t include server-side fusion.

crates/oxsearch/examples/documents.rs
assert!(articles.delete("bulk").await?);
assert!(articles.get("bulk").await?.is_none());
articles.delete_index().await?;