
How We Improved OpenSearch Retrieval Quality by Rethinking Our Chunking Strategy
This article explores how better document chunking can improve retrieval quality in Retrieval-Augmented Generation (RAG) applications using Amazon OpenSearch. It explains fixed-size, recursive, semantic, and hierarchical chunking strategies, along with practical implementation steps covering document preprocessing, embeddings, vector indexing, and retrieval.
A Retrieval-Augmented Generation (RAG) application can use a powerful language model, a vector database, and a well-designed prompt and still return irrelevant answers. One reason is often overlooked during development: how the source documents are divided before embedding.
Document chunking directly influences what information becomes searchable. When a document is split incorrectly, important context can disappear, related information can become disconnected, and the retrieval system may return passages that look relevant but do not actually answer the user's question.
While exploring AI data engineering RAG workflows, I found that improving document preparation and chunking deserves as much attention as selecting an embedding model or tuning vector search.
This article explains how to approach chunking optimization with Amazon OpenSearch Service and build a more reliable retrieval pipeline.
Why Chunking Matters in RAG Applications
RAG combines information retrieval with large language model generation. Instead of asking an LLM to answer exclusively from its training knowledge, the application retrieves relevant information from an external knowledge base and includes it in the prompt.
A typical workflow looks like this:
- Collect documents from different sources.
- Extract and normalize their content.
- Divide documents into smaller chunks.
- Generate embeddings for each chunk.
- Store embeddings and metadata in OpenSearch.
- Convert user questions into query embeddings.
- Retrieve relevant chunks.
- Send the retrieved context to an LLM for response generation.
The quality of the final answer depends partly on whether the retrieval stage finds the correct information.
Consider a technical document explaining an API endpoint, its authentication requirements, and its error-handling behavior. If these details are separated into unrelated chunks, a search query about authentication might retrieve only a partial explanation.
The model cannot reliably use information that retrieval never provides.
Understanding Common Chunking Strategies
There is no universal chunking configuration for every RAG application. Different document types and retrieval requirements need different approaches.
1. Fixed-Size Chunking
Fixed-size chunking divides text into segments based on a predefined token or character limit.
For example, a document can be divided into chunks of approximately 500 tokens, with a small overlap between neighboring chunks.
Advantages:
- Simple to implement.
- Easy to configure.
- Suitable for relatively uniform documents.
- Provides predictable chunk sizes.
Limitations:
- Can split sentences or related paragraphs.
- May separate headings from their explanations.
- Does not always preserve document structure.
It is a useful baseline for initial RAG implementations.
2. Recursive Chunking
Recursive chunking attempts to split documents using natural boundaries such as paragraphs, sentences, and separators before breaking content into smaller sections.
This approach helps preserve meaningful text relationships.
For example, a document might be divided using the following order:
- Document sections
- Paragraphs
- Sentences
- Smaller text segments when necessary
It is particularly useful when processing documentation, knowledge articles, and technical guides.
3. Semantic Chunking
Semantic chunking groups content according to changes in meaning rather than relying entirely on fixed boundaries.
For instance, a product document might contain separate discussions about pricing, security, deployment, and troubleshooting.
Semantic chunking attempts to keep related information together.
This approach can improve contextual relevance, although it may require additional processing and careful evaluation.
4. Hierarchical Chunking
Hierarchical chunking creates smaller child chunks connected to larger parent sections.
The retrieval system can identify a precise child passage and then provide its parent context to the language model.
This can help balance retrieval precision with sufficient context for answer generation.
Designing a Better Chunking Pipeline with Amazon OpenSearch
Amazon OpenSearch Service provides vector search capabilities that can support RAG applications.
A practical ingestion architecture can follow this pattern:
Document Sources → Data Processing → Text Extraction → Chunking → Embedding Generation → OpenSearch Indexing
The query workflow follows a separate path:
User Query → Query Embedding → OpenSearch Retrieval → Context Construction → LLM Response
Keeping ingestion and query processing separate makes the architecture easier to maintain and optimize.
Step 1: Clean and Normalize Source Documents
Before creating chunks, prepare the source data.
Remove:
- Duplicate content.
- Unnecessary navigation text.
- Repeated headers and footers.
- Broken formatting.
- Irrelevant metadata.
Preserve meaningful headings, paragraph boundaries, tables, and document identifiers wherever possible.
Poor source extraction can damage retrieval quality before chunking even begins.
Step 2: Configure Chunk Size and Overlap
Chunk size determines how much information each embedding represents. Overlap helps preserve context across neighboring chunks.
For example, consider these initial experimental configurations:
Configuration | Chunk size | Overlap |
|---|---|---|
A | 300 tokens | 30 tokens |
B | 500 tokens | 75 tokens |
C | 800 tokens | 100 tokens |
These are illustrative starting points, not universally optimal settings.
Smaller chunks may improve precision but lose important context. Larger chunks may retain more information but introduce unrelated content into search results.
The best configuration should be selected using representative queries and retrieval measurements.
Step 3: Generate Embeddings
After chunking, convert each text segment into a vector representation using an embedding model.
For an AWS-based implementation, Amazon Bedrock provides embedding models that can be integrated into the ingestion workflow.
Each indexed record should retain:
- Original chunk text.
- Embedding vector.
- Document identifier.
- Section or heading.
- Source information.
- Access-control metadata where required.
Keeping this information together makes retrieval, filtering, and debugging easier.
Step 4: Store Vectors in OpenSearch
Create a vector index with a mapping that supports the embedding dimensions and vector-search method used by your application.
A simplified OpenSearch mapping example:
PUT rag-chunks
{
"settings": {
"index": {
"knn": true
}
},
"mappings": {
"properties": {
"content": {
"type": "text"
},
"embedding": {
"type": "knn_vector",
"dimension": 1024,
"method": {
"name": "hnsw",
"space_type": "cosinesimil",
"engine": "faiss"
}
},
"document_id": {
"type": "keyword"
},
"section": {
"type": "keyword"
}
}
}
}
The dimension must match the embedding model's output. The example assumes a compatible OpenSearch version and vector engine configuration.
Step 5: Retrieve Relevant Chunks
When a user submits a question, generate its embedding using the same embedding model used for document indexing.
Then perform vector search against OpenSearch.
A simplified query example:
GET rag-chunks/_search
{
"size": 5,
"query": {
"knn": {
"embedding": {
"vector": [0.12, 0.24, 0.36],
"k": 5
}
}
}
}
The vector values above are placeholders. In an actual implementation, provide the complete vector returned by the embedding model.
The application can then retrieve the original text from the matching records and construct the context for the LLM.
How to Evaluate Retrieval Quality
Changing chunk sizes without measuring results can create new problems.
I recommend creating a small evaluation dataset containing realistic questions and the source passages expected to answer them.
Useful evaluation metrics include:
Recall@K: Measures whether relevant chunks appear within the top K retrieved results.
Precision@K: Measures how many retrieved results are actually relevant.
Mean Reciprocal Rank (MRR): Evaluates how highly the first relevant result appears.
Context Relevance: Checks whether retrieved passages are useful for answering the question.
You can also compare the final generated answers for factual accuracy and completeness.
For example, run the same questions against three chunking configurations and compare their retrieval results. This gives you evidence about which approach works best for your documents.
Additional Improvements Worth Testing
Chunking is only one part of retrieval optimization.
Consider these improvements:
- Hybrid search: Combine vector similarity with keyword matching for technical terms, identifiers, and exact phrases.
- Metadata filtering: Restrict retrieval using document type, department, version, or access permissions.
- Reranking: Reorder retrieved candidates using a relevance model before sending them to the LLM.
- Parent-child retrieval: Retrieve a precise passage while preserving its larger contextual section.
- Document versioning: Prevent outdated information from appearing alongside current content.
These techniques can work together to improve an enterprise RAG architecture.
Final Thoughts
Improving OpenSearch retrieval quality requires more than increasing the number of retrieved documents or switching to a different language model.
The way information is extracted, organized, divided, embedded, and indexed plays an important role in the overall performance of a RAG application.
A practical approach is to begin with fixed-size chunking, establish a baseline, test recursive or semantic alternatives, and evaluate each configuration using real questions.
For developers working on AI data engineering RAG systems, the main lesson is to treat document preparation as an essential part of the retrieval architecture rather than a minor preprocessing task.
Better retrieval starts with better data organization.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article