
Level Up Your Match Analytics: Querying Your Knowledge Base with Amazon Bedrock
Learn how to query your Amazon Bedrock Knowledge Base using both the AWS Management Console and Lambda functions!
Welcome to Day 4 of Challenge #2 ! Today you'll learn how to query your Amazon Bedrock Knowledge Base using both the AWS Management Console and Lambda functions. Think of this as your guide to turning raw match statistics into actionable insights - perfect for analyzing champion performance, and understanding meta trends. In about 60 minutes, you'll learn how to make console-based queries and programmatic access through Lambda functions. We're not just running basic searches - we're building a comprehensive system that can answer complex questions about match patterns, player performance, and game statistics.
What You Will Accomplish Today
✅ Set up and test your Knowledge Base via AWS Management Console
✅ Crafting effective RAG queries
✅ Build Lambda functions for programmatic Knowledge Base access
✅ Implement proper error handling and security best practices
✅ Create automated match analysis workflows
✅ Test your system with real Riot API match data
✅ Deploy production-ready query solutions
What You Will Need
💻 Your AWS account with appropriate permissions
🎮 Knowledge Base containing Riot API match data
⏰ About 60 minutes
🔍 Basic understanding of RAG concepts
🐍 Python knowledge for Lambda functions
Step 1: Verify your Knowledge Base Status 🧠
In our previous challenge, you learned how to create a RAG Knowledge Base and connected an S3 bucket as your data source. Let’s verify the status of the Knowledge Base you created previously to get started.
- Navigate to Amazon Bedrock Console - Go to the AWS Management Console and search for "Bedrock"
- Access Knowledge Bases - In the left sidebar, click "Orchestration" → "Knowledge bases"
- Locate Your Match Data KB - Find your knowledge base (likely named something like "riot-match-analytics" or "lol-statistics-kb")
- Check Status - Ensure status shows "Active" and data source shows "Ready"
Important: If your Knowledge Base shows "Creating" or "Failed", you'll need to wait or troubleshoot before proceeding. A properly configured KB is essential for accurate match analysis.
UNDERSTANDING YOUR DATA STRUCTURE
Your Knowledge Base likely contains:
- Match Details: Game duration, mode, patch version, queue type
- Champion Performance: KDA ratios, damage dealt, CS scores, item builds
- Team Statistics: Objectives taken, vision scores, gold differentials
- Player Metrics: Individual performance across multiple matches
- Meta Analysis: Win rates by champion, role, and item combinations
This structured approach ensures your queries can extract meaningful insights rather than just raw statistics.
Step 2: Creating Console-Based Queries 🎯
Let's start with the AWS Management Console to understand how Knowledge Base queries work before automating them.
ACCESS THE TEST INTERFACE
- Open Your Knowledge Base - Click on your Knowledge Base name from the list
- Find Test Section - Look for "Test knowledge base" panel on the right side of the screen
- Select Foundation Model - Click “Select model” button and choose from a list of model providers and select your preferred inference profiles.
- Note: If the model you are wanting to select is greyed-out, you will need to request model access.
- Configure Settings - Set "Number of results" to 5-10 for comprehensive responses
CRAFT YOUR FIRST QUERY
Start with a simple but specific question about your match data:
Example Query: "What is the average KDA ratio for Jinx players in ranked games during patch 13.21?"
Why This Works:
- Specific champion (Jinx)
- Clear metric (KDA ratio)
- Defined context (ranked games, specific patch)
- Measurable outcome (average)
ADVANCED QUERY TECHNIQUES
PATTERN ANALYSIS QUERIES
1
"Show me the most successful item builds for ADC champions with win rates above 55% in Diamond+ games"COMPARATIVE ANALYSIS
1
"Compare the performance of tank supports versus enchanter supports in terms of vision score and team fight participation"META TREND IDENTIFICATION
1
"Which champions have seen the biggest increase in pick rate between patches 13.20 and 13.21, and what might be driving these changes?"PERFORMANCE CORRELATION
1
"What correlation exists between early game CS differential and match outcome for mid lane champions?"INTERPRETING RESULTS
Your Knowledge Base will return:
- Relevant Context: Specific match data that informed the answer
- Statistical Analysis: Calculated metrics and trends
- Source Attribution: Which matches or data points were used
- Confidence Indicators: How certain the model is about the response
Pro Tip: If results seem incomplete, try rephrasing your query with more specific parameters or breaking complex questions into smaller parts.
Step 3: Building Your Query Lambda Function ⚡
Time to automate your Knowledge Base queries with Lambda functions. This is where the real power comes in - programmatic access that can scale to analyze thousands of matches.
CREATE THE LAMBDA FUNCTION
- Navigate to Lambda Console - Search for "Lambda" in AWS Console
- Create Function:
- Click "Create function"
- Choose "Author from scratch"
- Function name:
bedrock-kb-query-function - Runtime: Python 3.13
- Architecture: x86_64
- Execution role: "Create a new role with basic Lambda permissions"
CONFIGURE PERMISSIONS
Your Lambda function needs specific permissions to access Bedrock and your Knowledge Base:
Required IAM Policies:
AmazonBedrockFullAccess(or custom policy with bedrock:Retrieve and bedrock:RetrieveAndGenerate)AWSLambdaBasicExecutionRole(for CloudWatch logging)
Add Permissions:
- Go to IAM Console → Roles
- Find your Lambda execution role (created automatically)
- In the “Permissions” tab, click "Add permissions" → "Attach policies"
- Search for and attach the required policies
IMPLEMENT THE QUERY CODE
Replace the default Lambda code with this comprehensive solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import json
import boto3
import logging
import os
from typing import Dict, List, Any, Optional
from botocore.exceptions import ClientError
# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Initialize Bedrock client
bedrock_agent_runtime = boto3.client('bedrock-agent-runtime')
# Configuration - Replace with your actual Knowledge Base ID
KNOWLEDGE_BASE_ID = os.environ['KNOWLEDGE_BASE_ID'] # e.g., "ABCD1234EFGH"
model_id = os.environ['YOUR_MODEL_ID'] # e.g., "anthropic.claude-3-sonnet-20240229-v1:0"
MAX_RESULTS = 10
def lambda_handler(event: Dict[str, Any], context) -> Dict[str, Any]:
""" Main Lambda handler for querying Bedrock Knowledge Base
Expected event structure:
{
"query": "Your question about match data",
"max_results": 5, # optional
}
"""
try:
# Extract query parameters
query = event.get('query') # e.g., "What is the average KDA ratio for Jinx players in ranked games during patch 13.21?"
if not query:
return create_error_response(400, "Query parameter is required")
max_results = event.get('max_results', MAX_RESULTS)
logger.info(f"Processing query: {query[:100]}...")
# Query the Knowledge Base
response = query_knowledge_base(query, max_results, model_id)
return create_success_response(response)
except ClientError as e:
logger.error(f"AWS Client Error: {str(e)}")
return create_error_response(500, f"AWS service error: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return create_error_response(500, f"Internal error: {str(e)}")
def query_knowledge_base(query: str, max_results: int, model_id: str) -> Dict[str, Any]:
""" Query the Bedrock Knowledge Base using RetrieveAndGenerate API """
try:
# Use RetrieveAndGenerate for complete RAG workflow
response = bedrock_agent_runtime.retrieve_and_generate(
input={
'text': query },
retrieveAndGenerateConfiguration={
'type': 'KNOWLEDGE_BASE',
'knowledgeBaseConfiguration': {
'knowledgeBaseId': KNOWLEDGE_BASE_ID,
'modelArn': model_id,
'retrievalConfiguration': {
'vectorSearchConfiguration': {
'numberOfResults': max_results }
}
}
}
)
# Extract and structure the response
result = {
'answer': response.get('output', {}).get('text', ''),
'source_documents': [],
'session_id': response.get('sessionId', ''),
'citations': response.get('citations', [])
}
# Process citations to extract source information
for citation in response.get('citations', []):
for reference in citation.get('retrievedReferences', []):
source_doc = {
'content': reference.get('content', {}).get('text', ''),
'location': reference.get('location', {}),
'metadata': reference.get('metadata', {})
}
result['source_documents'].append(source_doc)
return result
except ClientError as e:
logger.error(f"Bedrock API error: {str(e)}")
raise
except Exception as e:
logger.error(f"Knowledge Base query error: {str(e)}")
raise
def create_success_response(data: Dict[str, Any]) -> Dict[str, Any]:
"""Create a successful API response"""
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'success': True,
'data': data,
'timestamp': context.aws_request_id if 'context' in globals() else None
})
}
def create_error_response(status_code: int, message: str) -> Dict[str, Any]:
"""Create an error API response"""
return {
'statusCode': status_code,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'success': False,
'error': message,
'timestamp': context.aws_request_id if 'context' in globals() else None
})
}DEPLOY AND CONFIGURE
As best practices, you should not hardcode your credentials into your function, but rather add environment variables.
- Update Environment Variables:
- Go to Configuration → Environment variables
- Click “Edit” and Add
KNOWLEDGE_BASE_IDwith your KB ID- You can find your Knowledge Base ID by clicking on your Knowledge Base from the drop down menu in Bedrock.
- Add
YOUR_MODEL_IDwith the Foundational Model of your choice.- Refer to this documentation to find the model ID. Be sure to verify that your region is supported.
- Increase Timeout:
- Go to Configuration → General configuration
- Set timeout to 5 minutes (Knowledge Base queries can take time)
- Set memory to 512 MB for optimal performance
- Deploy the Function:
- Click "Deploy" to save your changes
- Wait for the "Changes deployed" confirmation
Step 4: Testing Your Lambda Function 🧪
Let's verify everything works before building more complex workflows.
CREATE TEST EVENTS
- Configure Test Event:
- Click the "Test" tab
- Click "Create new test event"
- Event name:
MatchAnalysisTest - Replace the default JSON with:
- Replace the
querywith a simple but specific question about your match data.
- Replace the
1
2
3
4
{
"query": "What are the most successful item builds for Jinx in ranked games, and what is her average KDA with these builds?",
"max_results": 5,
}- Run the Test:
- Click the orange "Test" button
- Wait 30-60 seconds for execution (Knowledge Base queries take time)
- Check the "Execution result" section
VERIFY SUCCESSFUL EXECUTION
Success Indicators:
- Status shows "succeeded" in green
- Response contains structured match analysis
- Source documents show relevant match data
- No error messages in logs
Sample Successful Response:
1
2
3
4
5
6
7
8
9
10
11
{
"statusCode": 200,
"body": {
"success": true,
"data": {
"answer": "Based on the match data analysis, Jinx players achieve highest success with the Kraken Slayer → Phantom Dancer → Infinity Edge build path, showing a 64% win rate with an average KDA of 8.2/4.1/12.3...",
"source_documents": [...],
"citations": [...]
}
}
}TROUBLESHOOTING COMMON ISSUES
"Knowledge Base not found" Error:
- Verify your Knowledge Base ID is correct
- Ensure the KB is in the same region as your Lambda
- Check that the KB status is "Active"
Permission Denied Errors:
- Verify IAM policies are attached to Lambda execution role
- Ensure Bedrock service permissions include your specific KB
- Check region consistency across all resources
Timeout Errors:
- Increase Lambda timeout to 5 minutes
- Simplify your query to reduce processing time
- Check Knowledge Base data source status
Empty or Irrelevant Results:
- Refine your query to be more specific
- Verify your Knowledge Base contains relevant match data
- Try different model IDs (Claude v3.7 vs v3.5)
Step 5: Configure and Customize Your Queries 🎯
Now that your Lambda function is working, let's explore how to fine-tune your Knowledge Base queries to get the most relevant and useful responses. The techniques listed here can optimize your results - the right configuration can make all the difference between a good result and a great one.
UNDERSTANDING QUERY CONFIGURATION OPTIONS
Amazon Bedrock Knowledge Bases offer several configuration options that control how your queries are processed and how responses are generated.
Key Configuration Areas:
- Retrieval Settings: How many relevant documents to find
- Generation Settings: How the AI model creates responses
- Model Selection: Which foundation model to use
- Response Filtering: What type of content to prioritize
1. RETRIEVAL CONFIGURATION
The retrieval phase determines which documents from your Knowledge Base are most relevant to your query.
Number of Results:
- Default: 5 results
- Range: 1-100 results
- Recommendation: Start with 5-10 for most match analysis queries
- When to increase: Complex questions requiring multiple data points
- When to decrease: Simple, specific questions about individual matches
Example Configuration in Lambda:
1
2
3
4
5
'retrievalConfiguration': {
'vectorSearchConfiguration': {
'numberOfResults': 10 # Adjust based on query complexity
}
}Practical Guidelines:
- Champion performance queries: 5-8 results (focused analysis)
- Meta trend analysis: 10-15 results (broader data needed)
- Specific match details: 3-5 results (precise information)
- Comparative analysis: 8-12 results (multiple data points)
2. MODEL SELECTION AND OPTIMIZATION
Different foundation models excel at different types of analysis. Choose your model based on what you're trying to accomplish.
Available Models:
- Claude v3 Haiku: Faster responses, good for simple queries
- Claude v3 Opus: Most capable for complex analytical tasks
Model Selection Guide:
1
2
3
4
5
# For quick statistics lookups
model_id = "anthropic.claude-3-haiku-20240307-v1:0"
# For complex meta analysis
model_id = "anthropic.claude-3-opus-20240229-v1:0"3. CRAFTING EFFECTIVE QUERIES
The way you phrase your questions dramatically impacts the quality of responses. Here are proven patterns that work well with match data analysis.
Query Structure Best Practices:
1. Be Specific About Context
1
2
❌ "How is Jinx performing?"
✅ "What is Jinx's win rate and average KDA in ranked Solo Queue games during patch 13.21?"2. Define Your Metrics Clearly
1
2
❌ "Show me good ADC champions"
✅ "Which ADC champions have win rates above 52% and pick rates above 5% in Diamond+ ranked games?"3. Specify Time Periods
1
2
❌ "What's the current meta?"
✅ "What are the top 5 most picked champions in each role during the last 30 days of ranked games?"4. Include Rank/Skill Context
1
2
❌ "Best support champions"
✅ "Which support champions have the highest win rates in Gold and Platinum ranked games?"4. TESTING AND ITERATION
Start Simple, Then Expand:
- Begin with basic queries to understand your data
- Gradually add more specific parameters
- Test different phrasings for the same question
- Note which approaches give the most useful responses
Common Refinement Patterns:
- If responses are too broad → Add more specific parameters
- If responses are too narrow → Increase retrieval results or broaden query scope
- If responses lack context → Ask for explanations and reasoning
- If responses are inconsistent → Standardize your query format
Mission Complete: Your RAG Query System is Ready! ✅
✅ Verified “Active” Knowledge Base Status
✅ Successfully Tested queries via AWS Management Console
✅ Configured Lambda Implementation
✅ Testing & Optimization
You've transformed from basic Knowledge Base user to advanced RAG practitioner! Your system now provides:
🎯 Precision Querying: You can extract specific insights from thousands of matches with surgical precision, whether you're analyzing champion performance, meta trends, or build optimization.
⚡ Automated Analysis: Your Lambda functions can process complex queries programmatically, enabling automated reporting, real-time analysis, and integration with other systems.
🔧 Advanced Configuration: You understand how to fine-tune retrieval settings and optimize query performance for different types of analysis.
Next Level: Building Strand Agents with Bedrock Knowledge Bases 🤖
Ready to take your match analysis to the next level? In our next challenge, we'll build intelligent Strand Agents that can conduct autonomous research and analysis using your Knowledge Base as their primary data source.Your RAG query system is the foundation - now we're building the intelligence layer that makes it truly powerful. In the next challenge, you'll create agents that don't just answer questions about your matches, but actively help you understand and improve your gameplay.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article