这是本节的多页打印视图。 .
HugeGraph Client
Java 和 Go Client 位于 HugeGraph Toolchain 仓库,Python Client 位于 HugeGraph-AI 仓库。三者的安装方式和 API 不完全相同,请进入对应页面查看。
1 - HugeGraph-Java-Client
1 HugeGraph-Client 概述
HugeGraph Java Client 将 Java API 转换为 HugeGraph Server 的 REST 请求,支持管理 Schema 和图数据、执行 Gremlin 及调用 Traverser API。详细接口见 Client API,本文给出 Java 项目的接入示例。
其他语言可使用 Go Client 或 HugeGraph-AI 仓库中的 Python Client。
2 环境要求
- JDK 11(当前 CI 使用版本;源码目标版本为 Java 8)
- Maven 3.6+
3 使用流程
使用 HugeGraph-Client 的基本步骤如下:
- 新建Eclipse/ IDEA Maven 项目;
- 在 pom 文件中添加 HugeGraph-Client 依赖;
- 创建类,调用 HugeGraph-Client 接口;
详细使用过程见下节完整示例。
4 完整示例
4.1 新建 Maven 工程
可以选择 Eclipse 或者 Intellij Idea 创建工程:
4.2 添加 hugegraph-client 依赖
添加 hugegraph-client 依赖
1
2<dependencies>
3 <dependency>
4 <groupId>org.apache.hugegraph</groupId>
5 <artifactId>hugegraph-client</artifactId>
6 <!-- 请按下载页选择已发布版本 -->
7 <version>1.7.0</version>
8 </dependency>
9</dependencies>Client 与 Server 的开发版本可能不同。升级前应按对应发布说明核对兼容性。
4.3 Example
4.3.1 SingleExample
1import java.io.IOException;
2import java.util.Iterator;
3import java.util.List;
4
5import org.apache.hugegraph.driver.GraphManager;
6import org.apache.hugegraph.driver.GremlinManager;
7import org.apache.hugegraph.driver.HugeClient;
8import org.apache.hugegraph.driver.SchemaManager;
9import org.apache.hugegraph.structure.constant.T;
10import org.apache.hugegraph.structure.graph.Edge;
11import org.apache.hugegraph.structure.graph.Path;
12import org.apache.hugegraph.structure.graph.Vertex;
13import org.apache.hugegraph.structure.gremlin.Result;
14import org.apache.hugegraph.structure.gremlin.ResultSet;
15
16public class SingleExample {
17
18 public static void main(String[] args) throws IOException {
19 // If connect failed will throw a exception.
20 HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
21 "DEFAULT",
22 "hugegraph")
23 .configUser("username", "password")
24 // 这是示例,生产环境需要使用安全的凭证
25 .build();
26
27 SchemaManager schema = hugeClient.schema();
28
29 schema.propertyKey("name").asText().ifNotExist().create();
30 schema.propertyKey("age").asInt().ifNotExist().create();
31 schema.propertyKey("city").asText().ifNotExist().create();
32 schema.propertyKey("weight").asDouble().ifNotExist().create();
33 schema.propertyKey("lang").asText().ifNotExist().create();
34 schema.propertyKey("date").asDate().ifNotExist().create();
35 schema.propertyKey("price").asInt().ifNotExist().create();
36
37 schema.vertexLabel("person")
38 .properties("name", "age", "city")
39 .primaryKeys("name")
40 .ifNotExist()
41 .create();
42
43 schema.vertexLabel("software")
44 .properties("name", "lang", "price")
45 .primaryKeys("name")
46 .ifNotExist()
47 .create();
48
49 schema.indexLabel("personByCity")
50 .onV("person")
51 .by("city")
52 .secondary()
53 .ifNotExist()
54 .create();
55
56 schema.indexLabel("personByAgeAndCity")
57 .onV("person")
58 .by("age", "city")
59 .secondary()
60 .ifNotExist()
61 .create();
62
63 schema.indexLabel("softwareByPrice")
64 .onV("software")
65 .by("price")
66 .range()
67 .ifNotExist()
68 .create();
69
70 schema.edgeLabel("knows")
71 .sourceLabel("person")
72 .targetLabel("person")
73 .properties("date", "weight")
74 .ifNotExist()
75 .create();
76
77 schema.edgeLabel("created")
78 .sourceLabel("person").targetLabel("software")
79 .properties("date", "weight")
80 .ifNotExist()
81 .create();
82
83 schema.indexLabel("createdByDate")
84 .onE("created")
85 .by("date")
86 .secondary()
87 .ifNotExist()
88 .create();
89
90 schema.indexLabel("createdByWeight")
91 .onE("created")
92 .by("weight")
93 .range()
94 .ifNotExist()
95 .create();
96
97 schema.indexLabel("knowsByWeight")
98 .onE("knows")
99 .by("weight")
100 .range()
101 .ifNotExist()
102 .create();
103
104 GraphManager graph = hugeClient.graph();
105 Vertex marko = graph.addVertex(T.LABEL, "person", "name", "marko",
106 "age", 29, "city", "Beijing");
107 Vertex vadas = graph.addVertex(T.LABEL, "person", "name", "vadas",
108 "age", 27, "city", "Hongkong");
109 Vertex lop = graph.addVertex(T.LABEL, "software", "name", "lop",
110 "lang", "java", "price", 328);
111 Vertex josh = graph.addVertex(T.LABEL, "person", "name", "josh",
112 "age", 32, "city", "Beijing");
113 Vertex ripple = graph.addVertex(T.LABEL, "software", "name", "ripple",
114 "lang", "java", "price", 199);
115 Vertex peter = graph.addVertex(T.LABEL, "person", "name", "peter",
116 "age", 35, "city", "Shanghai");
117
118 marko.addEdge("knows", vadas, "date", "2016-01-10", "weight", 0.5);
119 marko.addEdge("knows", josh, "date", "2013-02-20", "weight", 1.0);
120 marko.addEdge("created", lop, "date", "2017-12-10", "weight", 0.4);
121 josh.addEdge("created", lop, "date", "2009-11-11", "weight", 0.4);
122 josh.addEdge("created", ripple, "date", "2017-12-10", "weight", 1.0);
123 peter.addEdge("created", lop, "date", "2017-03-24", "weight", 0.2);
124
125 GremlinManager gremlin = hugeClient.gremlin();
126 System.out.println("==== Path ====");
127 ResultSet resultSet = gremlin.gremlin("g.V().outE().path()").execute();
128 Iterator<Result> results = resultSet.iterator();
129 results.forEachRemaining(result -> {
130 System.out.println(result.getObject().getClass());
131 Object object = result.getObject();
132 if (object instanceof Vertex) {
133 System.out.println(((Vertex) object).id());
134 } else if (object instanceof Edge) {
135 System.out.println(((Edge) object).id());
136 } else if (object instanceof Path) {
137 List<Object> elements = ((Path) object).objects();
138 elements.forEach(element -> {
139 System.out.println(element.getClass());
140 System.out.println(element);
141 });
142 } else {
143 System.out.println(object);
144 }
145 });
146
147 hugeClient.close();
148 }
149}4.3.2 BatchExample
1import java.util.ArrayList;
2import java.util.List;
3
4import org.apache.hugegraph.driver.GraphManager;
5import org.apache.hugegraph.driver.HugeClient;
6import org.apache.hugegraph.driver.SchemaManager;
7import org.apache.hugegraph.structure.graph.Edge;
8import org.apache.hugegraph.structure.graph.Vertex;
9
10public class BatchExample {
11
12 public static void main(String[] args) {
13 // If connect failed will throw a exception.
14 HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
15 "DEFAULT",
16 "hugegraph")
17 .configUser("username", "password")
18 // 这是示例,生产环境需要使用安全的凭证
19 .build();
20
21 SchemaManager schema = hugeClient.schema();
22
23 schema.propertyKey("name").asText().ifNotExist().create();
24 schema.propertyKey("age").asInt().ifNotExist().create();
25 schema.propertyKey("lang").asText().ifNotExist().create();
26 schema.propertyKey("date").asDate().ifNotExist().create();
27 schema.propertyKey("price").asInt().ifNotExist().create();
28
29 schema.vertexLabel("person")
30 .properties("name", "age")
31 .primaryKeys("name")
32 .ifNotExist()
33 .create();
34
35 schema.vertexLabel("person")
36 .properties("price")
37 .nullableKeys("price")
38 .append();
39
40 schema.vertexLabel("software")
41 .properties("name", "lang", "price")
42 .primaryKeys("name")
43 .ifNotExist()
44 .create();
45
46 schema.indexLabel("softwareByPrice")
47 .onV("software").by("price")
48 .range()
49 .ifNotExist()
50 .create();
51
52 schema.edgeLabel("knows")
53 .link("person", "person")
54 .properties("date")
55 .ifNotExist()
56 .create();
57
58 schema.edgeLabel("created")
59 .link("person", "software")
60 .properties("date")
61 .ifNotExist()
62 .create();
63
64 schema.indexLabel("createdByDate")
65 .onE("created").by("date")
66 .secondary()
67 .ifNotExist()
68 .create();
69
70 // get schema object by name
71 System.out.println(schema.getPropertyKey("name"));
72 System.out.println(schema.getVertexLabel("person"));
73 System.out.println(schema.getEdgeLabel("knows"));
74 System.out.println(schema.getIndexLabel("createdByDate"));
75
76 // list all schema objects
77 System.out.println(schema.getPropertyKeys());
78 System.out.println(schema.getVertexLabels());
79 System.out.println(schema.getEdgeLabels());
80 System.out.println(schema.getIndexLabels());
81
82 GraphManager graph = hugeClient.graph();
83
84 Vertex marko = new Vertex("person").property("name", "marko")
85 .property("age", 29);
86 Vertex vadas = new Vertex("person").property("name", "vadas")
87 .property("age", 27);
88 Vertex lop = new Vertex("software").property("name", "lop")
89 .property("lang", "java")
90 .property("price", 328);
91 Vertex josh = new Vertex("person").property("name", "josh")
92 .property("age", 32);
93 Vertex ripple = new Vertex("software").property("name", "ripple")
94 .property("lang", "java")
95 .property("price", 199);
96 Vertex peter = new Vertex("person").property("name", "peter")
97 .property("age", 35);
98
99 Edge markoKnowsVadas = new Edge("knows").source(marko).target(vadas)
100 .property("date", "2016-01-10");
101 Edge markoKnowsJosh = new Edge("knows").source(marko).target(josh)
102 .property("date", "2013-02-20");
103 Edge markoCreateLop = new Edge("created").source(marko).target(lop)
104 .property("date",
105 "2017-12-10");
106 Edge joshCreateRipple = new Edge("created").source(josh).target(ripple)
107 .property("date",
108 "2017-12-10");
109 Edge joshCreateLop = new Edge("created").source(josh).target(lop)
110 .property("date", "2009-11-11");
111 Edge peterCreateLop = new Edge("created").source(peter).target(lop)
112 .property("date",
113 "2017-03-24");
114
115 List<Vertex> vertices = new ArrayList<>();
116 vertices.add(marko);
117 vertices.add(vadas);
118 vertices.add(lop);
119 vertices.add(josh);
120 vertices.add(ripple);
121 vertices.add(peter);
122
123 List<Edge> edges = new ArrayList<>();
124 edges.add(markoKnowsVadas);
125 edges.add(markoKnowsJosh);
126 edges.add(markoCreateLop);
127 edges.add(joshCreateRipple);
128 edges.add(joshCreateLop);
129 edges.add(peterCreateLop);
130
131 vertices = graph.addVertices(vertices);
132 vertices.forEach(vertex -> System.out.println(vertex));
133
134 edges = graph.addEdges(edges, false);
135 edges.forEach(edge -> System.out.println(edge));
136
137 hugeClient.close();
138 }
139}4.4 运行 Example
运行 Example 之前需要启动 Server, 启动过程见HugeGraph-Server Quick Start
4.5 详细 API 说明
2 - 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/。
3 - HugeGraph Go 客户端快速入门
HugeGraph Go Client 是 Toolchain 仓库中的 Go SDK,目前提供版本查询、Schema、顶点、边和 Gremlin API。
该模块仍在开发中。接口范围以
hugegraph-client-go/api/v1下的源码为准。
环境要求
- Go 1.19 或更高版本
- 可访问的 HugeGraph Server,默认示例地址为
http://127.0.0.1:8080
安装
在 Go module 项目中执行:
1go get github.com/apache/hugegraph-toolchain/hugegraph-client-go初始化客户端
NewCommonClient 要求 Host 是 IP 地址;未启用认证时,用户名和密码留空。当前 Server 的图资源路径包含图空间,默认填写 DEFAULT。将 GraphSpace 留空只适用于仍使用 /graphs/{graph} 路径的旧版 Server。
1package main
2
3import (
4 "fmt"
5 "log"
6
7 hugegraph "github.com/apache/hugegraph-toolchain/hugegraph-client-go"
8)
9
10func main() {
11 client, err := hugegraph.NewCommonClient(hugegraph.Config{
12 Host: "127.0.0.1",
13 Port: 8080,
14 GraphSpace: "DEFAULT",
15 Graph: "hugegraph",
16 Username: "",
17 Password: "",
18 })
19 if err != nil {
20 log.Fatal(err)
21 }
22
23 response, err := client.Version()
24 if err != nil {
25 log.Fatal(err)
26 }
27 defer response.Body.Close()
28
29 fmt.Println(response.Versions.Version)
30}Version() 返回的 Versions 包含 HugeGraph Server、Core、Gremlin 和 REST API 版本。若使用源码提供的 NewDefaultCommonClient(),默认连接 127.0.0.1:8080 下的 hugegraph 图,并使用 admin/pa 认证;生产代码通常应显式传入配置。
已实现的入口
CommonClient 当前公开以下入口:
| 入口 | 用途 |
|---|---|
Version() | 查询服务端版本 |
Schema() | 查询完整 Schema |
Propertykey | 管理 PropertyKey |
VertexLabel | 管理 VertexLabel |
EdgeLabel | 管理 EdgeLabel |
Vertex | 创建、批量创建和更新顶点属性 |
Gremlin | 通过 GET 或 POST 执行 Gremlin |
完整调用方式可参考各 API 目录中的测试,例如 version_test.go 和 vertexlabel_test.go。