这是本节的多页打印视图。 .
HugeGraph Client
1 - HugeGraph-Java-Client
1 HugeGraph-Client 概述
HugeGraph-Client 向 HugeGraph-Server 发出 HTTP 请求,获取并解析 Server 的执行结果。
提供了 Java/Go/Python 版,
用户可以使用 Client-API 编写代码操作 HugeGraph,比如元数据和图数据的增删改查,或者执行 gremlin 语句等。
后文主要是 Java 使用示例 (其他语言 SDK 可参考对应 READEME 页面)
现在已经支持基于 Go/Python 语言的 HugeGraph Client SDK (version >=1.2.0)
2 环境要求
- java 11 (兼容 java 8)
- maven 3.5+
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 <!-- Update to the latest release version -->
7 <version>1.5.0</version>
8 </dependency>
9</dependencies>注:Graph 所有组件版本号均保持一致
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 "hugegraph")
22 .build();
23
24 SchemaManager schema = hugeClient.schema();
25
26 schema.propertyKey("name").asText().ifNotExist().create();
27 schema.propertyKey("age").asInt().ifNotExist().create();
28 schema.propertyKey("city").asText().ifNotExist().create();
29 schema.propertyKey("weight").asDouble().ifNotExist().create();
30 schema.propertyKey("lang").asText().ifNotExist().create();
31 schema.propertyKey("date").asDate().ifNotExist().create();
32 schema.propertyKey("price").asInt().ifNotExist().create();
33
34 schema.vertexLabel("person")
35 .properties("name", "age", "city")
36 .primaryKeys("name")
37 .ifNotExist()
38 .create();
39
40 schema.vertexLabel("software")
41 .properties("name", "lang", "price")
42 .primaryKeys("name")
43 .ifNotExist()
44 .create();
45
46 schema.indexLabel("personByCity")
47 .onV("person")
48 .by("city")
49 .secondary()
50 .ifNotExist()
51 .create();
52
53 schema.indexLabel("personByAgeAndCity")
54 .onV("person")
55 .by("age", "city")
56 .secondary()
57 .ifNotExist()
58 .create();
59
60 schema.indexLabel("softwareByPrice")
61 .onV("software")
62 .by("price")
63 .range()
64 .ifNotExist()
65 .create();
66
67 schema.edgeLabel("knows")
68 .sourceLabel("person")
69 .targetLabel("person")
70 .properties("date", "weight")
71 .ifNotExist()
72 .create();
73
74 schema.edgeLabel("created")
75 .sourceLabel("person").targetLabel("software")
76 .properties("date", "weight")
77 .ifNotExist()
78 .create();
79
80 schema.indexLabel("createdByDate")
81 .onE("created")
82 .by("date")
83 .secondary()
84 .ifNotExist()
85 .create();
86
87 schema.indexLabel("createdByWeight")
88 .onE("created")
89 .by("weight")
90 .range()
91 .ifNotExist()
92 .create();
93
94 schema.indexLabel("knowsByWeight")
95 .onE("knows")
96 .by("weight")
97 .range()
98 .ifNotExist()
99 .create();
100
101 GraphManager graph = hugeClient.graph();
102 Vertex marko = graph.addVertex(T.LABEL, "person", "name", "marko",
103 "age", 29, "city", "Beijing");
104 Vertex vadas = graph.addVertex(T.LABEL, "person", "name", "vadas",
105 "age", 27, "city", "Hongkong");
106 Vertex lop = graph.addVertex(T.LABEL, "software", "name", "lop",
107 "lang", "java", "price", 328);
108 Vertex josh = graph.addVertex(T.LABEL, "person", "name", "josh",
109 "age", 32, "city", "Beijing");
110 Vertex ripple = graph.addVertex(T.LABEL, "software", "name", "ripple",
111 "lang", "java", "price", 199);
112 Vertex peter = graph.addVertex(T.LABEL, "person", "name", "peter",
113 "age", 35, "city", "Shanghai");
114
115 marko.addEdge("knows", vadas, "date", "2016-01-10", "weight", 0.5);
116 marko.addEdge("knows", josh, "date", "2013-02-20", "weight", 1.0);
117 marko.addEdge("created", lop, "date", "2017-12-10", "weight", 0.4);
118 josh.addEdge("created", lop, "date", "2009-11-11", "weight", 0.4);
119 josh.addEdge("created", ripple, "date", "2017-12-10", "weight", 1.0);
120 peter.addEdge("created", lop, "date", "2017-03-24", "weight", 0.2);
121
122 GremlinManager gremlin = hugeClient.gremlin();
123 System.out.println("==== Path ====");
124 ResultSet resultSet = gremlin.gremlin("g.V().outE().path()").execute();
125 Iterator<Result> results = resultSet.iterator();
126 results.forEachRemaining(result -> {
127 System.out.println(result.getObject().getClass());
128 Object object = result.getObject();
129 if (object instanceof Vertex) {
130 System.out.println(((Vertex) object).id());
131 } else if (object instanceof Edge) {
132 System.out.println(((Edge) object).id());
133 } else if (object instanceof Path) {
134 List<Object> elements = ((Path) object).objects();
135 elements.forEach(element -> {
136 System.out.println(element.getClass());
137 System.out.println(element);
138 });
139 } else {
140 System.out.println(object);
141 }
142 });
143
144 hugeClient.close();
145 }
146}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 "hugegraph")
16 .build();
17
18 SchemaManager schema = hugeClient.schema();
19
20 schema.propertyKey("name").asText().ifNotExist().create();
21 schema.propertyKey("age").asInt().ifNotExist().create();
22 schema.propertyKey("lang").asText().ifNotExist().create();
23 schema.propertyKey("date").asDate().ifNotExist().create();
24 schema.propertyKey("price").asInt().ifNotExist().create();
25
26 schema.vertexLabel("person")
27 .properties("name", "age")
28 .primaryKeys("name")
29 .ifNotExist()
30 .create();
31
32 schema.vertexLabel("person")
33 .properties("price")
34 .nullableKeys("price")
35 .append();
36
37 schema.vertexLabel("software")
38 .properties("name", "lang", "price")
39 .primaryKeys("name")
40 .ifNotExist()
41 .create();
42
43 schema.indexLabel("softwareByPrice")
44 .onV("software").by("price")
45 .range()
46 .ifNotExist()
47 .create();
48
49 schema.edgeLabel("knows")
50 .link("person", "person")
51 .properties("date")
52 .ifNotExist()
53 .create();
54
55 schema.edgeLabel("created")
56 .link("person", "software")
57 .properties("date")
58 .ifNotExist()
59 .create();
60
61 schema.indexLabel("createdByDate")
62 .onE("created").by("date")
63 .secondary()
64 .ifNotExist()
65 .create();
66
67 // get schema object by name
68 System.out.println(schema.getPropertyKey("name"));
69 System.out.println(schema.getVertexLabel("person"));
70 System.out.println(schema.getEdgeLabel("knows"));
71 System.out.println(schema.getIndexLabel("createdByDate"));
72
73 // list all schema objects
74 System.out.println(schema.getPropertyKeys());
75 System.out.println(schema.getVertexLabels());
76 System.out.println(schema.getEdgeLabels());
77 System.out.println(schema.getIndexLabels());
78
79 GraphManager graph = hugeClient.graph();
80
81 Vertex marko = new Vertex("person").property("name", "marko")
82 .property("age", 29);
83 Vertex vadas = new Vertex("person").property("name", "vadas")
84 .property("age", 27);
85 Vertex lop = new Vertex("software").property("name", "lop")
86 .property("lang", "java")
87 .property("price", 328);
88 Vertex josh = new Vertex("person").property("name", "josh")
89 .property("age", 32);
90 Vertex ripple = new Vertex("software").property("name", "ripple")
91 .property("lang", "java")
92 .property("price", 199);
93 Vertex peter = new Vertex("person").property("name", "peter")
94 .property("age", 35);
95
96 Edge markoKnowsVadas = new Edge("knows").source(marko).target(vadas)
97 .property("date", "2016-01-10");
98 Edge markoKnowsJosh = new Edge("knows").source(marko).target(josh)
99 .property("date", "2013-02-20");
100 Edge markoCreateLop = new Edge("created").source(marko).target(lop)
101 .property("date",
102 "2017-12-10");
103 Edge joshCreateRipple = new Edge("created").source(josh).target(ripple)
104 .property("date",
105 "2017-12-10");
106 Edge joshCreateLop = new Edge("created").source(josh).target(lop)
107 .property("date", "2009-11-11");
108 Edge peterCreateLop = new Edge("created").source(peter).target(lop)
109 .property("date",
110 "2017-03-24");
111
112 List<Vertex> vertices = new ArrayList<>();
113 vertices.add(marko);
114 vertices.add(vadas);
115 vertices.add(lop);
116 vertices.add(josh);
117 vertices.add(ripple);
118 vertices.add(peter);
119
120 List<Edge> edges = new ArrayList<>();
121 edges.add(markoKnowsVadas);
122 edges.add(markoKnowsJosh);
123 edges.add(markoCreateLop);
124 edges.add(joshCreateRipple);
125 edges.add(joshCreateLop);
126 edges.add(peterCreateLop);
127
128 vertices = graph.addVertices(vertices);
129 vertices.forEach(vertex -> System.out.println(vertex));
130
131 edges = graph.addEdges(edges, false);
132 edges.forEach(edge -> System.out.println(edge));
133
134 hugeClient.close();
135 }
136}4.4 运行 Example
运行 Example 之前需要启动 Server, 启动过程见HugeGraph-Server Quick Start
4.5 详细 API 说明
2 - HugeGraph Python 客户端快速入门
hugegraph-python-client 是 HugeGraph 图数据库的 Python 客户端/SDK。
它用于定义图结构、对图数据执行 CRUD 操作、管理 Schema 以及执行 Gremlin 查询。hugegraph-llm 和 hugegraph-ml 模块都依赖于这个基础库。
安装
安装已发布的包(稳定版)
要安装 hugegraph-python-client,您可以使用 uv/pip 或从源码构建:
1# uv 是可选的,您可以直接使用 pip
2uv pip install hugegraph-python # 注意:可能不是最新版本,建议从源码安装
3# WIP:我们很快会将 'hugegraph-python-client' 作为包名从源码安装(最新代码)
要从源码安装,请克隆仓库并安装所需的依赖项:
1git clone https://github.com/apache/incubator-hugegraph-ai.git
2cd incubator-hugegraph-ai/hugegraph-python-client
3
4# 普通安装
5uv pip install .
6
7# (可选) 安装开发版本
8uv pip install -e .使用示例
定义图结构
您可以使用 hugegraph-python-client 来定义图结构。以下是如何定义图的示例:
1from pyhugegraph.client import PyHugeClient
2
3# 初始化客户端
4# 对于 HugeGraph API 版本 ≥ v3:(或启用 graphspace 功能)
5# - 如果启用了 graphspace,则 'graphspace' 参数变得相关(默认名称为 'DEFAULT')
6# - 否则,graphspace 参数是可选的,可以忽略。
7client = PyHugeClient("127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph", graphspace="DEFAULT")
8
9""""
10注意:
11可以参考您 HugeGraph 版本的官方 REST-API 文档以获取准确的详细信息。
12如果某些 API 与预期不符,请提交 issue 或联系我们。
13"""
14schema = client.schema()
15schema.propertyKey("name").asText().ifNotExist().create()
16schema.propertyKey("birthDate").asText().ifNotExist().create()
17schema.vertexLabel("Person").properties("name", "birthDate").usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
18schema.vertexLabel("Movie").properties("name").usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
19schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie").ifNotExist().create()
20
21print(schema.getVertexLabels())
22print(schema.getEdgeLabels())
23print(schema.getRelations())
24
25# 初始化图
26g = client.graph()
27v_al_pacino = g.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"})
28v_robert = g.addVertex("Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"})
29v_godfather = g.addVertex("Movie", {"name": "The Godfather"})
30v_godfather2 = g.addVertex("Movie", {"name": "The Godfather Part II"})
31v_godfather3 = g.addVertex("Movie", {"name": "The Godfather Coda The Death of Michael Corleone"})
32
33g.addEdge("ActedIn", v_al_pacino.id, v_godfather.id, {})
34g.addEdge("ActedIn", v_al_pacino.id, v_godfather2.id, {})
35g.addEdge("ActedIn", v_al_pacino.id, v_godfather3.id, {})
36g.addEdge("ActedIn", v_robert.id, v_godfather2.id, {})
37
38res = g.getVertexById(v_al_pacino.id).label
39print(res)
40g.close()Schema 管理
hugegraph-python-client 提供了全面的 Schema 管理功能。
定义属性键 (Property Key)
1# 定义属性键
2client.schema().propertyKey('name').dataType('STRING').cardinality('SINGLE').create()定义顶点标签 (Vertex Label)
1# 定义顶点标签
2client.schema().vertexLabel('person').properties('name', 'age').primaryKeys('name').create()定义边标签 (Edge Label)
1# 定义边标签
2client.schema().edgeLabel('knows').sourceLabel('person').targetLabel('person').properties('since').create()定义索引标签 (Index Label)
1# 定义索引标签
2client.schema().indexLabel('personByName').onV('person').by('name').secondary().create()CRUD 操作
客户端允许您对图数据执行 CRUD 操作。以下是如何创建、读取、更新和删除顶点和边的示例:
创建顶点和边
1# 创建顶点
2v1 = client.graph().addVertex('person').property('name', 'John').property('age', 29).create()
3v2 = client.graph().addVertex('person').property('name', 'Jane').property('age', 25).create()
4
5# 创建边
6client.graph().addEdge(v1, 'knows', v2).property('since', '2020').create()读取顶点和边
1# 通过 ID 获取顶点
2vertex = client.graph().getVertexById(v1.id)
3print(vertex)
4
5# 通过 ID 获取边
6edge = client.graph().getEdgeById(edge.id) # 假设 edge 对象已定义并有 id 属性
7print(edge)更新顶点和边
1# 更新顶点
2client.graph().updateVertex(v1.id).property('age', 30).update()
3
4# 更新边
5client.graph().updateEdge(edge.id).property('since', '2021').update() # 假设 edge 对象已定义并有 id 属性删除顶点和边
1# 删除顶点
2client.graph().deleteVertex(v1.id)
3
4# 删除边
5client.graph().deleteEdge(edge.id) # 假设 edge 对象已定义并有 id 属性执行 Gremlin 查询
客户端还支持执行 Gremlin 查询:
1# 执行 Gremlin 查询
2g = client.gremlin()
3res = g.exec("g.V().limit(5)")
4print(res)其他信息正在建设中 🚧 (欢迎为此添加更多文档,用户可以参考 java-client-doc 获取类似用法)
API 文档参考
贡献
- 欢迎为
hugegraph-python-client做出贡献。请参阅 贡献指南 获取更多信息。 - 代码格式:请在提交 PR 前运行
./style/code_format_and_analysis.sh来格式化您的代码。
感谢所有已经为 hugegraph-python-client 做出贡献的人!
3 - HugeGraph Go 客户端快速入门
基于 Go 语言的 HugeGraph Client SDK 工具。
软件架构
(软件架构说明)
安装教程
1go get github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go已实现 API
| API | 说明 |
|---|---|
| schema | 获取模型 schema |
| version | 获取版本信息 |
使用说明
1. 初始化客户端
1package main
2
3import (
4 "log"
5 "os"
6
7 "github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go"
8 "github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go/hgtransport"
9)
10
11func main() {
12 client, err := hugegraph.NewCommonClient(hugegraph.Config{
13 Host: "127.0.0.1",
14 Port: 8080,
15 Graph: "hugegraph",
16 Username: "", // 根据实际情况填写用户名
17 Password: "", // 根据实际情况填写密码
18 Logger: &hgtransport.ColorLogger{
19 Output: os.Stdout,
20 EnableRequestBody: true,
21 EnableResponseBody: true,
22 },
23 })
24
25 if err != nil {
26 log.Fatalf("Error creating the client: %s\n", err)
27 }
28
29 // 使用 client 进行操作...
30 _ = client // 避免 "imported and not used" 错误
31}2. 获取 HugeGraph 版本
使用 SDK 获取版本信息
1package main
2
3import (
4 "fmt"
5 "log"
6 "os"
7
8 "github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go"
9 "github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go/hgtransport"
10)
11
12// initClient 初始化并返回一个 HugeGraph 客户端实例
13func initClient() *hugegraph.CommonClient {
14 client, err := hugegraph.NewCommonClient(hugegraph.Config{
15 Host: "127.0.0.1",
16 Port: 8080,
17 Graph: "hugegraph",
18 Username: "",
19 Password: "",
20 Logger: &hgtransport.ColorLogger{
21 Output: os.Stdout,
22 EnableRequestBody: true,
23 EnableResponseBody: true,
24 },
25 })
26 if err != nil {
27 log.Fatalf("Error creating the client: %s\n", err)
28 }
29 return client
30}
31
32func getVersion() {
33 client := initClient()
34 // 假设 client 有一个 Version 方法返回版本信息和一个错误
35 // res, err := client.Version() // 实际调用
36 // 模拟返回,因为原始 README 中的 client.Version() 返回类型与此处使用不完全匹配
37 type VersionInfo struct {
38 Versions struct {
39 Version string `json:"version"`
40 Core string `json:"core"`
41 Gremlin string `json:"gremlin"`
42 API string `json:"api"`
43 } `json:"versions"`
44 // Body io.ReadCloser // 假设有 Body 用于关闭,根据实际 SDK 调整
45 }
46
47 // 模拟 API 调用和返回
48 res := &VersionInfo{
49 Versions: struct {
50 Version string `json:"version"`
51 Core string `json:"core"`
52 Gremlin string `json:"gremlin"`
53 API string `json:"api"`
54 }{
55 Version: "1.0.0", // 示例版本
56 Core: "1.0.0",
57 Gremlin: "3.x.x",
58 API: "v1",
59 },
60 }
61 // err := error(nil) // 假设没有错误
62
63 // if err != nil {
64 // log.Fatalf("Error getting the response: %s\n", err)
65 // }
66 // defer res.Body.Close() // 如果有 Body,需要关闭
67
68 fmt.Println(res.Versions)
69 fmt.Println(res.Versions.Version)
70}
71
72func main() {
73 getVersion()
74}返回值的结构
1package main
2
3// VersionResponse 定义了版本 API 返回的结构体
4type VersionResponse struct {
5 Versions struct {
6 Version string `json:"version"` // hugegraph version
7 Core string `json:"core"` // hugegraph core version
8 Gremlin string `json:"gremlin"` // hugegraph gremlin version
9 API string `json:"api"` // hugegraph api version
10 } `json:"versions"`
11}