关于 using-graph-databases
面向开发者的图数据库选型与实现指南,适用于关系和遍历是应用核心的场景,涵盖数据库比较、图建模、查询模式及性能优化。
主要功能
- 01选择图数据库
- 02建模节点与关系
- 03使用 Cypher 查询模式
- 04检查图模式与遍历
- 05优化索引和缓存
适用场景
- 01构建社交关系查询
- 02为 AI/RAG 增加图上下文
- 03创建推荐引擎
- 04检测关联欺诈模式
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ancoleman/ ai-design-components --skill using-graph-databases安装后在 Claude Code 中输入/using-graph-databases确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
outputs.yamlexamples/knowledge-graph/hybrid_vector_graph.pyexamples/social-graph/schema.cypherexamples/social-graph/python-neo4j/main.pyexamples/social-graph/typescript-neo4j/index.tsreferences/arangodb.mdcypher-patterns.mdgraph-modeling.mdneo4j.mdscripts/validate_graph_schema.py详细介绍
图数据库
用途
本技能将指导你为实体间关系至关重要的应用选择和实现图数据库。与通过外键和联接来建模关系的关系型数据库不同,图数据库会将连接原生表示为属性,因此可以高效执行遍历密集型查询。
何时使用本技能
以下情况适合使用图数据库:
- 深层关系遍历(4 跳及以上):“朋友的朋友的朋友”
- 可变或不断演进的关系:架构变更不会破坏现有查询
- 路径查找:最短路径、网络分析、依赖链
- 模式匹配:欺诈检测、推荐引擎、访问控制
以下情况不要使用图数据库:
- 架构固定且联接层次较浅(2~3 张表)→ 使用 PostgreSQL
- 主要进行聚合或分析 → 使用列式数据库
- 仅进行键值查找 → 使用 Redis/DynamoDB
快速决策框架
DATA CHARACTERISTICS?
├── Fixed schema, shallow joins (≤3 hops)
│ └─ PostgreSQL (relational)
│
├── Already on PostgreSQL + simple graphs
│ └─ Apache AGE (PostgreSQL extension)
│
├── Deep traversals (4+ hops) + general purpose
│ └─ Neo4j (battle-tested, largest ecosystem)
│
├── Multi-model (documents + graph)
│ └─ ArangoDB
│
├── AWS-native, serverless
│ └─ Amazon Neptune
│
└── Real-time streaming, in-memory
└─ Memgraph
核心概念
属性图模型
图数据库将数据存储为:
- 节点(顶点):带有标签和属性的实体
- 关系(边):带有属性的有类型连接
- 属性:节点和关系上的键值对
(Person {name: "Alice", age: 28})-[:FRIEND {since: "2020-01-15"}]->(Person {name: "Bob"})
查询语言
| 语言 | 数据库 | 易读性 | 最适用于 |
|---|---|---|---|
| Cypher | Neo4j、Memgraph、AGE | ⭐⭐⭐⭐⭐ 类似 SQL | 通用场景 |
| Gremlin | Neptune、JanusGraph | ⭐⭐⭐ 函数式 | 跨数据库 |
| AQL | ArangoDB | ⭐⭐⭐⭐ 类似 SQL | 多模型场景 |
| SPARQL | Neptune、RDF 存储 | ⭐⭐⭐ W3C 标准 | 语义网 |
常见 Cypher 模式
完整示例请参阅 references/cypher-patterns.md。
模式 1:基本匹配
// Find all users at a company
MATCH (u:User)-[:WORKS_AT]->(c:Company {name: 'Acme Corp'})
RETURN u.name, u.title
模式 2:可变长度路径
// Find friends up to 3 degrees away
MATCH (u:User {name: 'Alice'})-[:FRIEND*1..3]->(friend)
WHERE u <> friend
RETURN DISTINCT friend.name
LIMIT 100
模式 3:最短路径
// Find shortest connection between two users
MATCH path = shortestPath(
(a:User {name: 'Alice'})-[*]-(b:User {name: 'Bob'})
)
RETURN path, length(path) AS distance
模式 4:推荐
// Collaborative filtering: Products liked by similar users
MATCH (u:User {id: $userId})-[:PURCHASED]->(p:Product)<-[:PURCHASED]-(similar)
MATCH (similar)-[:PURCHASED]->(rec:Product)
WHERE NOT exists((u)-[:PURCHASED]->(rec))
RETURN rec.name, count(*) AS score
ORDER BY score DESC
LIMIT 10
模式 5:欺诈检测
// Detect circular money flows
MATCH path = (a:Account)-[:SENT*3..6]->(a)
WHERE all(r IN relationships(path) WHERE r.amount > 1000)
RETURN path, [r IN relationships(path) | r.amount] AS amounts
数据库选择指南
Neo4j(首选推荐)
适用于:通用图应用
优势:
- 最成熟(2007 年),社区规模最大(200 多万名开发者)
- 提供 65 多种图算法(GDS 库):PageRank、Louvain、Dijkstra
- 工具支持最佳:Neo4j Browser、Bloom 可视化
- 全面的 Cypher 支持
安装:
# Python driver
pip install neo4j
# TypeScript driver
npm install neo4j-driver
# Rust driver
cargo add neo4rs
参考:references/neo4j.md
ArangoDB
适用于:多模型应用(文档 + 图)
优势:
- 在一个数据库中存储文档和图
- AQL 将文档查询与图查询相结合
- 支持关系的灵活架构
参考:references/arangodb.md
Apache AGE
适用于:为现有 PostgreSQL 添加图功能
优势:
- 使用图查询扩展 PostgreSQL
- 无需新增基础设施
- 同时查询关系型数据和图数据
参考:实现详情请见 examples/
Amazon Neptune
适用于:原生 AWS、无服务器部署
优势:
- 完全托管,自动扩缩容
- 同时支持 Gremlin 和 SPARQL
- 集成 AWS 生态系统
图数据建模模式
完整模式请参阅 references/graph-modeling.md。
最佳实践 1:将关系视为一等公民
反模式(将关系存储在节点属性中):
// BAD
(:Person {name: 'Alice', friend_ids: ['b123', 'c456']})
模式(显式关系):
// GOOD
(:Person {name: 'Alice'})-[:FRIEND]->(:Person {id: 'b123'})
(:Person {name: 'Alice'})-[:FRIEND]->(:Person {id: 'c456'})
最佳实践 2:使用关系属性存储元数据
// Track interaction details on relationships
(:Person)-[:FRIEND {
since: '2020-01-15',
strength: 0.85,
last_interaction: datetime()
}]->(:Person)
最佳实践 3:限制遍历范围以提升性能
// SLOW: Unbounded traversal
MATCH (a)-[:FRIEND*]->(distant)
RETURN distant
// FAST: Bounded depth with index
MATCH (a)-[:FRIEND*1..4]->(distant)
WHERE distant.active = true
RETURN distant
LIMIT 100
最佳实践 4:避免超级节点
问题:拥有数千条关系的节点会拖慢遍历。
解决方案:使用中间聚合节点
// Instead of: (:User)-[:POSTED]->(:Post) [1M relationships]
// Use time partitioning:
(:User)-[:POSTED_IN]->(:Year {year: 2025})
-[:HAS_MONTH]->(:Month {month: 12})
-[:HAS_POST]->(:Post)
用例示例
社交网络
架构和实现见 examples/social-graph/
主要功能:
- 好友推荐(好友的好友)
- 共同联系人
- 新闻推送生成
- 影响力指标
AI/RAG 知识图谱
集成示例见 examples/knowledge-graph/
主要功能:
- 向量 + 图混合搜索
- 实体关系映射
- 扩展大模型提示词的上下文
- 语义关系遍历
与向量数据库集成:
# Step 1: Vector search in Qdrant/pgvector
vector_results = qdrant.search(collection="concepts", query_vector=embedding)
# Step 2: Expand with graph relationships
concept_ids = [r.id for r in vector_results]
graph_context = neo4j.run("""
MATCH (c:Concept) WHERE c.id IN $ids
MATCH (c)-[:RELATED_TO|IS_A*1..2]-(related)
RETURN c, related, relationships(path)
""", ids=concept_ids)
推荐引擎
示例见 examples/social-graph/
策略:
- 协同过滤:“购买 X 的用户也购买了 Y”
- 基于内容:“与您喜欢的产品相似的产品”
- 基于会话:“最近浏览的商品”
欺诈检测
模式检测示例见 examples/
检测模式:
- 循环资金流
- 多个账户共用设备
- 快速交易链
- 连接模式异常
性能优化
详细优化内容请参阅 references/cypher-patterns.md。
索引
// Single-property index
CREATE INDEX user_email FOR (u:User) ON (u.email)
// Composite index (Neo4j 5.x+)
CREATE INDEX user_name_location FOR (u:User) ON (u.name, u.location)
// Full-text search
CREATE FULLTEXT INDEX product_search FOR (p:Product) ON EACH [p.name, p.description]
缓存开销较大的聚合
// Materialize friend count as property
MATCH (u:User)-[:FRIEND]->(f)
WITH u, count(f) AS friendCount
SET u.friend_count = friendCount
// Query becomes instant
MATCH (u:User) WHERE u.friend_count > 100
RETURN u.name, u.friend_count
扩展策略
| 规模 | 策略 | 实现方式 |
|---|---|---|
| 纵向 | 增加 RAM/CPU | 内存缓存、更大的实例 |
| 横向(读取) | 只读副本 | Neo4j Cluster、ArangoDB Cluster |
| 横向(写入) | 分片 | ArangoDB SmartGraphs、JanusGraph |
| 缓存 | 应用级缓存 | 为高频路径使用 Redis |
语言集成
Python(Neo4j)
完整示例见 examples/social-graph/python-neo4j/
from neo4j import GraphDatabase
class GraphDB:
def __init__(self, uri: str, user: str, password: str):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
def find_friends_of_friends(self, user_id: str, max_depth: int = 2):
query = """
MATCH (u:User {id: $userId})-[:FRIEND*1..$maxDepth]->(fof)
WHERE u <> fof
RETURN DISTINCT fof.id, fof.name
LIMIT 100
"""
with self.driver.session() as session:
result = session.run(query, userId=user_id, maxDepth=max_depth)
return [dict(record) for record in result]
# Usage
db = GraphDB("bolt://localhost:7687", "neo4j", "password")
friends = db.find_friends_of_friends("u123", max_depth=3)
TypeScript(Neo4j)
完整示例见 examples/social-graph/typescript-neo4j/
import neo4j, { Driver } from 'neo4j-driver'
class Neo4jService {
private driver: Driver
constructor(uri: string, username: string, password: string) {
this.driver = neo4j.driver(uri, neo4j.auth.basic(username, password))
}
async findFriendsOfFriends(userId: string, maxDepth: number = 2) {
const session = this.driver.session()
try {
const result = await session.run(
`MATCH (u:User {id: $userId})-[:FRIEND*1..$maxDepth]->(fof)
WHERE u <> fof
RETURN DISTINCT fof.id, fof.name
LIMIT 100`,
{ userId, maxDepth }
)
return result.records.map(r => r.toObject())
} finally {
await session.close()
}
}
}
Go(ArangoDB)
import (
"github.com/arangodb/go-driver"
"github.com/arangodb/go-driver/http"
)
func findFriendsOfFriends(db driver.Database, userId string, maxDepth int) ([]User, error) {
query := `
FOR vertex, edge, path IN 1..@maxDepth OUTBOUND @startVertex GRAPH 'socialGraph'
FILTER vertex._id != @startVertex
RETURN DISTINCT vertex
LIMIT 100
`
cursor, err := db.Query(ctx, query, map[string]interface{}{
"startVertex": userId,
"maxDepth": maxDepth,
})
// Handle results...
}
架构验证
使用 scripts/validate_graph_schema.py 检查:
- 无界遍历(缺少深度限制)
- 经常查询的属性缺少索引
- 超级节点(关系过多的节点)
- 关系属性一致性
运行验证:
python scripts/validate_graph_schema.py --database neo4j://localhost:7687
与其他技能集成
与 databases-vector 集成(混合搜索)
结合向量相似度和图上下文,用于 AI/RAG 应用。
参见 examples/knowledge-graph/
与 search-filter 集成
实现基于关系的查询:“查找与指定用户相隔 3 度以内的所有用户”
与 ai-chat 集成
使用知识图谱通过结构化关系丰富大模型上下文。
与 auth-security 集成(ReBAC)
实现基于关系的访问控制:“用户 X 能否通过关系 Z 访问资源 Y?”
常见架构模式
星型架构(中心与辐射)
(:User)-[:PURCHASED]->(:Product)
(:User)-[:VIEWED]->(:Product)
(:User)-[:RATED]->(:Product)
层次架构(树)
(:CEO)-[:MANAGES]->(:VP)-[:MANAGES]->(:Director)
时序架构(事件序列)
(:Event {timestamp})-[:NEXT]->(:Event {timestamp})
快速开始
- 选择数据库:使用上文的决策框架
- 设计架构:参阅
references/graph-modeling.md - 实现查询:使用
references/cypher-patterns.md中的模式 - 验证:运行
scripts/validate_graph_schema.py - 优化:添加索引、限制遍历范围、缓存聚合结果
延伸阅读
references/neo4j.md- Neo4j 设置、驱动程序、GDS 算法references/arangodb.md- ArangoDB 多模型模式references/cypher-patterns.md- 完整的 Cypher 查询库references/graph-modeling.md- 数据建模最佳实践examples/social-graph/- 完整的社交网络实现examples/knowledge-graph/- 用于 AI/RAG 的向量 + 图混合方案