Skip to content

AI search

This is the retrieval half of a RAG application: passages indexed with their embeddings, and the ones that answer a question found by fusing a keyword match with nearest neighbours. It runs on any license, with your own embeddings; the quick start shows semantic_text, where Elasticsearch embeds the text itself.

Cargo.toml
[dependencies]
oxsearch = { version = "0.2", features = ["admin", "transport-reqwest"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt"] }

The example stands in for an embedding model with a toy function that scores how much a text is about vectors, ingestion and operations, so it needs nothing but Elasticsearch. In an application, the vectors come from your model.

crates/oxsearch/examples/rag.rs
let mut properties = IndexMap::new();
properties.insert("text".to_owned(), Property::Text(TextProperty::new()));
properties.insert(
"topic".to_owned(),
Property::Keyword(KeywordProperty::new()),
);
properties.insert(
"embedding".to_owned(),
Property::DenseVector(
DenseVectorProperty::new()
.dims(3)
.similarity(DenseVectorSimilarity::Cosine),
),
);
let _ = client.send(&delete::Request::new(INDEX)).await;
let mapping = TypeMapping::new().properties(properties);
client
.send(&create::Request::new(INDEX).body(create::RequestBody::new().mappings(mapping)))
.await?;

The mapping is built from the generated types: text for the keyword match, keyword for the topic, and a dense_vector with cosine similarity for the embedding.

crates/oxsearch/examples/rag.rs
let mut lines: Vec<bulk::RequestBody<Passage>> = Vec::new();
for (n, (text, topic)) in passages.iter().enumerate() {
lines.push(bulk::RequestBody::OperationContainer(
bulk::OperationContainer::Index(
bulk::IndexOperation::new().index(INDEX).id(n.to_string()),
),
));
lines.push(bulk::RequestBody::TDocument(Passage {
text: (*text).to_owned(),
topic: (*topic).to_owned(),
embedding: embed(text),
}));
}
let indexed = client
.send(&bulk::Request::new().refresh(Refresh::True).body(lines))
.await?;
println!("indexed {} passages", indexed.items.len());

A bulk request takes its lines as bulk::RequestBody: an operation, then the document it applies to, as your own type. For large loads, the helpers feature has a bulk loader with backpressure.

crates/oxsearch/examples/rag.rs
// Retrieve for a question: a keyword match and nearest neighbours,
// fused with RRF, on the server if its license includes it.
let question = "How do vector indexes find nearest neighbours?";
let fused = Fusion::rrf([
Retriever::standard(Query::r#match("text", question)),
Retriever::knn("embedding", embed(question), 3, 10),
])
.size(3)
.search::<Passage, _>(&client, INDEX)
.await?;
if let Some(why) = &fused.fallback {
println!("{why}: fused on the client");
}
println!("\n{question}");
for hit in &fused.hits {
if let Some(passage) = &hit.source {
println!(
" {:.3} [{}] {}",
hit.score.unwrap_or_default(),
passage.topic,
passage.text
);
}
}

Fusion::rrf fuses the results of several retrievers with reciprocal rank fusion. Elasticsearch does it on the server with the rrf retriever, which needs a license above Basic. On Basic, the request fails with Error::License, and Fusion runs each retriever on its own and fuses their results on the client instead; fallback says why it did.

Query and Retriever build the common ones in one call each:

  • Query::r#match, Query::term, Query::range and the rest of the query DSL, and Query::semantic on a semantic_text field.
  • Query::knn and Retriever::knn for nearest neighbours of a vector, and Query::sparse_vector for weighted tokens.
  • Retriever::standard for a query, and Retriever::rrf and Retriever::linear to fuse others on the server.

Every other query and retriever the specification describes is a generated type too, and one the types don’t know yet is a Raw variant: what isn’t covered yet.