Bedrock Knowledge Bases: Managed RAG

Generative & Agentic AI · Retrieval-Augmented Generation · Advanced · 22 min

Set up RAG on AWS without building the plumbing: connect a data source, let Amazon Bedrock Knowledge Bases parse, chunk, embed and index it, then query with Retrieve or RetrieveAndGenerate, with metadata filters and citations.

Two conveyor belts. The first carries documents from an S3 bucket through a shredder (chunking) and a translator (embeddings) into a filing cabinet (the vector store). The second carries a question to that cabinet, pulls out the best pages, and hands them to a writer who answers and staples the sources on.

The idea in everyday words

Building RAG yourself is like building your own kitchen: you pick every appliance and fix every leak. Bedrock Knowledge Bases is a restaurant kitchen you rent: the ovens, fridges and dishwashers are installed and maintained. You still choose the menu (data, chunking, model, filters), but you are not fixing the plumbing.

What "managed RAG" actually manages

In the RAG lesson you built the pipeline by hand: load, split, embed, store, search, prompt. Amazon Bedrock Knowledge Bases runs that pipeline for you.

You decide Knowledge Bases does
where the documents live (data source) reads them and tracks what changed
parsing and chunking strategy parses files and splits them into chunks
which embedding model calls it for every chunk
which vector store writes vectors and metadata into it
which LLM answers retrieves, builds the prompt, calls the model, returns citations

There are two pipelines:

  1. Ingestion (sync): data source → parse → chunk → embed → vector store. Runs when you start an ingestion job.
  2. Query: question → embed → search the vector store (plus optional filters and reranking) → either return the chunks, or also generate an answer.

The key idea: you configure the pipeline instead of coding it, and you pay for the underlying pieces (embedding calls, the vector store, model calls). Check the AWS pricing pages for each piece.

Ingestion: from files to vectors

Data sources. Amazon S3 is the most common. Connectors also exist for sources such as web crawling, Confluence, SharePoint and Salesforce, plus a custom data source for pushing documents directly. The list grows, so check the docs.

Parsing. The default parser extracts text. For PDFs full of tables and figures you can choose an advanced parser (a foundation model or Bedrock Data Automation) that understands layout, at extra cost.

Chunking. Options include default (a fixed size set by AWS), fixed-size (you set max tokens and overlap %), hierarchical (parent and child chunks), semantic (split where meaning changes) and no chunking (each file is one chunk). For anything else, a custom transformation Lambda can rewrite chunks during ingestion.

Embeddings. Pick a Bedrock embedding model, for example Amazon Titan Text Embeddings V2 or Cohere Embed. The vector dimension is fixed at creation, so changing models means re-indexing.

Vector store. Quick create sets up Amazon OpenSearch Serverless for you. Other supported stores include Aurora PostgreSQL (pgvector), Amazon S3 Vectors, Neptune Analytics (for GraphRAG) and partner stores such as Pinecone, MongoDB Atlas and Redis.

Metadata for filtering comes from a sidecar file next to each S3 object. For s3://kb-docs/hr/leave.txt it is leave.txt.metadata.json in the same folder:

{ "metadataAttributes": { "dept": "hr", "year": 2025 } }

Sync. Nothing is indexed until you run an ingestion job (console "Sync" button or StartIngestionJob). Jobs are incremental: new, changed and deleted files are processed, unchanged ones are skipped. Schedule a sync (for example EventBridge + Lambda) if your documents change often.

# boto3 (runs against your AWS account, not in the browser)
import boto3
agent = boto3.client("bedrock-agent")             # control plane
job = agent.start_ingestion_job(knowledgeBaseId="KB12345678", dataSourceId="DS12345678")
print(job["ingestionJob"]["status"])              # STARTING, then IN_PROGRESS, then COMPLETE

Querying: Retrieve vs RetrieveAndGenerate

Both live in the bedrock-agent-runtime client.

API Returns Use it when
Retrieve the top chunks with score, text, source location and metadata you want control: your own prompt, your own model call, your own reranking, or retrieval inside an agent
RetrieveAndGenerate a generated answer plus citations pointing to the chunks used you want a working Q&A endpoint fast
import boto3
rt = boto3.client("bedrock-agent-runtime")

# 1) Retrieve: chunks only
resp = rt.retrieve(
    knowledgeBaseId="KB12345678",
    retrievalQuery={"text": "How many days of annual leave do I get?"},
    retrievalConfiguration={"vectorSearchConfiguration": {
        "numberOfResults": 5,
        "overrideSearchType": "HYBRID",           # or "SEMANTIC"; hybrid needs a supported store
        "filter": {"andAll": [
            {"equals": {"key": "dept", "value": "hr"}},
            {"greaterThanOrEquals": {"key": "year", "value": 2024}},
        ]},
    }},
)
for r in resp["retrievalResults"]:
    print(round(r["score"], 3), r["location"]["s3Location"]["uri"])

