Skip to content

Tags ​

This page is the reference of concepts of tagged retrieval in duckdb-vectors: what a tag is, how the prefix is built, how the metadata of a document is merged, and which keys are reserved. It does not say what to do when a search fails. The troubleshooting procedure does, and it leads to the procedures that apply the concepts, in the order of their cost: project tags, evaluate retrieval and generate contextual tags.

What is tagged retrieval? ​

Tagged retrieval puts context back in front of a chunk before it is embedded. It is a deterministic variant of Anthropic's Contextual Retrieval: the context comes from the front matter of the page, and no language model runs while you index. Indexing stays offline and repeatable.

Three terms are used consistently in the documentation:

  • A tag is a short label: value pair taken from the front matter of a page.
  • A section context is a sentence that situates one section in its page. It is stored as metadata of that section, and it is indexed like any other tag.
  • The prefix is the block of tag lines put in front of the chunk text before embedding.

Adopters meet the practice in four layers, ordered by cost: project the metadata that you already have, measure on your own questions, generate contextual tags with a model where the metadata is thin, and keep the tags fresh in continuous integration. The procedures of the follow-up section carry them.

What is a tag for? ​

Chunking removes context. A chunk that says "the refund window is 30 days" no longer says which product or which audience it belongs to, so a search for the enterprise plan can return the consumer chunk. A tag restores that context. With tagged retrieval each chunk is embedded as its tags followed by its text:

text
product: Atlas
audience: finance, support
The refund window is 30 days from the invoice date.

Only the embedded text changes. The chunk stored in the index, and the text returned to the caller, stay the raw chunk.

A tag helps when its value is something a searcher says, or something that separates chunks the searcher would confuse: a product, a company, a news source. A tag that every document shares adds noise, because it separates nothing. A tag shared by several documents that have something in common is what you want. A tag with a different value on every document does no harm by itself: a title can match words in a query, while an opaque code such as REF-001 cannot.

How are tags declared? ​

Tagging is off by default, and an index built without it is the same as before. A tag is declared as a label: $.path pair, where the path is a JSONPath expression evaluated over the metadata of the document. The list of pairs is ordered, and the order is the order of the lines in the prefix. It is given to the indexer with --tag-field, to Settings as tag_fields, or in the environment as DUCKDB_VECTORS_TAG_FIELDS. The projection procedure shows the three forms.

Four rules describe the behavior:

  • A tag whose path finds nothing in a document is left out of the prefix of that document.
  • Changing the list, or a value, embeds again only the chunks whose prefix changed. add_texts and put_vectors tag too, from the metadata that you pass.
  • By default the tags only change the embedding. --tag-bm25, or DUCKDB_VECTORS_TAG_BM25=true, also matches them in the exact-token keyword search.
  • The keyword index is built by the process that indexes, and a search follows whatever index the file holds. Indexing again with the other --tag-bm25 setting rebuilds it, even when no page changed.

Which JSONPath expressions work? ​

duckdb-vectors evaluates paths with the JSON engine of DuckDB, tested on DuckDB 2.0. It supports the common subset of JSONPath, not the whole of RFC 9535.

