Build Knowledge Graph-powered AI Agents For Your Use Case | Databases for AI
Learn when graph databases belong in your AI stack, how to implement knowledge graphs for security, fraud, and customer intelligence use cases on Amazon Neptune, and how to make them accessible through AI agents — no graph query expertise required. This post is part of the Databases for AI series.
Building Knowledge Graph-Powered AI Agents: When Your Data Problem Is About Connections, Not Similarity
Hosts: Emily Bayuk, Melissa Kwok
Original Livestream:
The Problem
You've built a RAG pipeline. Vector embeddings are stored, semantic search is working, and your AI system handles questions like "What's our refund policy?" without breaking a sweat.
Then someone asks: "How will our sales prospects be affected by the new product launch?"
Your system returns documents about product launches. Documents about sales prospects. Maybe some tangentially relevant marketing copy. What it can't do is connect the dots — trace the relationships between prospects, their parent companies, past purchasing behavior, and the products they've evaluated.
This isn't a retrieval quality problem. It's a data model problem.
Standard vector search generates embeddings, stores them in a vector database, and surfaces results based on semantic similarity. This works when the question maps to a chunk of text somewhere in your corpus. It breaks down when the answer lives in the connections between entities.
Approach | Strength | Limitation |
|---|---|---|
Vector / Semantic Search | Finds conceptually similar content across unstructured text | Cannot traverse relationships between entities; answers live
"in" documents |
SQL / Relational Queries | Structured lookups across normalized tables | Multi-hop joins become expensive and hard to write;
relationship depth is limited |
Graph Traversal | Natively models and queries relationships across connected
entities | Requires graph-shaped data; not ideal for unstructured text
similarity |
Ask 'Which accounts share suspicious patterns?' and semantic search returns results about fraud detection. What you actually need: connections between accounts, transactions, phone numbers, and addresses. If your hardest questions involve words like "path," "connected to," "related," "affects," or "influences," you're dealing with a graph problem.
The Core Concepts (What You Need to Know)
What is a knowledge graph, and why does it matter for AI?
A knowledge graph is a data structure that represents entities as nodes and the relationships between them as edges, making it possible to query and traverse connections directly. Unlike tabular data, where relationships are implicit in foreign keys and JOIN operations, a knowledge graph makes relationships first-class citizens.
This matters for AI because many real-world questions require multi-hop reasoning — following chains of relationships to arrive at an answer. A knowledge graph gives your AI system a structured map of how things connect.
How does graph traversal differ from semantic search?
Semantic search finds content that is conceptually similar to your query. Graph traversal finds entities that are structurally connected to a starting point, regardless of textual similarity.
Dimension | Semantic / Vector Search | Graph Traversal |
|---|---|---|
What it finds | Text chunks with similar meaning | Entities connected by typed relationships |
How it works | Cosine similarity between embedding vectors | Path traversal across nodes and edges |
Best for | "What documents discuss X?" | "How does A connect to B?" |
Breaks down when | The answer is in relationships, not text | The data is unstructured with no clear entities |
Example | "Find policies about data retention" | "What resources can this compromised IAM role
reach?" |
When should you combine graph and vector approaches?
Use them together when your use case requires both contextual understanding (what a document says) and structural reasoning (how entities relate). This hybrid pattern — sometimes called GraphRAG — extracts entities and relationships from documents into a knowledge graph, then uses graph traversal to provide richer context for LLM-based answers.
What are graph algorithms, and when do they matter?
Graph algorithms are computational methods that analyze the structure of a graph to reveal patterns invisible at the individual node level. Two categories come up repeatedly in practical use cases:
Algorithm Category | Examples | What It Reveals | Use Case |
|---|---|---|---|
Clustering | Connected Components, Label Propagation, Louvain | Groups of highly connected entities | Fraud ring detection, community identification |
Centrality | PageRank, Degree Centrality, Closeness Centrality | Relative importance or influence of a node | Identifying key accounts, critical infrastructure nodes |
These algorithms let you ask structural questions at scale — "Which node is most connected?" or "Which clusters of nodes behave anomalously?" — without manually writing traversal queries for every pattern.
What We're Building (Architecture & Implementation)
6a. Architecture Overview
The core pattern here is a knowledge graph backed by Amazon Neptune, made accessible through an AI agent that translates natural language into graph queries.
Layer | Service | Purpose |
|---|---|---|
Graph Database | Amazon Neptune | Stores and queries the knowledge graph; supports property
graph (openCypher/Gremlin) and RDF (SPARQL) |
AI Agent | Strands Agent | Interprets natural language, generates graph queries, formats
results |
Agent-to-Graph Bridge | Neptune MCP Server | Provides the AI agent with tools to query and explore the
graph database |
Development & Exploration | graph-notebook (open source) | Jupyter-based environment for prototyping queries and
visualizing results |
Data Ingestion | Streaming/batch pipelines (Amazon Kinesis, AWS Glue, etc.) | Transforms source data into graph operations |
Architecture Diagram