# 2) RetrieveAndGenerate: retrieval + prompt + model + citations
resp = rt.retrieve_and_generate(
    input={"text": "How many days of annual leave do I get?"},
    retrieveAndGenerateConfiguration={
        "type": "KNOWLEDGE_BASE",
        "knowledgeBaseConfiguration": {
            "knowledgeBaseId": "KB12345678",
            "modelArn": "<model or inference profile ARN>",
        },
    },
)
print(resp["output"]["text"])
for c in resp["citations"]:
    for ref in c["retrievedReferences"]:
        print("source:", ref["location"]["s3Location"]["uri"])
# Pass sessionId=resp["sessionId"] next time so follow-up questions keep context.

Parameter names above match the API at the time of writing; always check the current boto3 docs.

The key idea: Retrieve is a search engine, RetrieveAndGenerate is a search engine plus a writer. Agents (Bedrock Agents, AgentCore) usually call Retrieve as a tool.

Filters, citations and quality knobs

Metadata filters use a small JSON language: comparison operators such as equals, notEquals, greaterThan, lessThan, in, startsWith, combined with andAll and orAll. Use them for:

  • freshness: only documents from this year, so an old policy does not contradict the new one;
  • security: only documents for this tenant or role. Build the filter in your backend from the user's identity, never from text the user typed;
  • scope: only the product the user is asking about.

Citations come back with RetrieveAndGenerate. Show them in the UI so users can verify the answer, and log them so you can debug bad answers.

Quality knobs (availability depends on the vector store and Region, check the docs):

  • number of results, and SEMANTIC vs HYBRID search;
  • reranking with a Bedrock reranker model inside the Retrieve call;
  • query decomposition for multi-part questions;
  • a custom prompt template for RetrieveAndGenerate (for example "If the answer is not in the sources, say you don't know");
  • Bedrock Guardrails attached to generation.

Evaluate with a fixed question set (see Advanced RAG), for example with Amazon Bedrock Evaluations for knowledge bases.

Validate filters before you send them. The real service rejects a filter with an unknown operator, and your own code should too: a typo such as equal instead of equals must fail loudly in tests, not silently return nothing (or, worse, everything) in production. The challenge below asks you to raise an error for exactly this case.

When to build your own instead

Knowledge Bases covers most document Q&A. Build your own pipeline (for example Lambda + Bedrock embeddings + OpenSearch, or LangChain / LlamaIndex) when:

Need Why managed may not fit
A retrieval flow with many custom stages (multi-hop, graph walks, custom scoring) you want full control of every step
A vector store or embedding model that is not supported the managed pipeline only talks to its supported list
Very fine control of cost or latency per query you want to tune every call
The same code on several clouds or on-premises managed services are AWS-only

A common middle path: use Knowledge Bases for ingestion and Retrieve, then write your own prompt, reranking and generation on top.

Equivalents elsewhere: Vertex AI RAG Engine (GCP), Azure AI Search "On Your Data" (Azure), LlamaIndex or LangChain pipelines (open source).

Go deeper (engineer level)

Ingestion job semantics. A sync compares the data source with what was indexed last time: new and changed files are parsed, chunked and embedded again, and files deleted from the source have their vectors removed. Only one ingestion job can run at a time for a data source (check the Bedrock quotas page), so a Lambda that calls StartIngestionJob on every S3 upload will hit ConflictException during a bulk upload. Debounce instead: send S3 events to SQS or EventBridge and start one job every few minutes, or catch the conflict and retry later. Poll GetIngestionJob and read its statistics: individual documents can fail (unsupported format, too large, a malformed metadata sidecar) while the job as a whole still reports COMPLETE.

Chunking trade-offs. Hierarchical chunking searches small child chunks but returns the parent, so precision is high but each result costs more prompt tokens. Changing the chunking strategy after creation is limited, so plan on building a new data source or knowledge base and re-ingesting.

Query-time behaviour.

  • Scores are similarity scores from the vector store, not calibrated probabilities. Do not hard-code a threshold without testing it on your own data.
  • Metadata filters run inside the vector store, so they inherit its filtering behaviour (see Vector Databases: a post-filtering store can return fewer results than numberOfResults).
  • RetrieveAndGenerate uses a prompt template with a placeholder for the search results. Customise it to require citations and an "I don't know" answer.

Security and multi-tenancy. One knowledge base per tenant gives the strongest isolation but multiplies indexes and syncs. A shared knowledge base with a tenant metadata filter is cheaper, but every query path must add the filter server side, and a single missing filter leaks data. Write a test that fails if any retrieval call has no tenant filter.

Step by step

  1. Upload:

    Put leave.txt (25 days, year 2025) and old-leave.txt (20 days, year 2022) in S3, each with a .metadata.json sidecar holding dept and year.

  2. Sync:

    Start an ingestion job. Each file is parsed, split into chunks (here: one sentence each), embedded with Titan Text Embeddings, and written to the vector store with its metadata and S3 URI.

  3. Retrieve without a filter:

    Ask "How many days of annual leave do employees get?". The two leave chunks score the same: one says 25 days, the stale one says 20. The model could pick either.

  4. Add a filter:

    Add {"equals": {"key": "year", "value": 2025}}. Now only the current policy is searched.

  5. RetrieveAndGenerate:

    The KB builds the prompt from the top chunk, calls the model, and returns "25 days of annual leave" with a citation to s3://kb-docs/hr/leave.txt.

  6. Update:

    HR edits the policy. Run another sync; only the changed file is re-processed.