Front matter shapePathResult
Top-level key$.titleThe value
Nested key$.product.nameThe value
Array$.audience[*]Every item, joined with commas
One array item$.audience[0], $.audience[#-1]First and last item
Array of objects$.authors[*].nameEvery name, joined with commas
Nested arrays$.matrix[*][*]Flattened, joined with commas
Key with a hyphen or a space$."my-key"The value
Any depth$..nameEvery name below the root
Missing key$.missingNo tag for that document

Dates are ISO text. PDF files expose their document information as $.title, $.author, $.subject and $.keywords, when the file declares them, so the same paths work on PDF and Markdown files. Filter expressions such as $.authors[?(@.name=='x')] and bracket-quoted keys such as $['title'] are rejected by DuckDB. Use the quoted dot form instead.

How to give each section its own context? ​

Front matter describes a whole page, so its tags are the same for every chunk of the page. A Markdown page can also carry metadata for one section only, under the reserved sections key. Each entry is keyed by the section path that the chunker reports in the section_path of each chunk:

yaml
---
title: Deployment runbook
sections:
  deployment-runbook/rollback:
    retrieval:
      context: How to roll back a failed Cedar release, after the canary step.
---

The chunker merges each entry into the chunks of that section, so $.retrieval.context is a tag like any other:

shell
$ duckdb-vectors index ./docs --recursive \
    --tag-field "context: $.retrieval.context" --tag-bm25

An entry whose path matches no section is logged as a warning, so a renamed heading does not fail silently. Writing a context like this for every section, with a language model that reads each page once, is Anthropic's Contextual Retrieval moved upstream of indexing. The generation procedure does it, and the evaluation procedure measures the result on your own questions.

Where can tags live besides the front matter? ​

In a sidematter file: a YAML file next to the document, named after it with .sidematter.yaml added, such as deployment-runbook.md.sidematter.yaml. The indexer merges it into the metadata of the document, so tags written by a model stay out of the file that people edit, and a document that has no front matter, such as a PDF file, can still carry them.

yaml
# deployment-runbook.md.sidematter.yaml
retrieval:
  product: Cedar
sections:
  deployment-runbook/rollback:
    retrieval:
      context: How to roll back a failed Cedar release, after the canary step.

The metadata of a document is read in this order: the native metadata (the front matter of a Markdown page, the document information of a PDF file), then the sidematter, then the entry of sections for the chunk's section, or of pages for a PDF page. The native metadata wins on a collision: when the same key path holds a different value in both places, the native value is kept and a warning names the document and the key. A sidematter file whose document is missing is reported as a warning. Every --tag-field expression and every SQL filter then works the same, whichever file the value came from. The generation procedure writes its tags to sidematter files by default. This is the only definition of sidematter in the documentation: the other pages link here.

Which keys are reserved? ​

Some keys of the metadata have a meaning for the chunkers and the scripts, so do not use them for other purposes.

KeyWhereMeaning
sectionsFront matter or sidematter of a Markdown pageMetadata for the chunks of one section, keyed by section_path. Never copied into chunk metadata as such.
pagesSidematter of a PDF fileMetadata for the chunks of one page, keyed by the 1-based page number.
retrievalFront matter or sidematterValues derived by a model or a script for retrieval, such as retrieval.context. They stay apart from the tags that people wrote.
crcFront matter or sidematterFingerprint of the page text, written by the curation scripts to tell whether the tags are current.
document.titleAdded by the Markdown and PDF chunkersThe title of the front matter, else the first H1 of the page, else the file name without extension. For a PDF, the title of the document information, else the file name without extension.
document.pathAdded by every chunkerThe path of the file relative to the indexed folder, without extension, with its separators.
section.headingsAdded by the Markdown chunkerThe text of the headings of the section, from H1 down, joined with >. It is the readable form of section_path.

The names document and section are reserved: they win over a front matter key of the same name. For example, --tag-field "title: $.document.title" --tag-field "where: $.section.headings" puts the title and the position of each section in front of its text. A mapping that a page keeps under document keeps its other keys. Without a tag field, the embedded text, the etag and the vector of a chunk do not change; only the stored metadata of the chunk gains these keys. The results workbook reports which of these tags improve retrieval. The three keys added by the chunkers cost nothing to produce, and the projection procedure shows how to use them as tags.

Who should write the tags? ​

People write the best tags, because they know the words that searchers use. Use the front matter that already exists, and fill it in where it is sparse.

A language model can write section contexts when pages have little front matter: duckdb-vectors annotate does it, and the generation procedure explains how. Keep what a model writes under its own key, $.retrieval, so that derived values never mix with tags written by people. Page-level tags that a model derived did not help on our pages, and the command was removed. Only a run on your own questions shows that a tag helps.

How to control the tag vocabulary? ​

Tags only group documents when the same thing is always written the same way. Enterprise, enterprise plan and Ent. count as three values and split a group that should be one. Agree on a list of allowed values for each tag, check the front matter against it in review, and prefer a short fixed list over free text.

If a language model proposes tags, compare them with the native tags before you trust them, and discard answers such as "Other" or "None": a tag that says nothing tells a search nothing. The inspection procedure lists the values of each tag, so you can spot variants.

How long can the prefix be? ​

The prefix has no length cap, because truncating it would silently drop a tag you chose. The limit that matters is the input window of the embedding model, and models cut input beyond it. With fastembed 0.9.1 every model cuts at 512 tokens, the default static model included, and the two paraphrase-multilingual models were trained on 128. A long prefix pushes the end of the chunk out of the window.

The tags report warns when prefix plus chunk probably exceeds the window of the active model, estimated at four characters per token. Keep the prefix to the few tags that matter. The benchmark found no reliable difference between putting the tags before or after the chunk text, except for transformers, as the last section explains.

Can tags be used in SQL queries? ​

Yes. The front matter of a page is also stored as JSON in the metadata column of each of its chunks, and section metadata is merged into the chunks of that section. A plain SELECT can filter on any of it, whether or not the tag is embedded:

sql
SELECT source, title
FROM chunks
WHERE json_extract_string(metadata, '$.kind') = 'policy';

The user guide shows how to inject such a filter into a search, or into the ranking itself.

See also ​