Skip to main content

Update and delete documents

Index::delete deletes every chunk whose metadata matches a filter, so a changed file is replaced by deleting its chunks and adding the new ones. It works on InMemoryVectors and on PgVectorStore.

Replacing a file​

Give every chunk a source, as Load documents into an index does, and a file's chunks are one delete away.

use freyja::{Document, Index};
use serde_json::json;

/// Replaces every chunk of `path` with `chunks`.
async fn replace(index: &Index, path: &str, chunks: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
index.delete(&json!({"source": path})).await?;
index
.add(chunks.into_iter().map(|text| Document::new(text).metadata(json!({"source": path}))))
.await?;
Ok(())
}

Deleting a file is the first half: the delete alone. It returns how many chunks it deleted, and 0 when the file was never added. A filter with a second key, such as {"source": path, "chunk": 0}, narrows it further.

Rebuilding without a gap​

Between the delete and the add, a search does not find the file. For a whole rebuild with no such gap, build into a new collection, switch to it, then clear the old one:

use freyja::{Client, EndpointPreset};
use freyja_sqlx::PgVectorStore;

// Connects to OpenAI with the key in OPENAI_API_KEY, for the embeddings.
let client = Client::from_env(EndpointPreset::OpenAi)?;
let next = Index::with_store(client.clone(), "text-embedding-3-small", PgVectorStore::new(pool.clone(), "handbook-v2"));
load(&next, Path::new("docs")).await?;
// Build agents from `next` from here on, then:
PgVectorStore::new(pool.clone(), "handbook").clear().await?;

In memory​

InMemoryVectors keeps nothing between runs, so the index is built at start from the files on disk. While it runs, replace above updates it in place, and an agent's search tool sees the change, since it shares its texts with the index. A whole rebuild is a new index, and the agent is built again from it, since its search tool keeps the index it was given.

Re-embedding costs​

Every replaced chunk is embedded again, and embedding is billed. Replace only the files that changed, which is what keying on source makes possible. A file's modification time, or a hash of its text kept in the metadata, tells you which ones those are.