Data flow from question to answer:
1. User asks a natural language question (e.g., "Which phone number has been used by the most accounts?")
2. The AI agent interprets the intent and determines the graph traversal pattern needed
3. The agent generates the corresponding graph query (openCypher or Gremlin), using the graph schema to ensure logical correctness
4. The query executes against the knowledge graph in Amazon Neptune
5. The agent formats results for the user — natural language summary, table, or graph visualization depending on the question type
6b. Implementation Patterns
Pattern 1: Structured Data Ingestion (Streaming/Batch)
For use cases like security graphs and fraud detection, where source data lives in operational databases and event streams.
What it does: Captures data changes from source systems and maintains a synchronized knowledge graph.
When to use it: When your graph data originates from structured sources — relational databases, event logs, transaction systems.
How it works:
- Capture events from source databases (creates, updates, deletes)
- Queue events in a stream (e.g., Amazon Kinesis, Amazon MSK)
- Transform events into graph operations that add or update nodes and relationships
- Apply corresponding graph queries to maintain the knowledge graph
-- Example: Adding a transaction relationship between accounts in openCypherMERGE (a1:Account {id: $sourceAccountId})MERGE (a2:Account {id: $targetAccountId})CREATE (a1)-[:TRANSFERRED_TO {amount: $amount, timestamp: $timestamp}]->(a2)What to watch out for: Event ordering matters. Out-of-order events can create inconsistent graph state. Design your pipeline to handle idempotency and eventual consistency.
Pattern 2: Unstructured Data Ingestion (GraphRAG)
For use cases where entities and relationships need to be extracted from documents.
What it does: Processes documents to extract entities and relationships, then populates the knowledge graph.
When to use it: When your source data is unstructured — reports, emails, support tickets, contracts.
How it works:
1. Implement document versioning to handle updates and replacements
2. Extract entities and relationships from documents during processing (using an LLM or NLP pipeline)
3. Use frameworks that support incremental graph updates as documents change
4. Maintain connections between source documents and extracted graph entities
What to watch out for: Entity resolution is hard. The same entity may appear with different names across documents ("AWS" vs. "Amazon Web Services" vs. "Amazon"). Build de-duplication into your extraction pipeline.
Pattern 3: AI Agent with MCP for Natural Language Graph Access
What it does: Makes the knowledge graph queryable by non-technical users through natural language.
When to use it: When your graph contains valuable intelligence but your users can't (or shouldn't have to) write openCypher or Gremlin.
How it works:
2. Configure the AI agent with the graph schema so it generates valid queries
3. The agent translates natural language → graph query → executes → formats response
4. For "show me" questions, the agent returns graph visualizations; for analytical questions, natural language summaries
User: "Show me the account with the most transactions"
Agent internally generates:
MATCH (a:Account)-[t:TRANSFERRED_TO]-() RETURN a.id, count(t) AS txCount ORDER BY txCount DESC LIMIT 1Agent responds: "Account A-4471 has the most transactions with 847 transfers..."
What to watch out for: The agent needs the graph schema to generate correct queries. Without it, queries may reference non-existent node labels or relationship types. Also, complex multi-step traversals may require chain-of-thought prompting to decompose correctly
Pattern | Flow | Best For | Example Use Case |
|---|---|---|---|
Structured Ingestion | Source DB → Stream → Transform → Neptune | Operational data with clear entity models | Security posture graph from AWS Config data |
Unstructured Ingestion (GraphRAG) | Documents → Entity Extraction → Neptune | Text-heavy sources requiring relationship mining | Customer intelligence from support tickets and contracts |
AI Agent + MCP | User → Agent → MCP Server → Neptune → Response | Making existing graphs accessible to non-technical users | Fraud investigators querying account networks |
6c. Workflow: AI Agent Query Pipeline

