Skip to main content
Ameerpet, Hyderabad · Classroom & live online
Cloud Soft Solutions

Production RAG with Amazon Bedrock Knowledge Bases: Chunking, Vector Stores, Reranking and Evaluation

Build production RAG on Amazon Bedrock Knowledge Bases: managed vs customer-managed, S3 metadata, parsing, chunking strategies, embedding models, vector stores, Retrieve vs RetrieveAndGenerate, filters, reranking, evaluation, IAM, cost and troubleshooting.

Production RAG architecture with Amazon Bedrock Knowledge Bases, S3 data source, embeddings, vector store and reranking
Last updated · 13 min read · 2,926 words

Production RAG architecture with Amazon Bedrock Knowledge Bases, S3 data source, embeddings, vector store and reranking

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.

AspectBedrock Managed Knowledge BaseCustomer-managed knowledge base
Vector storeBedrock runs an auto-scaling datastore for youYou provision and operate the vector store
EmbeddingsService-managed model by default, or your own Bedrock model with float32 and 1,024 dimensionsAny supported Bedrock embedding model
RerankingBuilt-in managed reranker, or your ownOptional, using a Bedrock reranker model
ConnectorsS3, SharePoint, Confluence, Web Crawler, Google Drive, OneDrive, CustomS3 and Custom
Generation APIRetrieve or AgenticRetrieveStream; RetrieveAndGenerate is not supportedRetrieve and RetrieveAndGenerate
Regions11 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)SettingsWhen to use
DefaultAbout 300 tokens, honours sentence boundariesStarting point for general prose
FIXED_SIZEmaxTokens, overlapPercentageUniform documents such as FAQs and policies
HIERARCHICALExactly two levelConfigurations (parent and child maxTokens) plus overlapTokensLong manuals where small chunks match precisely but the model needs the surrounding section
SEMANTICmaxTokens 1 to 8,192, bufferSize 0 or 1, breakpointPercentileThreshold 50 to 99Documents whose topics shift without clear headings; costs extra because it uses a foundation model
NONEEach file is one chunkWhen 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

ModelModel IDDimensionsVector types
Titan Text Embeddings V2amazon.titan-embed-text-v2:0256, 512, 1,024Float, binary
Titan Embeddings G1 - Textamazon.titan-embed-text-v11,536Float
Cohere Embed Englishcohere.embed-english-v31,024Float, binary
Cohere Embed Multilingualcohere.embed-multilingual-v31,024Float, 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

StoreNotes from the docs
Amazon OpenSearch ServerlessQuick-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 clustersBinary 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 VectorsFloat only; documented as cost-effective for infrequent-query workloads; up to 1 KB custom metadata and 35 keys per vector
Amazon Aurora PostgreSQLSame 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 AnalyticsGraphRAG; create an empty graph with a vector index at creation time
Pinecone, Redis Enterprise Cloud, MongoDB AtlasThird-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

RetrieveRetrieveAndGenerate
ReturnsChunks with content, location, metadata and scoreA generated answer with citations and a sessionId
Prompt controlFull: you build the prompt and call Converse yourselfPrompt templates via promptTemplate.textPromptTemplate
Best forAgents, custom prompts, multi-source RAG, non-Bedrock modelsFast path to a cited answer with conversation memory
Managed KBSupportedNot 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.com with aws:SourceAccount and an aws:SourceArn of arn:aws:bedrock:<region>:<account>:knowledge-base/* (narrow the wildcard after creation). Grant bedrock:InvokeModel on the embedding model, s3:ListBucket/s3:GetObject on the bucket with an aws:ResourceAccount condition, and store access such as aoss:APIAccessAll on the collection.
  • Application role that queries. bedrock:Retrieve on the knowledge base ARN; for RetrieveAndGenerate, also bedrock:RetrieveAndGenerate and bedrock:InvokeModel on the generation model; add bedrock:Rerank if you rerank in RetrieveAndGenerate.
  • 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:Retrieve can 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

SymptomLikely causeWhat to check
"I couldn't find that" for content you know existsIngestion failed or skipped the fileIngestion job statistics and failureReasons; bucket Region; inclusion prefixes; KMS decrypt permission
Right document, wrong sectionChunks too large or poorly splitCall Retrieve alone and read the chunks; try hierarchical or smaller fixed-size chunks
Correct chunk at rank 9, answer wrongRankingAdd a reranker; raise numberOfResults before reranking
Exact codes or product names missedPure semantic searchoverrideSearchType HYBRID on OpenSearch Serverless; metadata with includeForEmbedding
Filter returns too few results on AuroraFiltering applied after the HNSW scanEnable iterative index scans (pgvector 0.8.0 or later), as the docs recommend
Filter fails on OpenSearch managed clusters with a "Rewrite first" errorCustom metadata field not keyword-mappedMap the field as keyword or text with a keyword subfield
Fewer results than requestedHierarchical chunking or table/page context mergingExpected behaviour; account for it in prompts
Answer adds facts not in the sourcesModel filling gapsStricter prompt template, lower temperature, guardrail grounding check, Faithfulness metric
Stale answersSync not runSchedule 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

📞 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.

Share𝕏inf✉
EnrollWhatsAppCall us