Code example

import math, re

# Pretend S3 bucket: object -> (text, metadata from the .metadata.json sidecar)
bucket = {
    "s3://kb-docs/hr/leave.txt": ("Employees get 25 days of annual leave. Unused leave expires in March.", {"dept": "hr", "year": 2025}),
    "s3://kb-docs/hr/old-leave.txt": ("Employees get 20 days of annual leave.", {"dept": "hr", "year": 2022}),
    "s3://kb-docs/eng/oncall.txt": ("On-call engineers are paged for incidents. Each shift lasts one week.", {"dept": "eng", "year": 2025}),
}
VOCAB = ["employees", "days", "annual", "leave", "expires", "engineers", "paged", "incidents", "shift", "week"]

def embed(text):
    """Stand-in for Titan Text Embeddings: word counts over a tiny vocabulary, normalised."""
    words = re.findall(r"[a-z0-9]+", text.lower())
    v = [words.count(w) for w in VOCAB]
    n = math.sqrt(sum(x * x for x in v)) or 1
    return [x / n for x in v]

class MockKnowledgeBase:
    def __init__(self):
        self.store = []                                  # the "vector store"

    def start_ingestion_job(self, source):
        for uri, (text, meta) in source.items():
            for sentence in [s.strip() for s in text.split(".") if s.strip()]:   # chunk = sentence
                self.store.append({"text": sentence + ".", "uri": uri, "meta": meta, "vec": embed(sentence)})
        return {"status": "COMPLETE", "chunks": len(self.store)}

    def retrieve(self, query, n=2, equals=None):
        q = embed(query)
        hits = [c for c in self.store if not equals or all(c["meta"].get(k) == v for k, v in equals.items())]
        score = lambda c: sum(a * b for a, b in zip(q, c["vec"]))
        hits.sort(key=lambda c: -score(c))
        return [{"score": round(score(c), 3), "text": c["text"], "uri": c["uri"]} for c in hits[:n]]

    def retrieve_and_generate(self, query, equals=None):
        refs = self.retrieve(query, 1, equals)
        answer = "Per the policy: " + refs[0]["text"] + " [1]"      # a real KB calls an LLM here
        return {"output": answer, "citations": [r["uri"] for r in refs]}

kb = MockKnowledgeBase()
print("Sync:", kb.start_ingestion_job(bucket))
q = "How many days of annual leave do employees get?"
print("Retrieve, no filter:")
for r in kb.retrieve(q):
    print("  ", r)
print("Retrieve, year == 2025:")
for r in kb.retrieve(q, equals={"year": 2025}):
    print("  ", r)
print("RetrieveAndGenerate:", kb.retrieve_and_generate(q, equals={"year": 2025}))

Complexity

  • Time: Filter evaluation: O(n × f) for n docs and a filter tree with f nodes. Inside a real vector store the filter is applied during the ANN search.
  • Space: O(depth of the filter tree) for the recursion, plus O(n) for the output list.

Interview tips

  • Draw both pipelines: ingestion (S3 → parse → chunk → embed → vector store, via an ingestion job) and query (embed → search + filter → optional rerank → model → citations).

  • Explain Retrieve vs RetrieveAndGenerate and when you would use each (control vs speed of delivery; agents usually call Retrieve).

  • Say how you keep answers fresh (scheduled incremental syncs, date metadata filters) and secure (tenant filters built server side from identity).

  • Know which choices are fixed at creation (embedding model and dimension, vector store) and need re-indexing to change.

  • Have a view on build vs buy: managed for standard document Q&A, custom when you need unsupported stores or complex multi-stage retrieval.

Challenge: Evaluate a Metadata Filter

Knowledge Bases filters are JSON trees. Write match_filter(docs, flt) that returns the ids of the docs whose metadata satisfies flt, in their original order.

Each filter object has exactly one key:

  • Leaf: equals, notEquals, greaterThan, lessThan → {"key": k, "value": v}; in → value is a list and the field must be one of them.
  • Combiners: andAll and orAll → a list of filters (all / any must be true).
  • If a doc's metadata does not have the key, the leaf is false (even for notEquals).
  • Any other operator (for example the typo equal) must raise an error / throw, anywhere in the tree. Check the whole filter first, before looking at any doc: the call must fail even when docs is empty, when the doc does not have the key, or when the typo sits after an andAll child that is already false. A typo must fail loudly, never match silently.

Example:

docs = [{"id": "d1", "metadata": {"dept": "hr", "year": 2023}},
        {"id": "d2", "metadata": {"dept": "eng", "year": 2024}}]
match_filter(docs, {"equals": {"key": "dept", "value": "hr"}})  →  ["d1"]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Retrieval-Augmented Generation

Previous: Advanced RAG: Chunking, Hybrid Search & Reranking · Next: GraphRAG: Knowledge Graphs for Retrieval