1 - HugeGraph-Java-Client
1 Overview
HugeGraph Java Client translates Java APIs into REST requests to HugeGraph Server. It supports managing schemas and graph data, executing Gremlin queries, and calling Traverser APIs. See the Client API for detailed interfaces; this page shows how to use the client in a Java project.
For other languages, use the Go Client or the Python Client maintained in the HugeGraph-AI repository.
2 What You Need
- JDK 11 (used by the current CI; the source target remains Java 8)
- Maven 3.6+
3 How To Use
The basic steps to use HugeGraph-Client are as follows:
- Build a new Maven project by IDEA or Eclipse
- Add HugeGraph-Client dependency in a pom file;
- Create an object to invoke the interface of HugeGraph-Client
See the complete example in the following section for the detail.
4 Complete Example
4.1 Build New Maven Project
Using IDEA or Eclipse to create the project:
4.2 Add Hugegraph-Client Dependency In POM
1<dependencies>
2 <dependency>
3 <groupId>org.apache.hugegraph</groupId>
4 <artifactId>hugegraph-client</artifactId>
5 <!-- The complete examples below work with the published 1.7.0 client -->
6 <version>1.7.0</version>
7 </dependency>
8</dependencies>
The complete examples below use Schema, Graph, Gremlin and resource-cleanup APIs available in the published Client 1.7.0
and compatible with Toolchain master. Use the dependency above directly in your example project.
For new master APIs in the API reference, such as capability detection, use Client 1.8.0
from Toolchain master and change the POM version to 1.8.0. If that version is not published to Maven yet, run the following
command from the Toolchain source root to install the Client and its parent POM locally. The source build still needs
its dependencies available from your configured Maven repositories.
1mvn install -pl hugegraph-client -am -DskipTests -Dmaven.javadoc.skip=true -ntp
Client and Server versions need not match. Check the supported server API range and required capabilities before upgrading.
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 // This is an example. In a production environment, secure credentials should be used.
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 HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
14 "DEFAULT",
15 "hugegraph")
16 .configUser("username", "password")
17 // This is an example. In a production environment, secure credentials should be used.
18 .build();
19
20 SchemaManager schema = hugeClient.schema();
21
22 schema.propertyKey("name").asText().ifNotExist().create();
23 schema.propertyKey("age").asInt().ifNotExist().create();
24 schema.propertyKey("lang").asText().ifNotExist().create();
25 schema.propertyKey("date").asDate().ifNotExist().create();
26 schema.propertyKey("price").asInt().ifNotExist().create();
27
28 schema.vertexLabel("person")
29 .properties("name", "age")
30 .primaryKeys("name")
31 .ifNotExist()
32 .create();
33
34 schema.vertexLabel("person")
35 .properties("price")
36 .nullableKeys("price")
37 .append();
38
39 schema.vertexLabel("software")
40 .properties("name", "lang", "price")
41 .primaryKeys("name")
42 .ifNotExist()
43 .create();
44
45 schema.indexLabel("softwareByPrice")
46 .onV("software").by("price")
47 .range()
48 .ifNotExist()
49 .create();
50
51 schema.edgeLabel("knows")
52 .link("person", "person")
53 .properties("date")
54 .ifNotExist()
55 .create();
56
57 schema.edgeLabel("created")
58 .link("person", "software")
59 .properties("date")
60 .ifNotExist()
61 .create();
62
63 schema.indexLabel("createdByDate")
64 .onE("created").by("date")
65 .secondary()
66 .ifNotExist()
67 .create();
68
69 // get schema object by name
70 System.out.println(schema.getPropertyKey("name"));
71 System.out.println(schema.getVertexLabel("person"));
72 System.out.println(schema.getEdgeLabel("knows"));
73 System.out.println(schema.getIndexLabel("createdByDate"));
74
75 // list all schema objects
76 System.out.println(schema.getPropertyKeys());
77 System.out.println(schema.getVertexLabels());
78 System.out.println(schema.getEdgeLabels());
79 System.out.println(schema.getIndexLabels());
80
81 GraphManager graph = hugeClient.graph();
82
83 Vertex marko = new Vertex("person").property("name", "marko")
84 .property("age", 29);
85 Vertex vadas = new Vertex("person").property("name", "vadas")
86 .property("age", 27);
87 Vertex lop = new Vertex("software").property("name", "lop")
88 .property("lang", "java")
89 .property("price", 328);
90 Vertex josh = new Vertex("person").property("name", "josh")
91 .property("age", 32);
92 Vertex ripple = new Vertex("software").property("name", "ripple")
93 .property("lang", "java")
94 .property("price", 199);
95 Vertex peter = new Vertex("person").property("name", "peter")
96 .property("age", 35);
97
98 Edge markoKnowsVadas = new Edge("knows").source(marko).target(vadas)
99 .property("date", "2016-01-10");
100 Edge markoKnowsJosh = new Edge("knows").source(marko).target(josh)
101 .property("date", "2013-02-20");
102 Edge markoCreateLop = new Edge("created").source(marko).target(lop)
103 .property("date",
104 "2017-12-10");
105 Edge joshCreateRipple = new Edge("created").source(josh).target(ripple)
106 .property("date",
107 "2017-12-10");
108 Edge joshCreateLop = new Edge("created").source(josh).target(lop)
109 .property("date", "2009-11-11");
110 Edge peterCreateLop = new Edge("created").source(peter).target(lop)
111 .property("date",
112 "2017-03-24");
113
114 List<Vertex> vertices = new ArrayList<>();
115 vertices.add(marko);
116 vertices.add(vadas);
117 vertices.add(lop);
118 vertices.add(josh);
119 vertices.add(ripple);
120 vertices.add(peter);
121
122 List<Edge> edges = new ArrayList<>();
123 edges.add(markoKnowsVadas);
124 edges.add(markoKnowsJosh);
125 edges.add(markoCreateLop);
126 edges.add(joshCreateRipple);
127 edges.add(joshCreateLop);
128 edges.add(peterCreateLop);
129
130 vertices = graph.addVertices(vertices);
131 vertices.forEach(vertex -> System.out.println(vertex));
132
133 edges = graph.addEdges(edges, false);
134 edges.forEach(edge -> System.out.println(edge));
135
136 hugeClient.close();
137 }
138}
4.4 Run The Example
Before running Example, you need to start the Server. For the startup process, seeHugeGraph-Server Quick Start.
SeeIntroduce basic API of HugeGraph-Client.
2 - HugeGraph Python Client Quick Start
hugegraph-python-client is the Python SDK for HugeGraph. It manages schemas, reads and writes graph data, and executes Gremlin queries. HugeGraph-LLM and HugeGraph-ML also use this client.
The module lives in the hugegraph-ai repository under hugegraph-python-client/. The import name is pyhugegraph.
Requirements
- The client and HugeGraph-AI workspace require Python 3.10 or later; CI runs client tests on 3.10 and 3.11.
- HugeGraph Server 1.5.0 or later. The client refuses to connect to older servers; use client v1.3.x for those.
uv (recommended) or pip
Runtime dependencies are decorator, requests, setuptools, urllib3 and rich.
Installation
The released package is published on PyPI as hugegraph-python:
1uv pip install hugegraph-python
2# Alternatively: pip install hugegraph-python
These commands do not pin a version and install the latest release; see PyPI. The source directory is hugegraph-python-client, while the distribution is hugegraph-python. Install from the HugeGraph-AI workspace for master code.
To use the latest repository code, sync the workspace from the root of the HugeGraph-AI repository. hugegraph-python-client is a workspace member exposed through the python-client extra, so plain uv sync does not pull it in:
1git clone https://github.com/apache/hugegraph-ai.git
2cd hugegraph-ai
3uv sync --extra python-client
4source .venv/bin/activate
Connect and Write Data
1from pyhugegraph.client import PyHugeClient
2
3client = PyHugeClient(
4 url="http://127.0.0.1:8080",
5 graph="hugegraph",
6 user="admin",
7 pwd="admin",
8 graphspace=None,
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()
Client Parameters
PyHugeClient(url, graph, user, pwd, graphspace=None, timeout=None)
Every HTTP session retries three times with a 0.1 backoff factor on 500, 502 and 504 responses.
Server Version and GraphSpace
The client resolves GraphSpace at construction time:
- A non-empty
graphspace string turns GraphSpace mode on directly. - Otherwise the client sends
GET {url}/versions and reads versions.core. - A server older than 1.5.0 raises
RuntimeError asking you to upgrade the server or use client v1.3.x. - A server newer than 1.5.0 gets
graphspace set to DEFAULT and GraphSpace mode turned on, with a warning in the log. A server at exactly 1.5.0 keeps GraphSpace mode off. - If the probe fails for network reasons, GraphSpace mode stays off.
The mode decides the request prefix: /graphspaces/<graphspace>/graphs/<graph>/... when GraphSpace is on, /graphs/<graph>/... when it is off.
Managers on the Client
Each accessor builds its manager lazily and gives it a dedicated HTTP session.
RankManager, RebuildManager and ServicesManager also ship in pyhugegraph.api, but PyHugeClient does not expose accessors for them yet; construct them directly with a session if you need them.
Common Operations
Build the Schema
The schema builders are fluent. Call create() last, or append(), eliminate() and remove() to change an existing definition.
1schema = client.schema()
2
3# Property keys: asText/asInt/asLong/asFloat/asDouble/asBool/asByte/asBlob/asDate/asObject
4# cardinality: valueSingle/valueList/valueSet
5# aggregation: calcMax/calcMin/calcSum/calcOld
6schema.propertyKey("age").asInt().valueSingle().ifNotExist().create()
7
8# Vertex labels: useAutomaticId/useCustomizeStringId/useCustomizeNumberId/usePrimaryKeyId
9schema.vertexLabel("person").properties("name", "age", "city") \
10 .primaryKeys("name").nullableKeys("city").ifNotExist().create()
11
12# Edge labels: link() is shorthand for sourceLabel() plus targetLabel()
13schema.edgeLabel("knows").link("person", "person").multiTimes() \
14 .properties("date", "city").sortKeys("date").nullableKeys("city") \
15 .ifNotExist().create()
16
17# Index labels: onV/onE, then secondary/range/search/shard/unique
18schema.indexLabel("personByCity").onV("person").by("city") \
19 .secondary().ifNotExist().create()
Query the Schema
1schema = client.schema()
2print(schema.getSchema()) # whole schema, format defaults to "json"
3print(schema.getPropertyKeys())
4print(schema.getVertexLabels())
5print(schema.getEdgeLabels())
6print(schema.getIndexLabels())
7
8# Single definitions
9print(schema.getPropertyKey("name"))
10print(schema.getVertexLabel("person"))
11print(schema.getEdgeLabel("knows"))
12print(schema.getIndexLabel("personByCity"))
13
14# Edge label links, formatted as "Person--ActedIn-->Movie"
15print(schema.getRelations())
Read, Update and Delete Graph Data
The graph API takes property dictionaries, not chained property builders:
1graph = client.graph()
2graph.appendVertex(person.id, {"birthDate": "1940-04-25"}) # add properties
3graph.eliminateVertex(person.id, {"birthDate": "1940-04-25"}) # drop properties
4graph.appendEdge(edge.id, {"city": "Beijing"})
5graph.eliminateEdge(edge.id, {"city": "Beijing"})
6graph.removeEdgeById(edge.id)
7graph.removeVertexById(person.id)
8graph.close()
addVertex returns a VertexData with id, label, type and properties. addEdge returns an EdgeData with id, label, type, outV, outVLabel, inV, inVLabel and properties.
Vertex ids passed to the client may be strings, integers or uuid.UUID values. Booleans are rejected, and integers must fit the Java signed long range.
Batch Writes
addVertices takes (label, properties) pairs, and addEdges takes (label, out_id, in_id, out_label, in_label, properties) tuples. Both return objects that carry only the generated ids.
1graph = client.graph()
2vertices = graph.addVertices([
3 ("person", {"name": "Alice", "age": 20}),
4 ("person", {"name": "Bob", "age": 23}),
5])
6edges = graph.addEdges([
7 ("knows", vertices[0].id, vertices[1].id, "person", "person", {"date": "2012-01-10"}),
8])
Paging and Conditional Queries
1graph = client.graph()
2
3# Returns (vertices, next_page); pass next_page back in to continue
4vertices, next_page = graph.getVertexByPage("person", limit=10)
5vertices, next_page = graph.getVertexByPage("person", limit=10, page=next_page)
6
7# Server-side property predicates
8older = graph.getVertexByCondition("person", properties={"age": "P.gt(29)"})
9
10# Edges by page. When vertex_id is given, direction is required
11edges, next_page = graph.getEdgeByPage(label="knows", limit=10)
12edges, next_page = graph.getEdgeByPage(vertex_id=person.id, direction="OUT", limit=10)
13
14# Batch lookup by id
15graph.getVerticesById([v1.id, v2.id])
16graph.getEdgesById([e1.id, e2.id])
Execute Gremlin
1gremlin = client.gremlin()
2result = gremlin.exec("g.V().limit(5)")
3print(result)
exec binds the graph and g aliases for you, based on the graph name and the resolved GraphSpace, and returns the result field of the server response. A response missing requestId, status or result raises ResponseParseError.
Traverse the Graph
TraverserManager wraps the server traverser endpoints. Its methods use snake_case.
1traverser = client.traverser()
2
3traverser.k_out(marko_id, 2)
4traverser.k_neighbor(marko_id, 2)
5traverser.same_neighbors(marko_id, josh_id)
6traverser.jaccard_similarity(marko_id, josh_id)
7traverser.shortest_path(marko_id, ripple_id, 3)
8traverser.all_shortest_paths(marko_id, ripple_id, 3)
9traverser.weighted_shortest_path(marko_id, ripple_id, "weight", 3)
10traverser.single_source_shortest_path(marko_id, 2)
11traverser.multi_node_shortest_path([marko_id, josh_id], max_depth=2)
12traverser.paths(marko_id, josh_id, 2)
13traverser.crosspoints(marko_id, josh_id, 2)
14traverser.rings(marko_id, 3)
15traverser.rays(marko_id, 2)
16traverser.vertices(marko_id)
17traverser.edges(edge_id)
The POST-based variants take request bodies: advanced_paths, customized_paths, template_paths, customized_crosspoints and fusiform_similarity.
Graph Variables
1variable = client.variable()
2variable.set("owner", "mary")
3print(variable.get("owner"))
4print(variable.all())
5variable.remove("owner")
Async Tasks
1task = client.task()
2print(task.list_tasks(status="success", limit=10))
3print(task.get_task(task_id))
4task.cancel_task(task_id)
5task.delete_task(task_id)
Server Metrics and Graph Info
1metrics = client.metrics()
2metrics.get_all_basic_metrics()
3metrics.get_gauges_metrics()
4metrics.get_counters_metrics()
5metrics.get_histograms_metrics()
6metrics.get_meters_metrics()
7metrics.get_timers_metrics()
8metrics.get_statistics_metrics()
9metrics.get_system_metrics()
10metrics.get_backend_metrics()
11
12graphs = client.graphs()
13graphs.get_all_graphs()
14graphs.get_version()
15graphs.get_graph_info()
16graphs.get_graph_config()
17graphs.clear_graph_all_data() # deletes every vertex, edge and schema entry
18
19print(client.version().version())
Authentication and Authorization
AuthManager follows the server routing: users, targets, belongs and accesses are mounted under /graphspaces/{graphspace}/auth/..., while groups stay at the server-level /auth/groups. On HugeGraph 1.7.0 and later a graphspace must be resolved, otherwise these calls raise ValueError before any request is sent.
1auth = client.auth()
2
3user = auth.create_user("test_user", "password")
4auth.modify_user(user["id"], user_email="hugegraph@apache.org")
5auth.get_user(user["id"])
6auth.list_users(limit=10)
7auth.delete_user(user["id"])
8
9group = auth.create_group("test_group", "read only")
10auth.modify_group(group["id"], group_description="updated")
11auth.list_groups()
12auth.delete_group(group["id"])
13
14target = auth.create_target("target1", "hugegraph", "127.0.0.1:8080", [])
15auth.update_target(target["id"], "target1", "hugegraph", "127.0.0.1:8080", [])
16auth.list_targets()
17auth.delete_target(target["id"])
18
19belong = auth.create_belong(user["id"], group["id"])
20auth.update_belong(belong["id"], "description")
21auth.list_belongs()
22auth.delete_belong(belong["id"])
23
24access = auth.grant_accesses(group["id"], target["id"], "READ")
25auth.modify_accesses(access["id"], "description")
26auth.list_accesses()
27auth.revoke_accesses(access["id"])
Method Naming
Manager methods written in camelCase, such as addVertex and getVertexById, also get a snake_case alias generated at construction time. graph.add_vertex(...) and graph.addVertex(...) reach the same method. The camelCase spellings are marked deprecated in the debug log, so prefer snake_case in new code.
Error Handling
Exceptions live in pyhugegraph.utils.exceptions:
Request and response bodies are logged with password, token and secret values redacted.
1from pyhugegraph.utils.exceptions import NotFoundError
2
3try:
4 graph.getVertexById("no-such-id")
5except NotFoundError:
6 print("vertex missing")
API parameters may change with the HugeGraph REST API version. If an interface is incompatible, first check the REST API documentation for the current server version and the client test cases.
Development Checks
Run formatting and static checks from the root of the HugeGraph-AI repository:
1./style/code_format_and_analysis.sh
Run the tests the same way CI does:
1# Unit and contract tests, no server needed
2uv run pytest hugegraph-python-client/src/tests -m "unit or contract"
3
4# Integration tests against a running server
5HUGEGRAPH_URL=http://127.0.0.1:8080 \
6HUGEGRAPH_GRAPH=hugegraph \
7HUGEGRAPH_USER=admin \
8HUGEGRAPH_PASSWORD=admin \
9uv run pytest hugegraph-python-client/src/tests -m "integration and hugegraph"
CI runs the integration job against the hugegraph/hugegraph:1.7.0 image. HUGEGRAPH_GRAPHSPACE is also read when you need a non-default space.
The source code and tests are under hugegraph-python-client/src/pyhugegraph/ and hugegraph-python-client/src/tests/. A runnable example is at hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py.
3 - HugeGraph Go Client Quick Start
HugeGraph Go Client is the Go SDK in the Toolchain repository. It currently provides APIs for version queries, schemas (property keys, vertex labels, and edge labels), vertices, and Gremlin. An edge data API is not implemented yet.
This module is still under development. Refer to the source code under hugegraph-client-go/api/v1 for the currently available interfaces.
Requirements
- Go 1.19 or later
- An accessible HugeGraph Server; examples use
http://127.0.0.1:8080
Installation
Run the following command in a Go module project:
1go get github.com/apache/hugegraph-toolchain/hugegraph-client-go
Initialize the Client
NewCommonClient requires Host to be an IP address and Port to be between 1 and 65535. The client always connects over plain HTTP. Leave the username and password empty when authentication is disabled; Basic Auth is sent only when both are set.
GraphSpace is applied only by the Vertex API, which then calls /graphspaces/{space}/graphs/{graph}/..., and by the default Gremlin aliases (an empty value is treated as DEFAULT). The schema entry points and Version() always call /graphs/{graph}/... and /versions, regardless of GraphSpace. Use DEFAULT for the default space; leaving GraphSpace empty makes the Vertex API fall back to the /graphs/{graph} path used by older servers.
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}
The Versions value returned by Version() includes the HugeGraph Server, Core, Gremlin, and REST API versions. The NewDefaultCommonClient() helper in the source connects to the hugegraph graph at 127.0.0.1:8080 with admin/pa authentication and a ColorLogger that prints every request and response body. Production code should normally pass an explicit configuration instead.
Configuration Options
hugegraph.Config has the following fields:
The hgtransport package ships four loggers: TextLogger (plain text), ColorLogger (terminal colors), CurlLogger (runnable curl commands), and JSONLogger (JSON lines). Each has the same fields: Output (an io.Writer), EnableRequestBody, and EnableResponseBody.
1import (
2 "os"
3
4 hugegraph "github.com/apache/hugegraph-toolchain/hugegraph-client-go"
5 "github.com/apache/hugegraph-toolchain/hugegraph-client-go/hgtransport"
6)
7
8client, err := hugegraph.NewCommonClient(hugegraph.Config{
9 Host: "127.0.0.1",
10 Port: 8080,
11 Graph: "hugegraph",
12 Logger: &hgtransport.ColorLogger{
13 Output: os.Stdout,
14 EnableRequestBody: true,
15 EnableResponseBody: true,
16 },
17})
Available Entry Points
CommonClient currently exposes the following entry points:
Each operation takes functional options named With... on the operation itself, for example client.Gremlin.Post.WithGremlin(...) or client.Propertykey.GetByName.WithName(...).
EdgeLabel.Create accepts Properties: nil or an empty []string{} in its request data to create an edge label without properties.
Typed APIs return err for request validation, transport, response reading, or JSON decoding failures.
An HTTP 4xx/5xx response can still return err == nil; for example, creating a vertex with a nonexistent label returns HTTP 400.
Check that response.StatusCode is in the 2xx range before reading result data. For Gremlin.Post, also check response.Data.Status.Code
for a successful Gremlin protocol status (2xx).
1resp, err := client.Gremlin.Post(
2 client.Gremlin.Post.WithGremlin("g.V().limit(3)"),
3)
4if err != nil {
5 log.Fatal(err)
6}
7defer resp.Body.Close()
8if resp.StatusCode < 200 || resp.StatusCode >= 300 {
9 log.Fatalf("HugeGraph returned HTTP %d", resp.StatusCode)
10}
11if resp.Data.Status.Code < 200 || resp.Data.Status.Code >= 300 {
12 log.Fatalf("Gremlin returned status %d: %s", resp.Data.Status.Code, resp.Data.Status.Message)
13}
14fmt.Println(resp.Data.Result.Data)
The Vertex operations take model.Vertex[any] values from the internal/model package. Go does not allow importing an internal package from another module, so at the moment the Vertex API can only be called from code inside the client module itself; its test file is also fully commented out.
For complete usage, see the tests in each API directory, such as version_test.go, gemlin_test.go, and vertexlabel_test.go.