
Amazon Bedrock Knowledge Bases turns a folder of documents into a retrieval-augmented generation (RAG) backend: it parses and chunks your files, creates embeddings, writes them to a vector store, and serves retrieval and answer-generation APIs. Getting a demo working takes an afternoon. Getting answers your users trust takes deliberate choices about chunking, embeddings, filtering, reranking and evaluation. This tutorial walks through those choices in build order, with boto3 code, and finishes with a troubleshooting table for bad answers. Everything here was checked against the AWS documentation on 5 December 2026.
If you are preparing for interviews rather than building, our 110-question Knowledge Bases interview guide covers the concepts in Q&A form. This post is the build guide.
First decision: managed or customer-managed knowledge base
The documentation now describes two kinds of knowledge base, and the choice shapes everything after it.
| Aspect | Bedrock Managed Knowledge Base | Customer-managed knowledge base |
|---|---|---|
| Vector store | Bedrock runs an auto-scaling datastore for you | You provision and operate the vector store |
| Embeddings | Service-managed model by default, or your own Bedrock model with float32 and 1,024 dimensions | Any supported Bedrock embedding model |
| Reranking | Built-in managed reranker, or your own | Optional, using a Bedrock reranker model |
| Connectors | S3, SharePoint, Confluence, Web Crawler, Google Drive, OneDrive, Custom | S3 and Custom |
| Generation API | Retrieve or AgenticRetrieveStream; RetrieveAndGenerate is not supported | Retrieve and RetrieveAndGenerate |
| Regions | 11 listed, including Asia Pacific (Mumbai) | Depends on the vector store, embedding model and reranker you choose; check each Regions page |
One change matters for anyone following older tutorials: from 30 September 2026, you can no longer create new Confluence, SharePoint, Salesforce or Web Crawler connectors on customer-managed knowledge bases. Existing ones keep working. AWS recommends the managed option if you need those connectors. The rest of this tutorial focuses on the customer-managed path, because it exposes every tuning knob and is what most existing production systems use, but the retrieval, filtering, evaluation and troubleshooting advice applies to both.
The ingestion pipeline
Ingestion runs in this order: data source, parsing, chunking, embedding, vector store. Each stage has settings you choose once, and some cannot be changed later. The console warns that you can't change the chunking strategy after connecting a data source.
Data source: Amazon S3
Only general-purpose S3 buckets are supported, and the bucket must be in the same Region as the knowledge base (it can be in another account with the right bucket and key policies). You can limit ingestion to inclusionPrefixes. Sync is incremental: each ingestion job crawls only new, modified and deleted content after the first full run.
For filtering later, put a sidecar file next to each document named <file name>.metadata.json, at most 10 KB:
{
"metadataAttributes": {
"department": {
"value": {"type": "STRING", "stringValue": "hr"},
"includeForEmbedding": false
},
"year": {
"value": {"type": "NUMBER", "numberValue": 2026},
"includeForEmbedding": false
}
}
}
With includeForEmbedding set to true, the key-value pair is prepended to the chunk before embedding, which boosts semantic matches on that metadata. With false, it is stored only for filtering.
Parsing
The default parser handles text. For PDFs with tables, scanned pages or charts, you can use a foundation model as the parser (Claude, Nova and Llama 4 vision model families are listed) or Amazon Bedrock Data Automation, which the docs mark as preview, US West (Oregon) only. When parsed content contains a table or figure, Bedrock can return the whole page or whole table (up to 10,000 characters) in place of the matching chunk. That improves answers about tables, but it also means you can get fewer results than numberOfResults.
Chunking
Strategy (chunkingStrategy) | Settings | When to use |
|---|---|---|
| Default | About 300 tokens, honours sentence boundaries | Starting point for general prose |
FIXED_SIZE | maxTokens, overlapPercentage | Uniform documents such as FAQs and policies |
HIERARCHICAL | Exactly two levelConfigurations (parent and child maxTokens) plus overlapTokens | Long manuals where small chunks match precisely but the model needs the surrounding section |
SEMANTIC | maxTokens 1 to 8,192, bufferSize 0 or 1, breakpointPercentileThreshold 50 to 99 | Documents whose topics shift without clear headings; costs extra because it uses a foundation model |
NONE | Each file is one chunk | When you pre-split content yourself, or use a custom transformation Lambda; loses page-number citations |
Hierarchical chunking retrieves child chunks and then swaps in their parents, so result counts can be lower than requested. AWS does not recommend it with S3 Vectors, because large parent chunks can exceed the per-vector metadata size limit.
Embedding model
| Model | Model ID | Dimensions | Vector types |
|---|---|---|---|
| Titan Text Embeddings V2 | amazon.titan-embed-text-v2:0 | 256, 512, 1,024 | Float, binary |
| Titan Embeddings G1 - Text | amazon.titan-embed-text-v1 | 1,536 | Float |
| Cohere Embed English | cohere.embed-english-v3 | 1,024 | Float, binary |
| Cohere Embed Multilingual | cohere.embed-multilingual-v3 | 1,024 | Float, binary |
Titan Text Embeddings V2 and both Cohere models list ap-south-1 (Mumbai) for single-Region support; Titan G1 does not. For Indian-language content, the multilingual Cohere model is the obvious candidate to evaluate. Multimodal models (Titan Multimodal, Cohere Embed v3 multimodal, Nova Multimodal Embeddings) are also listed for image, audio and video content in S3 or custom sources. Your vector index dimension must match the model.
Vector store
| Store | Notes from the docs |
|---|---|
| Amazon OpenSearch Serverless | Quick-create available; binary vectors supported; HYBRID search when a filterable text field exists; collections can be private behind a VPC endpoint |
| Amazon OpenSearch Service managed clusters | Binary vectors supported; faiss engine only; the domain must use public access (VPC domains are not supported for knowledge bases); custom filter fields need keyword mapping |
| Amazon S3 Vectors | Float only; documented as cost-effective for infrequent-query workloads; up to 1 KB custom metadata and 35 keys per vector |
| Amazon Aurora PostgreSQL | Same account as the knowledge base; you create the table, an HNSW index on the vector column and a GIN index on the text column |
| Amazon Neptune Analytics | GraphRAG; create an empty graph with a vector index at creation time |
| Pinecone, Redis Enterprise Cloud, MongoDB Atlas | Third-party; credentials in AWS Secrets Manager; MongoDB Atlas can use PrivateLink and needs manual filter configuration |
Build it with boto3
The build-time client is bedrock-agent; the query client is bedrock-agent-runtime. This example assumes an OpenSearch Serverless collection and vector index already exist, with the field names shown.
import boto3
REGION = "ap-south-1"
ACCOUNT = "111122223333"
agent = boto3.client("bedrock-agent", region_name=REGION)
kb = agent.create_knowledge_base(
name="hr-policies-kb",
roleArn=f"arn:aws:iam::{ACCOUNT}:role/BedrockKBServiceRole",
knowledgeBaseConfiguration={
"type": "VECTOR",
"vectorKnowledgeBaseConfiguration": {
"embeddingModelArn": f"arn:aws:bedrock:{REGION}::foundation-model/"
"amazon.titan-embed-text-v2:0",
"embeddingModelConfiguration": {
"bedrockEmbeddingModelConfiguration": {"dimensions": 1024}
},
},
},
storageConfiguration={
"type": "OPENSEARCH_SERVERLESS",
"opensearchServerlessConfiguration": {
"collectionArn": f"arn:aws:aoss:{REGION}:{ACCOUNT}:collection/abc123",
"vectorIndexName": "hr-index",
"fieldMapping": {
"vectorField": "embeddings",
"textField": "text",
"metadataField": "bedrock-metadata",
},
},
},
)
kb_id = kb["knowledgeBase"]["knowledgeBaseId"]
ds = agent.create_data_source(
knowledgeBaseId=kb_id,
name="hr-s3",
dataSourceConfiguration={
"type": "S3",
"s3Configuration": {
"bucketArn": "arn:aws:s3:::example-hr-docs",
"inclusionPrefixes": ["policies/"],
},
},
vectorIngestionConfiguration={
"chunkingConfiguration": {
"chunkingStrategy": "HIERARCHICAL",
"hierarchicalChunkingConfiguration": {
"levelConfigurations": [{"maxTokens": 1500}, {"maxTokens": 300}],
"overlapTokens": 60,
},
}
},
)
ds_id = ds["dataSource"]["dataSourceId"]
job = agent.start_ingestion_job(knowledgeBaseId=kb_id, dataSourceId=ds_id)
print(job["ingestionJob"]["ingestionJobId"], job["ingestionJob"]["status"])
The "type": "VECTOR" value and the create_data_source response key (dataSource) follow the API pattern but were not quoted verbatim on the pages we checked; confirm them in the CreateKnowledgeBase and CreateDataSource references for your SDK version. Poll the ingestion job and read its statistics (for example numberOfDocumentsFailed) and failureReasons before you test any queries.
Retrieve vs RetrieveAndGenerate
Retrieve | RetrieveAndGenerate | |
|---|---|---|
| Returns | Chunks with content, location, metadata and score | A generated answer with citations and a sessionId |
| Prompt control | Full: you build the prompt and call Converse yourself | Prompt templates via promptTemplate.textPromptTemplate |
| Best for | Agents, custom prompts, multi-source RAG, non-Bedrock models | Fast path to a cited answer with conversation memory |
| Managed KB | Supported | Not supported |
Retrieve with a filter and reranking
rt = boto3.client("bedrock-agent-runtime", region_name="us-west-2")
resp = rt.retrieve(
knowledgeBaseId=kb_id,
retrievalQuery={"text": "How many casual leave days do new joiners get?"},
retrievalConfiguration={
"vectorSearchConfiguration": {
"numberOfResults": 20, # 1 to 100
"filter": {
"andAll": [ # andAll and orAll need 2+ items
{"equals": {"key": "department", "value": "hr"}},
{"greaterThanOrEquals": {"key": "year", "value": 2025}},
]
},
"rerankingConfiguration": {
"type": "BEDROCK_RERANKING_MODEL",
"bedrockRerankingConfiguration": {
"modelConfiguration": {
"modelArn": "arn:aws:bedrock:us-west-2::foundation-model/"
"amazon.rerank-v1:0"
},
"numberOfRerankedResults": 5,
},
},
}
},
)
for r in resp["retrievalResults"]:
print(round(r["score"], 3), r["location"], r["content"]["text"][:80])
Reranking pays off when the right chunk is somewhere in the top 20 but not in the top 3. Check Regions carefully: the reranker models listed are Amazon Rerank 1.0 (ap-northeast-1, ca-central-1, eu-central-1, us-west-2) and Cohere Rerank 3.5 (the same plus us-east-1). Mumbai is not listed for either at the time of checking, which is why this example uses us-west-2; a Mumbai knowledge base would need the managed knowledge base's built-in reranker or reranking outside Bedrock.
Filter operators include equals, notEquals, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, in, notIn, listContains, stringContains, startsWith, andAll and orAll. startsWith is documented for OpenSearch Serverless only. There is also implicitFilterConfiguration, where a model derives filters from the question using metadata attribute descriptions you supply.
RetrieveAndGenerate with a guardrail and session
resp = rt.retrieve_and_generate(
input={"text": "And how many can carry forward?"},
sessionId=previous_session_id, # omit on the first turn; Bedrock creates it
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": kb_id,
# A model ARN or inference profile ARN
"modelArn": "<generation model or inference profile ARN>",
"retrievalConfiguration": {
"vectorSearchConfiguration": {"numberOfResults": 8}
},
"generationConfiguration": {
"guardrailConfiguration": {
"guardrailId": "<guardrail id>",
"guardrailVersion": "1",
},
"inferenceConfig": {
"textInferenceConfig": {"maxTokens": 600, "temperature": 0}
},
},
},
},
)
print(resp["output"]["text"])
print(resp.get("guardrailAction")) # INTERVENED or NONE
for c in resp["citations"]:
for ref in c["retrievedReferences"]:
print(ref["location"])
previous_session_id = resp["sessionId"]
You cannot choose your own sessionId; reuse the one Bedrock returns. Pass sessionConfiguration with a kmsKeyArn to encrypt session data with your own key. For building and testing the guardrail itself, follow our Bedrock Guardrails tutorial; its contextual grounding check is a strong second line of defence against unsupported answers.
IAM: three roles to get right
- Service role that Bedrock assumes. Trust
bedrock.amazonaws.comwithaws:SourceAccountand anaws:SourceArnofarn:aws:bedrock:<region>:<account>:knowledge-base/*(narrow the wildcard after creation). Grantbedrock:InvokeModelon the embedding model,s3:ListBucket/s3:GetObjecton the bucket with anaws:ResourceAccountcondition, and store access such asaoss:APIAccessAllon the collection. - Application role that queries.
bedrock:Retrieveon the knowledge base ARN; forRetrieveAndGenerate, alsobedrock:RetrieveAndGenerateandbedrock:InvokeModelon the generation model; addbedrock:Rerankif you rerank inRetrieveAndGenerate. - Data-source admins. AWS warns that data source actions don't pass a role, so anyone who can create or sync a data source can ingest whatever the service role can read, and anyone with
bedrock:Retrievecan read everything ingested. Scope the service role to exact prefixes and treat data source actions as privileged.
Private connectivity
Application calls go to the bedrock-agent-runtime interface VPC endpoint, and build-time calls to bedrock-agent. On the store side, an OpenSearch Serverless collection can use VPC network access so it isn't reachable from the internet, while OpenSearch managed cluster domains must stay public for knowledge bases. MongoDB Atlas documents an optional PrivateLink path. The Bedrock security and private networking guide covers endpoint policies, KMS and logging for the whole stack.
Evaluate before and after every change
Bedrock RAG evaluation jobs use an LLM judge. A retrieve-only job scores Builtin.ContextRelevance and Builtin.ContextCoverage (coverage needs ground-truth answers). A retrieve-and-generate job adds Builtin.Correctness, Builtin.Completeness, Builtin.Helpfulness, Builtin.LogicalCoherence, Builtin.Faithfulness, Builtin.CitationPrecision, Builtin.CitationCoverage, Builtin.Harmfulness, Builtin.Stereotyping and Builtin.Refusal. You can also bring your own inference responses from a RAG system outside Bedrock, and define custom metrics.
Build a test set of 50 to 200 real questions with reference answers, including questions whose answer is not in the corpus. Run it whenever you change chunking, the embedding model, the prompt template, numberOfResults or the reranker. Retrieval metrics tell you whether the problem is search; generation metrics tell you whether it is the prompt or model.
Cost levers
- Vector store choice. S3 Vectors is positioned for infrequent-query workloads at lower cost; OpenSearch suits high query rates and hybrid search.
- Smaller vectors. Titan Text Embeddings V2 supports 256 and 512 dimensions; binary embeddings (OpenSearch only) shrink storage further. Re-run your evaluation, because recall can drop.
- Chunking. Semantic chunking and foundation-model parsing invoke models during ingestion and add cost; use them only where the evaluation shows a gain.
- Retrieve fewer, rerank smarter. Sending eight good chunks costs fewer input tokens than sending twenty mediocre ones.
- Inference profiles. Knowledge bases accept inference profiles for generation; global cross-Region profiles are documented as roughly 10% cheaper than geographic ones, at the cost of worldwide routing.
- Incremental sync. Sync on a schedule matched to how often documents actually change.
Troubleshooting bad answers
| Symptom | Likely cause | What to check |
|---|---|---|
| "I couldn't find that" for content you know exists | Ingestion failed or skipped the file | Ingestion job statistics and failureReasons; bucket Region; inclusion prefixes; KMS decrypt permission |
| Right document, wrong section | Chunks too large or poorly split | Call Retrieve alone and read the chunks; try hierarchical or smaller fixed-size chunks |
| Correct chunk at rank 9, answer wrong | Ranking | Add a reranker; raise numberOfResults before reranking |
| Exact codes or product names missed | Pure semantic search | overrideSearchType HYBRID on OpenSearch Serverless; metadata with includeForEmbedding |
| Filter returns too few results on Aurora | Filtering applied after the HNSW scan | Enable iterative index scans (pgvector 0.8.0 or later), as the docs recommend |
| Filter fails on OpenSearch managed clusters with a "Rewrite first" error | Custom metadata field not keyword-mapped | Map the field as keyword or text with a keyword subfield |
| Fewer results than requested | Hierarchical chunking or table/page context merging | Expected behaviour; account for it in prompts |
| Answer adds facts not in the sources | Model filling gaps | Stricter prompt template, lower temperature, guardrail grounding check, Faithfulness metric |
| Stale answers | Sync not run | Schedule ingestion jobs after document updates |
For the wider AWS service map around a RAG system (IAM, EKS, Lambda), see AWS for AI engineers, and for interview rounds that go beyond Knowledge Bases, our Bedrock interview questions and AWS interview questions hub. If your RAG system will sit behind an agent, the AgentCore interview guide explains how agents consume retrieval tools.
Practise this at Cloud Soft Solutions
Building a knowledge base end to end, from S3 ingestion and chunking experiments to evaluation jobs and filtered retrieval, is one of the hands-on labs in our AI, GenAI and Agentic AI course. The supporting AWS skills, such as IAM, VPC endpoints and S3, are covered in our AWS training in Hyderabad. You can join in the classroom in Ameerpet or online.
Sources
- Build a managed knowledge base, checked 5 December 2026
- Managed knowledge base Regions, checked 5 December 2026
- Connect a data source to your knowledge base, checked 5 December 2026
- Connect to Amazon S3 for your knowledge base, checked 5 December 2026
- How content chunking works, checked 5 December 2026
- Supported models and Regions for knowledge bases, checked 5 December 2026
- Prerequisites for your own vector store, checked 5 December 2026
- Supported Regions and models for reranking, checked 5 December 2026
- Permissions for reranking, checked 5 December 2026
- Service role for Knowledge Bases, checked 5 December 2026
- Evaluate RAG sources, checked 5 December 2026
- RAG evaluation metrics, checked 5 December 2026
- Protect your data using Amazon VPC and AWS PrivateLink, checked 5 December 2026
- CreateKnowledgeBase API reference, checked 5 December 2026
- ChunkingConfiguration, HierarchicalChunkingConfiguration and SemanticChunkingConfiguration, checked 5 December 2026
- StartIngestionJob API reference, checked 5 December 2026
- Retrieve API reference, checked 5 December 2026
- RetrieveAndGenerate API reference, checked 5 December 2026
- RetrievalFilter, KnowledgeBaseVectorSearchConfiguration and VectorSearchRerankingConfiguration, checked 5 December 2026
- Global cross-Region inference, checked 5 December 2026
📞 Call +91 96660 19191 · +91 99496 16388 · WhatsApp
Cloud Soft Solutions, 513, 5th Floor, Aditya Enclave, Nilagiri Block, beside Ameerpet Metro Station, Ameerpet, Hyderabad 500016, Telangana, India
Frequently Asked Questions
What is the difference between Retrieve and RetrieveAndGenerate?
Retrieve returns ranked chunks with content, location, metadata and score so you can build your own prompt. RetrieveAndGenerate retrieves and then generates a cited answer with a session ID for follow-up questions. RetrieveAndGenerate is not supported on managed knowledge bases.
Which chunking strategies do Bedrock Knowledge Bases support?
Default (about 300 tokens), fixed-size, hierarchical (parent and child levels), semantic and no chunking. You can also use a custom transformation Lambda function. The chunking strategy cannot be changed after the data source is connected.
Which vector stores can a customer-managed knowledge base use?
Amazon OpenSearch Serverless, OpenSearch Service managed clusters, Amazon S3 Vectors, Amazon Aurora PostgreSQL, Amazon Neptune Analytics, Pinecone, Redis Enterprise Cloud and MongoDB Atlas.
Which reranking models work with Knowledge Bases?
Amazon Rerank 1.0 (amazon.rerank-v1:0) and Cohere Rerank 3.5 (cohere.rerank-v3-5:0). Regional support differs: Amazon Rerank 1.0 is not available in US East (N. Virginia), and neither model was listed for Asia Pacific (Mumbai) when this was checked.
How do I filter knowledge base results by metadata?
Add a .metadata.json file of up to 10 KB next to each S3 document, then pass a filter such as equals, in, greaterThan, listContains, andAll or orAll in vectorSearchConfiguration. startsWith is documented for OpenSearch Serverless only.
Which metrics do Bedrock RAG evaluation jobs provide?
Retrieve-only jobs report context relevance and context coverage. Retrieve-and-generate jobs add correctness, completeness, helpfulness, logical coherence, faithfulness, citation precision, citation coverage, harmfulness, stereotyping and refusal.



