Skip to main content

Load documents into an index

Every Markdown and text file in a folder, split into chunks and added to an index, each chunk carrying the file it came from.

text-splitter = { version = "0.33", features = ["markdown"] }
use freyja::{Document, Index};
use serde_json::json;
use std::path::Path;
use text_splitter::MarkdownSplitter;

/// Adds every Markdown and text file in `dir` to `index`, and returns how
/// many chunks went in.
async fn load(index: &Index, dir: &Path) -> Result<usize, Box<dyn std::error::Error>> {
let splitter = MarkdownSplitter::new(1000);
let mut added = 0;
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
let Some("md" | "txt") = path.extension().and_then(|extension| extension.to_str()) else {
continue;
};
let text = std::fs::read_to_string(&path)?;
let source = path.display().to_string();
let chunks: Vec<Document> = splitter
.chunks(&text)
.enumerate()
.map(|(chunk, piece)| Document::new(piece).metadata(json!({"source": source, "chunk": chunk})))
.collect();
added += chunks.len();
index.add(chunks).await?;
}
Ok(added)
}

Call it once at start, then search or hand the index to an agent:

let index = Index::new(client.clone(), "text-embedding-3-small");
let added = load(&index, Path::new("docs")).await?;

let hits = index.search("how long do refunds take?", 3).await?;
println!("{} (from {})", hits[0].text, hits[0].metadata["source"]);

Files of other types are skipped. The splitter keeps Markdown sections whole up to 1,000 characters, so a heading stays with its paragraph. Plain text splits on paragraphs and sentences the same way.

The source in the metadata is how a hit names its file, and how Update and delete documents finds a file's chunks again. The chunk number keeps them in order.

read_dir reads one folder. The walkdir crate walks a tree, and the loop stays the same.

PDFs and other formats​

An index holds text, so a PDF has to become text first. A crate such as pdf-extract does that, and its output goes through the same splitter. When a question is about one PDF, sending the file to the model is simpler. See Ask about a PDF.

Testing it for free​

HashEmbedder makes vectors from words, with no key and no network, so the loader can be tested on a folder of fixtures:

use freyja::testing::HashEmbedder;

let index = Index::new(HashEmbedder, "hash");
load(&index, Path::new("tests/fixtures")).await?;
let hits = index.search("how long do refunds take", 1).await?;
assert!(hits[0].text.contains("five business days"));

See Testing retrieval.