1. User asks a question in natural language
2. Agent interprets intent — determines whether this is a traversal, aggregation, or visualization request
3. Agent retrieves graph schema — uses the MCP server to understand available node labels, relationship types, and properties
4. Agent generates query — constructs an openCypher or Gremlin query that answers the question
5. Query executes against Neptune — the MCP server handles the connection and execution
6. Agent formats results — tables for aggregations, visualizations for "show me" requests, natural language for explanations
7. User drills deeper — clicks on visualization elements or asks follow-up questions; agent generates additional queries
Practical Examples
Example 1: Security Incident Response — Tracing the Blast Radius of a Compromised IAM Role
Scenario: An IAM role's credentials have been compromised. You need to understand the potential blast radius — every resource the attacker could reach through permission chains.
Approach: Model AWS resources as nodes and permissions/access relationships as edges in a knowledge graph. Use graph traversal to trace all reachable paths from the compromised role.
Implementation:
-- Trace all resources reachable from a compromised IAM role (up to 5 hops)MATCH path = (role:IAMRole {id: 'compromised-role-arn'})-[:CAN_ASSUME|HAS_POLICY|CAN_ACCESS*1..5]->(resource)RETURN pathThis query traverses from the compromised role through assumption chains, policy attachments, and access permissions up to 5 hops deep. Each hop represents a potential lateral movement step.
Graph Visualization of IAM role's blast radius

A compromised AWS IAM role serves as the entry point for attackers to conduct lateral movement and resource access through a multi-layered permission graph. The attack path radiates outward from the compromised role through three permission layers: first, the attacker can directly assume other IAM roles or leverage attached policies; second, these policies grant access to AWS resources like S3 buckets (data exfiltration), RDS instances (database exposure), and Lambda functions (code execution); and third, multi-hop chains enable deeper access by assuming progressively more privileged roles (e.g., Compromised IAM role → AdminRole → S3FullAccess policy → S3 bucket), creating complex lateral movement paths that can reach sensitive resources not directly accessible from the initial compromise point.
Result: Instead of manually checking IAM policies and tracing permission chains across the AWS console, you get a complete map of the blast radius in seconds. You can immediately prioritize remediation: revoke access to the most sensitive resources first, then work outward.
A compromised IAM role → the EC2 instances it can access → the S3 buckets those instances can read. That's a graph traversal problem, not a semantic search problem. Example 2: Fraud Detection — Uncovering Coordinated Fraud Rings
Scenario: You're a fraud investigator. Individual flagged transactions look suspicious in isolation, but you suspect coordinated activity across multiple accounts.
Approach: Model accounts, addresses, phone numbers, email addresses, and transactions as nodes. Connect them through shared attributes. Use clustering algorithms to find densely connected groups.
Implementation:
-- Find accounts sharing an unusually high number of attributesMATCH (a1:Account)-[:HAS_ADDRESS]->(addr:Address)<-[:HAS_ADDRESS]-(a2:Account)WHERE a1 <> a2WITH addr, collect(DISTINCT a1) + collect(DISTINCT a2) AS accountsWHERE size(accounts) > 5RETURN addr.value AS sharedAddress, size(accounts) AS accountCount, accountsORDER BY accountCount DESCThen apply graph algorithms for deeper analysis:
· Connected Components to identify clusters of accounts linked through shared attributes
· PageRank to find the most significant nodes in each cluster (the "hub" accounts)
· Louvain to detect community structures that may represent organized rings
Here is an example of a fraud ring data representation via graph where network of accounts appears as nodes and shared attributes create connecting edges(lines). Fraud rings immediately emerge as dense clusters—groups of accounts tightly interconnected through multiple shared attributes.

When we store this data in a relational database, it appears as rows and columns showing individual connections between accounts and shared attributes (phone numbers, addresses, emails). Identifying coordinated fraud patterns requires manually scanning multiple rows to spot accounts sharing the same contact details.

