Skip to content

This is the multi-page printable view of this section. .

Return to the regular view of this page.

HugeGraph Client

The Java and Go clients are maintained in the HugeGraph Toolchain repository, while the Python client is maintained in the HugeGraph-AI repository. Their installation methods and APIs differ; see the corresponding pages for details.

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        <!-- Select a released version from the download page -->
6        <version>1.7.0</version>
7    </dependency>    
8</dependencies>

Development versions of the client and server may differ. Check the corresponding release notes for compatibility 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.

4.5 More Information About Client-API

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.

Requirements

  • Python 3.9 or later
  • An accessible HugeGraph Server
  • uv (recommended) or pip

Installation

The package is currently published on PyPI as hugegraph-python:

1uv pip install hugegraph-python
2# Alternatively: pip install hugegraph-python

To use the latest repository code, sync the workspace from the root of the HugeGraph-AI repository:

1git clone https://github.com/apache/hugegraph-ai.git
2cd hugegraph-ai
3uv sync
4source .venv/bin/activate

Connect and Write Data

 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()

If GraphSpace is disabled in HugeGraph, omit graphspace. When it is enabled, pass the actual space name; the default space is usually DEFAULT.

Common Operations

Query the Schema

1schema = client.schema()
2print(schema.getPropertyKeys())
3print(schema.getVertexLabels())
4print(schema.getEdgeLabels())
5print(schema.getIndexLabels())

Update and Delete Graph Data

The graph API accepts dictionaries containing object properties:

1graph = client.graph()
2graph.appendVertex(person.id, {"birthDate": "1940-04-25"})
3graph.removeEdgeById(edge.id)
4graph.removeVertexById(person.id)
5graph.close()

Execute Gremlin

1gremlin = client.gremlin()
2result = gremlin.exec("g.V().limit(5)")
3print(result)

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

The source code and tests are under hugegraph-python-client/src/pyhugegraph/ and hugegraph-python-client/src/tests/.

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, vertices, edges, and Gremlin.

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. Leave the username and password empty when authentication is disabled. Current server graph resource paths include a graph space; use DEFAULT for the default space. Leaving GraphSpace empty applies only to older servers that still use the /graphs/{graph} path.

 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. Production code should normally pass an explicit configuration instead.

Available Entry Points

CommonClient currently exposes the following entry points:

Entry pointPurpose
Version()Query the server version
Schema()Query the complete schema
PropertykeyManage property keys
VertexLabelManage vertex labels
EdgeLabelManage edge labels
VertexCreate vertices in single or batch mode and update vertex properties
GremlinExecute Gremlin through GET or POST

For complete usage, see the tests in each API directory, such as version_test.go and vertexlabel_test.go.