Self-Query Retrieval

Let the LLM turn a natural-language question into a search query plus metadata filters.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 8 · Lesson 4 of 7 · Intermediate

Self-Query Retrieval

Let the LLM turn a natural-language question into a search query plus metadata filters.

Users rarely use filter dropdowns; they type questions such as "What did the 2025 finance policy say about hotel limits?". That question contains a semantic part ("hotel limits") and two filters (year = 2025, department = finance). Self-query retrieval uses an LLM to separate them: it turns the question into a search query plus structured metadata filters, which the vector store then applies.

How it works

  1. Describe your metadata fields and their allowed values to the LLM.
  2. The LLM returns a structured object: a rewritten search query and the filters it found.
  3. Your code validates the filters and converts them into the vector store's filter syntax.
  4. Run a filtered vector search.

Define the filter schema

A Pydantic model with fixed allowed values (Literal) ensures the LLM can only produce filters your index understands.

self_query.py
from typing import Literal, Optional
from pydantic import BaseModel, Field
import anthropic
from rag_helpers import embed

client = anthropic.Anthropic()

class SearchRequest(BaseModel):
    query: str = Field(description="The search text, with filter words removed")
    department: Optional[Literal["hr", "finance", "it", "legal"]] = None
    year_from: Optional[int] = None
    year_to: Optional[int] = None
    doc_type: Optional[Literal["policy", "faq", "procedure", "report"]] = None

SYSTEM = """You turn user questions into search requests for a company document index.
Metadata available:
- department: hr, finance, it or legal
- year: the year the document was published
- doc_type: policy, faq, procedure or report
Only set a filter when the question clearly asks for it. Do not guess.
Put the remaining topic words in `query`."""

def parse_question(question: str) -> SearchRequest:
    response = client.messages.parse(
        model="claude-opus-5-5",
        max_tokens=1000,
        output_config={"effort": "low"},
        system=SYSTEM,
        messages=[{"role": "user", "content": question}],
        output_format=SearchRequest,
    )
    return response.parsed_output

print(parse_question("What did the 2025 finance policy say about hotel limits?"))
query='hotel limits' department='finance' year_from=2025 year_to=2025 doc_type='policy'

Convert to a vector store filter

def to_chroma_where(req: SearchRequest) -> dict | None:
    conditions = []
    if req.department:
        conditions.append({"department": req.department})
    if req.doc_type:
        conditions.append({"doc_type": req.doc_type})
    if req.year_from:
        conditions.append({"year": {"$gte": req.year_from}})
    if req.year_to:
        conditions.append({"year": {"$lte": req.year_to}})
    if not conditions:
        return None
    return conditions[0] if len(conditions) == 1 else {"$and": conditions}

def self_query_search(collection, question: str, k: int = 5):
    req = parse_question(question)
    where = to_chroma_where(req)
    query_vec = embed(req.query, query=True)[0].tolist()
    result = collection.query(query_embeddings=[query_vec], n_results=k, where=where)
    if where and not result["ids"][0]:
        # The filters were too strict (or wrong): fall back to an unfiltered search
        result = collection.query(query_embeddings=[query_vec], n_results=k)
    return req, result

Things to watch

  • Over-filtering. An LLM that reads "recent" as year_from=2026 can hide the only relevant document. Keep the fallback, and tell the model to set filters only when the question is explicit.
  • Relative dates. "Last year" depends on today's date. Put the current date in the prompt (after any cached prefix, so it does not break caching).
  • Security filters are not self-query filters. Tenant and permission filters must always be added by your code, never chosen by the LLM.
  • Latency. Self-query adds one LLM call before retrieval. Use low effort and a short prompt, or a small, fast model for this step.
Frameworks

LangChain's SelfQueryRetriever and LlamaIndex's VectorIndexAutoRetriever implement the same idea, translating to many vector store filter syntaxes.

Key takeaways

  • Self-query retrieval lets an LLM extract metadata filters and a clean search query from a natural question.
  • Constrain the output with a schema whose values match your metadata exactly.
  • Fall back to unfiltered search when filters return nothing.
  • Never let the LLM choose security-relevant filters.