aws 使用lambda对neptune数据库连接
一、整体架构
Amazon Neptune 是一个托管的图数据库,只能在 VPC 内部访问。
而 Lambda 默认是无网络的,所以要连接 Neptune,必须把 Lambda 放进 VPC。
基本架构:
Lambda (VPC 内) → VPC 子网 → 安全组允许访问 8182 端口 → Neptune 集群
二、配置步骤
1. Neptune 配置
-
Neptune 集群创建后,会有 Writer Endpoint 和 Reader Endpoint,格式如:
your-cluster.cluster-xxxxxxxx.us-east-1.neptune.amazonaws.com:8182 -
确认 Neptune 安全组允许 Lambda 所在安全组访问 TCP 8182 端口。
2. Lambda 配置
-
运行时:Python、Node.js、Java 都可以。
-
VPC 设置:将 Lambda 放入 与 Neptune 相同 VPC 的子网,并绑定正确的安全组。
-
IAM 权限:如果 Lambda 需要从 Secrets Manager 获取 Neptune 的访问凭证,需要
secretsmanager:GetSecretValue权限。
3. 通信方式
Neptune 支持两种主要协议:
-
Gremlin (WebSocket) → 用于属性图
-
SPARQL (HTTP) → 用于 RDF 图
根据你的数据模型选一种即可。
三、代码示例
1. Python (SPARQL REST API)
适合 RDF 数据模型:
import os
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
# 连接信息
NEPTUNE_ENDPOINT = os.environ.get("NEPTUNE_ENDPOINT", "db-neptune-1.cluster-xxxxxx.us-east-1.neptune.amazonaws.com")
NEPTUNE_PORT = os.environ.get("NEPTUNE_PORT", "8182")
def lambda_handler(event, context):
# 创建 Gremlin 连接
url = f"wss://{NEPTUNE_ENDPOINT}:{NEPTUNE_PORT}/gremlin"
conn = DriverRemoteConnection(url, 'g')
g = traversal().withRemote(conn)
try:
# 插入数据顶点和边
# 在图数据库里创建一个顶点(Vertex),标签是 'person'
#给这个顶点添加属性 name=Alice 和 age=30。.next() → 执行这个操作并返回顶点对象(顶点 ID),赋值给变量 v1
v1 = g.addV('person').property('name', 'Alice').property('age', 30).next()
v2 = g.addV('person').property('name', 'Bob').property('age', 25).next()
#找到顶点 v1(Alice)从 Alice 出发创建一条边,边的标签是 'knows'指定边的终点是 v2(Bob)__ 表示匿名子遍历 给边加一个属性 since=2025,表示 Alice 认识 Bob 的年份
g.V(v1).addE('knows').to(__.V(v2)).property('since', 2025).next()
# 查询 Neptune 中顶点数量
count = g.V().count().next()
vertices = g.V().valueMap(True).toList()
print(vertices)
return {"vertex_count": count}
finally:
# 关闭连接
conn.close()
四、关键点总结
-
Lambda 必须在 VPC 内,否则连不上 Neptune。
-
安全组规则要开放
8182。 -
使用 Gremlin (WebSocket) 或 SPARQL (HTTP) 协议连接。
-
如果用 Gremlin,要在 Lambda Layer 中打包依赖。
-
如果用 SPARQL,直接用
requests/axios即可。
更多推荐


所有评论(0)