文档 1.7 版本已不再积极维护,你当前浏览的是一份归档快照。
最新文档请参阅 最新版本。
HugeGraph Python 客户端快速入门
hugegraph-python-client 是 HugeGraph 的 Python SDK,可管理 Schema、读写图数据并执行 Gremlin 查询。HugeGraph-LLM 和 HugeGraph-ML 也使用这个客户端。
环境要求
- Python 3.9 或更高版本
- 可访问的 HugeGraph Server
uv(推荐)或 pip
安装
PyPI 上的包名目前是 hugegraph-python:
1uv pip install hugegraph-python
2# 也可以使用 pip install hugegraph-python
如需使用仓库中的最新代码,请从 HugeGraph-AI 仓库根目录同步 workspace:
1git clone https://github.com/apache/hugegraph-ai.git
2cd hugegraph-ai
3uv sync
4source .venv/bin/activate
连接并写入数据
1from pyhugegraph.client import PyHugeClient
2
3client = PyHugeClient(
4 "127.0.0.1:8080",
5 graph="hugegraph",
6 user="admin",
7 pwd="admin",
8 graphspace="DEFAULT",
9)
10
11schema = client.schema()
12schema.propertyKey("name").asText().ifNotExist().create()
13schema.propertyKey("birthDate").asText().ifNotExist().create()
14schema.vertexLabel("Person").properties("name", "birthDate") \
15 .usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
16schema.vertexLabel("Movie").properties("name") \
17 .usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
18schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie") \
19 .ifNotExist().create()
20
21graph = client.graph()
22person = graph.addVertex(
23 "Person", {"name": "Al Pacino", "birthDate": "1940-04-25"}
24)
25movie = graph.addVertex("Movie", {"name": "The Godfather"})
26edge = graph.addEdge("ActedIn", person.id, movie.id, {})
27
28print(graph.getVertexById(person.id))
29print(graph.getEdgeById(edge.id))
30graph.close()
如果 HugeGraph 没有启用 GraphSpace,可以省略 graphspace。启用后请传入实际空间名;默认空间通常是 DEFAULT。
常用操作
查询 Schema
1schema = client.schema()
2print(schema.getPropertyKeys())
3print(schema.getVertexLabels())
4print(schema.getEdgeLabels())
5print(schema.getIndexLabels())
更新和删除图数据
图接口直接接收对象属性字典:
1graph = client.graph()
2graph.appendVertex(person.id, {"birthDate": "1940-04-25"})
3graph.removeEdgeById(edge.id)
4graph.removeVertexById(person.id)
5graph.close()
执行 Gremlin
1gremlin = client.gremlin()
2result = gremlin.exec("g.V().limit(5)")
3print(result)
接口参数会随 HugeGraph REST API 版本变化。遇到不兼容时,先核对当前 Server 的 REST API 文档与客户端测试用例。
开发检查
在 HugeGraph-AI 仓库根目录运行格式与静态检查:
1./style/code_format_and_analysis.sh
源码与测试位于 hugegraph-python-client/src/pyhugegraph/ 和 hugegraph-python-client/src/tests/。