Result: A single shared address between two accounts is noise. Ten accounts sharing the same address, each with different email addresses and phone numbers, conducting identical transaction patterns — that cluster is immediately visible in a graph visualization and trivially detectable with clustering algorithms. Fraud investigators get a starting point for investigation instead of sifting through isolated flags.
What We Learned / Key Takeaways
Not every connected-data problem needs a graph database. Before reaching for Neptune, validate two things: (1) you have highly connected data with many-to-many relationships, and (2) your questions require traversing connections, not just filtering rows. If your entities connect to other entities that connect to still more entities, and your questions involve paths through that web, you have a graph use case. If you're filtering and aggregating on single-table attributes, a relational database is probably fine.
Graph query languages are the real adoption bottleneck — AI agents fix this. The technical value of a knowledge graph is often clear, but getting business users to write openCypher or Gremlin is unrealistic. The Model Context Protocol (MCP) pattern — where an AI agent uses an MCP server to translate natural language into graph queries — removes this bottleneck entirely. Users interact conversationally; the agent handles the query generation.
Visualization makes graph data dramatically more actionable. Suspicious clusters appear as densely connected regions. Attack paths appear as literal paths through your infrastructure. Customer relationships map as organizational networks. Patterns that are invisible in tabular format become obvious in a graph layout. If you're building a graph-powered system, invest in the visualization layer — it's what turns data into decisions.
Start small: a few hundred nodes are enough to validate. You don't need to model your entire data estate to prove a graph use case works. Pick a single domain, model a representative subset, and validate that your key questions are answerable through graph traversal. Scale up once the approach is proven.
Whether you're investigating security incidents, detecting fraud, or navigating complex customer relationships, graph-powered AI agents provide the contextual intelligence that pure semantic search cannot deliver. The hybrid approach (vector + graph) is often the right answer. Pure semantic search fails at relationship questions. Pure graph fails at unstructured text similarity. For many production systems, you'll want both — vector search for "find me relevant documents" and graph traversal for "show me how these entities connect." GraphRAG is the emerging pattern that combines them.
Resources & Links
- Amazon Neptune: https://aws.amazon.com/neptune/ — Managed graph database service supporting property graphs (openCypher/Gremlin) and RDF (SPARQL)
- Neptune MCP Server: https://awslabs.github.io/mcp/servers/amazon-neptune-mcp-server — Model Context Protocol server for connecting AI agents to Neptune
- graph-notebook (open source): https://github.com/aws/graph-notebook — Jupyter notebook extension for graph query development and visualization; works with Neptune, Blazegraph, JanusGraph, and Neo4j
- Amazon Bedrock: https://aws.amazon.com/bedrock/ — Managed foundation model service for building AI agents
- Model Context Protocol (MCP): https://modelcontextprotocol.io/docs/getting-started/intro — Open protocol for connecting AI agents to external tools and data sources
- Build Knowledge Graph-powered AI Agents For Your Use case: https://medium.com/@kwokmeli/build-knowledge-graph-powered-ai-agents-for-your-use-case-a7925cd3bacc — Companion article covering how to build AI agents that query knowledge graphs on Amazon Neptune using the Model Context Protocol, with practical examples in security and fraud detection
- openCypher Query Language: https://opencypher.org/ — Declarative graph query language supported by Neptune
- Wiz (Cloud Security Platform): https://aws.amazon.com/blogs/database/the-world-is-a-graph-how-wiz-reimagines-cloud-security-using-a-graph-in-amazon-neptune/ — Referenced example of graph-based cloud security posture management
Call to Action
Here's how to get started in the next 15 minutes:
1. Sketch your graph model. Pick your most relationship-heavy analytical problem. Write down the entities (nodes) and the connections between them (edges). If you see a web of relationships, you've found your first graph use case.
2. Spin up a Neptune notebook. Install the graph-notebook project in a Jupyter environment. Load a sample dataset and run your first openCypher queries to validate your model.
3. Connect an AI agent. Deploy the Neptune MCP server and configure a Strands agent to query your graph. Start with 3-5 common questions your users would ask.
4. Explore the Databases for AI series on Builder Center for more patterns combining graph, vector, and relational databases in AI architectures.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article