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

<dependencies>
    <dependency>
        <groupId>org.apache.hugegraph</groupId>
        <artifactId>hugegraph-client</artifactId>
        <!-- Select a released version from the download page -->
        <version>1.7.0</version>
    </dependency>    
</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
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.hugegraph.driver.GraphManager;
import org.apache.hugegraph.driver.GremlinManager;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.driver.SchemaManager;
import org.apache.hugegraph.structure.constant.T;
import org.apache.hugegraph.structure.graph.Edge;
import org.apache.hugegraph.structure.graph.Path;
import org.apache.hugegraph.structure.graph.Vertex;
import org.apache.hugegraph.structure.gremlin.Result;
import org.apache.hugegraph.structure.gremlin.ResultSet;

public class SingleExample {

    public static void main(String[] args) throws IOException {
        // If connect failed will throw a exception.
        HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
                                                   "DEFAULT",
                                                   "hugegraph")
                                          .configUser("username", "password")
                                          // This is an example. In a production environment, secure credentials should be used.
                                          .build();

        SchemaManager schema = hugeClient.schema();

        schema.propertyKey("name").asText().ifNotExist().create();
        schema.propertyKey("age").asInt().ifNotExist().create();
        schema.propertyKey("city").asText().ifNotExist().create();
        schema.propertyKey("weight").asDouble().ifNotExist().create();
        schema.propertyKey("lang").asText().ifNotExist().create();
        schema.propertyKey("date").asDate().ifNotExist().create();
        schema.propertyKey("price").asInt().ifNotExist().create();

        schema.vertexLabel("person")
              .properties("name", "age", "city")
              .primaryKeys("name")
              .ifNotExist()
              .create();

        schema.vertexLabel("software")
              .properties("name", "lang", "price")
              .primaryKeys("name")
              .ifNotExist()
              .create();

        schema.indexLabel("personByCity")
              .onV("person")
              .by("city")
              .secondary()
              .ifNotExist()
              .create();

        schema.indexLabel("personByAgeAndCity")
              .onV("person")
              .by("age", "city")
              .secondary()
              .ifNotExist()
              .create();

        schema.indexLabel("softwareByPrice")
              .onV("software")
              .by("price")
              .range()
              .ifNotExist()
              .create();

        schema.edgeLabel("knows")
              .sourceLabel("person")
              .targetLabel("person")
              .properties("date", "weight")
              .ifNotExist()
              .create();

        schema.edgeLabel("created")
              .sourceLabel("person").targetLabel("software")
              .properties("date", "weight")
              .ifNotExist()
              .create();

        schema.indexLabel("createdByDate")
              .onE("created")
              .by("date")
              .secondary()
              .ifNotExist()
              .create();

        schema.indexLabel("createdByWeight")
              .onE("created")
              .by("weight")
              .range()
              .ifNotExist()
              .create();

        schema.indexLabel("knowsByWeight")
              .onE("knows")
              .by("weight")
              .range()
              .ifNotExist()
              .create();

        GraphManager graph = hugeClient.graph();
        Vertex marko = graph.addVertex(T.LABEL, "person", "name", "marko",
                                       "age", 29, "city", "Beijing");
        Vertex vadas = graph.addVertex(T.LABEL, "person", "name", "vadas",
                                       "age", 27, "city", "Hongkong");
        Vertex lop = graph.addVertex(T.LABEL, "software", "name", "lop",
                                     "lang", "java", "price", 328);
        Vertex josh = graph.addVertex(T.LABEL, "person", "name", "josh",
                                      "age", 32, "city", "Beijing");
        Vertex ripple = graph.addVertex(T.LABEL, "software", "name", "ripple",
                                        "lang", "java", "price", 199);
        Vertex peter = graph.addVertex(T.LABEL, "person", "name", "peter",
                                       "age", 35, "city", "Shanghai");

        marko.addEdge("knows", vadas, "date", "2016-01-10", "weight", 0.5);
        marko.addEdge("knows", josh, "date", "2013-02-20", "weight", 1.0);
        marko.addEdge("created", lop, "date", "2017-12-10", "weight", 0.4);
        josh.addEdge("created", lop, "date", "2009-11-11", "weight", 0.4);
        josh.addEdge("created", ripple, "date", "2017-12-10", "weight", 1.0);
        peter.addEdge("created", lop, "date", "2017-03-24", "weight", 0.2);

        GremlinManager gremlin = hugeClient.gremlin();
        System.out.println("==== Path ====");
        ResultSet resultSet = gremlin.gremlin("g.V().outE().path()").execute();
        Iterator<Result> results = resultSet.iterator();
        results.forEachRemaining(result -> {
            System.out.println(result.getObject().getClass());
            Object object = result.getObject();
            if (object instanceof Vertex) {
                System.out.println(((Vertex) object).id());
            } else if (object instanceof Edge) {
                System.out.println(((Edge) object).id());
            } else if (object instanceof Path) {
                List<Object> elements = ((Path) object).objects();
                elements.forEach(element -> {
                    System.out.println(element.getClass());
                    System.out.println(element);
                });
            } else {
                System.out.println(object);
            }
        });

        hugeClient.close();
    }
}
4.3.2 BatchExample
import java.util.ArrayList;
import java.util.List;

import org.apache.hugegraph.driver.GraphManager;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.driver.SchemaManager;
import org.apache.hugegraph.structure.graph.Edge;
import org.apache.hugegraph.structure.graph.Vertex;

public class BatchExample {

    public static void main(String[] args) {
        HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
                                                   "DEFAULT",
                                                   "hugegraph")
                                          .configUser("username", "password")
                                          // This is an example. In a production environment, secure credentials should be used.
                                          .build();

        SchemaManager schema = hugeClient.schema();

        schema.propertyKey("name").asText().ifNotExist().create();
        schema.propertyKey("age").asInt().ifNotExist().create();
        schema.propertyKey("lang").asText().ifNotExist().create();
        schema.propertyKey("date").asDate().ifNotExist().create();
        schema.propertyKey("price").asInt().ifNotExist().create();

        schema.vertexLabel("person")
              .properties("name", "age")
              .primaryKeys("name")
              .ifNotExist()
              .create();

        schema.vertexLabel("person")
              .properties("price")
              .nullableKeys("price")
              .append();

        schema.vertexLabel("software")
              .properties("name", "lang", "price")
              .primaryKeys("name")
              .ifNotExist()
              .create();

        schema.indexLabel("softwareByPrice")
              .onV("software").by("price")
              .range()
              .ifNotExist()
              .create();

        schema.edgeLabel("knows")
              .link("person", "person")
              .properties("date")
              .ifNotExist()
              .create();

        schema.edgeLabel("created")
              .link("person", "software")
              .properties("date")
              .ifNotExist()
              .create();

        schema.indexLabel("createdByDate")
              .onE("created").by("date")
              .secondary()
              .ifNotExist()
              .create();

        // get schema object by name
        System.out.println(schema.getPropertyKey("name"));
        System.out.println(schema.getVertexLabel("person"));
        System.out.println(schema.getEdgeLabel("knows"));
        System.out.println(schema.getIndexLabel("createdByDate"));

        // list all schema objects
        System.out.println(schema.getPropertyKeys());
        System.out.println(schema.getVertexLabels());
        System.out.println(schema.getEdgeLabels());
        System.out.println(schema.getIndexLabels());

        GraphManager graph = hugeClient.graph();

        Vertex marko = new Vertex("person").property("name", "marko")
                                           .property("age", 29);
        Vertex vadas = new Vertex("person").property("name", "vadas")
                                           .property("age", 27);
        Vertex lop = new Vertex("software").property("name", "lop")
                                           .property("lang", "java")
                                           .property("price", 328);
        Vertex josh = new Vertex("person").property("name", "josh")
                                          .property("age", 32);
        Vertex ripple = new Vertex("software").property("name", "ripple")
                                              .property("lang", "java")
                                              .property("price", 199);
        Vertex peter = new Vertex("person").property("name", "peter")
                                           .property("age", 35);

        Edge markoKnowsVadas = new Edge("knows").source(marko).target(vadas)
                                                .property("date", "2016-01-10");
        Edge markoKnowsJosh = new Edge("knows").source(marko).target(josh)
                                               .property("date", "2013-02-20");
        Edge markoCreateLop = new Edge("created").source(marko).target(lop)
                                                 .property("date",
                                                           "2017-12-10");
        Edge joshCreateRipple = new Edge("created").source(josh).target(ripple)
                                                   .property("date",
                                                             "2017-12-10");
        Edge joshCreateLop = new Edge("created").source(josh).target(lop)
                                                .property("date", "2009-11-11");
        Edge peterCreateLop = new Edge("created").source(peter).target(lop)
                                                 .property("date",
                                                           "2017-03-24");

        List<Vertex> vertices = new ArrayList<>();
        vertices.add(marko);
        vertices.add(vadas);
        vertices.add(lop);
        vertices.add(josh);
        vertices.add(ripple);
        vertices.add(peter);

        List<Edge> edges = new ArrayList<>();
        edges.add(markoKnowsVadas);
        edges.add(markoKnowsJosh);
        edges.add(markoCreateLop);
        edges.add(joshCreateRipple);
        edges.add(joshCreateLop);
        edges.add(peterCreateLop);

        vertices = graph.addVertices(vertices);
        vertices.forEach(vertex -> System.out.println(vertex));

        edges = graph.addEdges(edges, false);
        edges.forEach(edge -> System.out.println(edge));

        hugeClient.close();
    }
}

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.

The module lives in the hugegraph-ai repository under hugegraph-python-client/. The import name is pyhugegraph.

Requirements

  • Python 3.9 or later for the client itself. The HugeGraph-AI workspace requires Python 3.10 or later, and CI runs the 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:

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

The PyPI release lags behind the repository. In the source tree the distribution is declared as hugegraph-python-client and versioned with the rest of HugeGraph-AI, so install from source if you need the newest 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:

git clone https://github.com/apache/hugegraph-ai.git
cd hugegraph-ai
uv sync --extra python-client
source .venv/bin/activate

Connect and Write Data

from pyhugegraph.client import PyHugeClient

client = PyHugeClient(
    url="http://127.0.0.1:8080",
    graph="hugegraph",
    user="admin",
    pwd="admin",
    graphspace=None,
)

schema = client.schema()
schema.propertyKey("name").asText().ifNotExist().create()
schema.propertyKey("birthDate").asText().ifNotExist().create()
schema.vertexLabel("Person").properties("name", "birthDate") \
      .usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
schema.vertexLabel("Movie").properties("name") \
      .usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie") \
      .ifNotExist().create()

graph = client.graph()
person = graph.addVertex(
    "Person", {"name": "Al Pacino", "birthDate": "1940-04-25"}
)
movie = graph.addVertex("Movie", {"name": "The Godfather"})
edge = graph.addEdge("ActedIn", person.id, movie.id, {})

print(graph.getVertexById(person.id))
print(graph.getEdgeById(edge.id))
graph.close()

Client Parameters

PyHugeClient(url, graph, user, pwd, graphspace=None, timeout=None)

ParameterTypeDefaultDescription
urlstrrequiredBase URL of HugeGraph Server. If the value has no scheme, http:// is prepended, so 127.0.0.1:8080 also works.
graphstrrequiredGraph name. This is the second positional parameter.
userstrrequiredUsername, sent as HTTP basic auth.
pwdstrrequiredPassword, sent as HTTP basic auth.
graphspacestr or NoneNoneGraphSpace name. See below for how None is resolved.
timeouttuple[float, float] or NoneNone(connect, read) timeouts in seconds. None becomes (0.5, 15.0).

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.

AccessorManagerCovers
client.schema()SchemaManagerProperty keys, vertex labels, edge labels, index labels
client.graph()GraphManagerVertex and edge CRUD, batch writes, paging
client.gremlin()GremlinManagerGremlin execution
client.graphs()GraphsManagerGraph list, graph info, config, clear data
client.traverser()TraverserManagerTraversal and path algorithms
client.variable()VariableManagerGraph variables
client.task()TaskManagerAsync task list, query, cancel, delete
client.auth()AuthManagerUsers, groups, targets, belongs, accesses
client.metrics()MetricsManagerServer metrics
client.version()VersionManagerServer version

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.

schema = client.schema()

# Property keys: asText/asInt/asLong/asFloat/asDouble/asBool/asByte/asBlob/asDate/asObject
# cardinality: valueSingle/valueList/valueSet
# aggregation: calcMax/calcMin/calcSum/calcOld
schema.propertyKey("age").asInt().valueSingle().ifNotExist().create()

# Vertex labels: useAutomaticId/useCustomizeStringId/useCustomizeNumberId/usePrimaryKeyId
schema.vertexLabel("person").properties("name", "age", "city") \
      .primaryKeys("name").nullableKeys("city").ifNotExist().create()

# Edge labels: link() is shorthand for sourceLabel() plus targetLabel()
schema.edgeLabel("knows").link("person", "person").multiTimes() \
      .properties("date", "city").sortKeys("date").nullableKeys("city") \
      .ifNotExist().create()

# Index labels: onV/onE, then secondary/range/search/shard/unique
schema.indexLabel("personByCity").onV("person").by("city") \
      .secondary().ifNotExist().create()

Query the Schema

schema = client.schema()
print(schema.getSchema())            # whole schema, format defaults to "json"
print(schema.getPropertyKeys())
print(schema.getVertexLabels())
print(schema.getEdgeLabels())
print(schema.getIndexLabels())

# Single definitions
print(schema.getPropertyKey("name"))
print(schema.getVertexLabel("person"))
print(schema.getEdgeLabel("knows"))
print(schema.getIndexLabel("personByCity"))

# Edge label links, formatted as "Person--ActedIn-->Movie"
print(schema.getRelations())

Read, Update and Delete Graph Data

The graph API takes property dictionaries, not chained property builders:

graph = client.graph()
graph.appendVertex(person.id, {"birthDate": "1940-04-25"})    # add properties
graph.eliminateVertex(person.id, {"birthDate": "1940-04-25"}) # drop properties
graph.appendEdge(edge.id, {"city": "Beijing"})
graph.eliminateEdge(edge.id, {"city": "Beijing"})
graph.removeEdgeById(edge.id)
graph.removeVertexById(person.id)
graph.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.

graph = client.graph()
vertices = graph.addVertices([
    ("person", {"name": "Alice", "age": 20}),
    ("person", {"name": "Bob", "age": 23}),
])
edges = graph.addEdges([
    ("knows", vertices[0].id, vertices[1].id, "person", "person", {"date": "2012-01-10"}),
])

Paging and Conditional Queries

graph = client.graph()

# Returns (vertices, next_page); pass next_page back in to continue
vertices, next_page = graph.getVertexByPage("person", limit=10)
vertices, next_page = graph.getVertexByPage("person", limit=10, page=next_page)

# Server-side property predicates
older = graph.getVertexByCondition("person", properties={"age": "P.gt(29)"})

# Edges by page. When vertex_id is given, direction is required
edges, next_page = graph.getEdgeByPage(label="knows", limit=10)
edges, next_page = graph.getEdgeByPage(vertex_id=person.id, direction="OUT", limit=10)

# Batch lookup by id
graph.getVerticesById([v1.id, v2.id])
graph.getEdgesById([e1.id, e2.id])

Execute Gremlin

gremlin = client.gremlin()
result = gremlin.exec("g.V().limit(5)")
print(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.

traverser = client.traverser()

traverser.k_out(marko_id, 2)
traverser.k_neighbor(marko_id, 2)
traverser.same_neighbors(marko_id, josh_id)
traverser.jaccard_similarity(marko_id, josh_id)
traverser.shortest_path(marko_id, ripple_id, 3)
traverser.all_shortest_paths(marko_id, ripple_id, 3)
traverser.weighted_shortest_path(marko_id, ripple_id, "weight", 3)
traverser.single_source_shortest_path(marko_id, 2)
traverser.multi_node_shortest_path([marko_id, josh_id], max_depth=2)
traverser.paths(marko_id, josh_id, 2)
traverser.crosspoints(marko_id, josh_id, 2)
traverser.rings(marko_id, 3)
traverser.rays(marko_id, 2)
traverser.vertices(marko_id)
traverser.edges(edge_id)

The POST-based variants take request bodies: advanced_paths, customized_paths, template_paths, customized_crosspoints and fusiform_similarity.

Graph Variables

variable = client.variable()
variable.set("owner", "mary")
print(variable.get("owner"))
print(variable.all())
variable.remove("owner")

Async Tasks

task = client.task()
print(task.list_tasks(status="success", limit=10))
print(task.get_task(task_id))
task.cancel_task(task_id)
task.delete_task(task_id)

Server Metrics and Graph Info

metrics = client.metrics()
metrics.get_all_basic_metrics()
metrics.get_gauges_metrics()
metrics.get_counters_metrics()
metrics.get_histograms_metrics()
metrics.get_meters_metrics()
metrics.get_timers_metrics()
metrics.get_statistics_metrics()
metrics.get_system_metrics()
metrics.get_backend_metrics()

graphs = client.graphs()
graphs.get_all_graphs()
graphs.get_version()
graphs.get_graph_info()
graphs.get_graph_config()
graphs.clear_graph_all_data()   # deletes every vertex, edge and schema entry

print(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.

auth = client.auth()

user = auth.create_user("test_user", "password")
auth.modify_user(user["id"], user_email="hugegraph@apache.org")
auth.get_user(user["id"])
auth.list_users(limit=10)
auth.delete_user(user["id"])

group = auth.create_group("test_group", "read only")
auth.modify_group(group["id"], group_description="updated")
auth.list_groups()
auth.delete_group(group["id"])

target = auth.create_target("target1", "hugegraph", "127.0.0.1:8080", [])
auth.update_target(target["id"], "target1", "hugegraph", "127.0.0.1:8080", [])
auth.list_targets()
auth.delete_target(target["id"])

belong = auth.create_belong(user["id"], group["id"])
auth.update_belong(belong["id"], "description")
auth.list_belongs()
auth.delete_belong(belong["id"])

access = auth.grant_accesses(group["id"], target["id"], "READ")
auth.modify_accesses(access["id"], "description")
auth.list_accesses()
auth.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:

ExceptionRaised when
NotAuthorizedErrorThe server answers 401
NotFoundErrorThe server answers 404, or a required argument is missing
ServerErrorAny other non-2xx response, with the server message attached
ResponseParseErrorA successful response cannot be parsed into the expected shape
ServiceUnavailableErrorThe server reports ServiceUnavailableException
InvalidParameterError, CreateError, RemoveError, UpdateError, DataFormatErrorRaised by individual builders and structures

Request and response bodies are logged with password, token and secret values redacted.

from pyhugegraph.utils.exceptions import NotFoundError

try:
    graph.getVertexById("no-such-id")
except NotFoundError:
    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:

./style/code_format_and_analysis.sh

Run the tests the same way CI does:

# Unit and contract tests, no server needed
uv run pytest hugegraph-python-client/src/tests -m "unit or contract"

# Integration tests against a running server
HUGEGRAPH_URL=http://127.0.0.1:8080 \
HUGEGRAPH_GRAPH=hugegraph \
HUGEGRAPH_USER=admin \
HUGEGRAPH_PASSWORD=admin \
uv 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:

go 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.

package main

import (
	"fmt"
	"log"

	hugegraph "github.com/apache/hugegraph-toolchain/hugegraph-client-go"
)

func main() {
	client, err := hugegraph.NewCommonClient(hugegraph.Config{
		Host:       "127.0.0.1",
		Port:       8080,
		GraphSpace: "DEFAULT",
		Graph:      "hugegraph",
		Username:   "",
		Password:   "",
	})
	if err != nil {
		log.Fatal(err)
	}

	response, err := client.Version()
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()

	fmt.Println(response.Versions.Version)
}

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:

FieldTypeDescription
HoststringHugeGraph Server IP address. Host names are rejected.
PortintHugeGraph Server REST port, 1 to 65535
GraphSpacestringGraph space; only used by the Vertex API and the default Gremlin aliases. Set an empty string when not needed.
GraphstringGraph name configured on the server
UsernamestringServer username; empty string when authentication is disabled
PasswordstringServer password; empty string when authentication is disabled
Transporthttp.RoundTripperCustom HTTP transport; http.DefaultTransport when nil
Loggerhgtransport.LoggerRequest/response logger; no logging when nil

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.

import (
	"os"

	hugegraph "github.com/apache/hugegraph-toolchain/hugegraph-client-go"
	"github.com/apache/hugegraph-toolchain/hugegraph-client-go/hgtransport"
)

client, err := hugegraph.NewCommonClient(hugegraph.Config{
	Host:  "127.0.0.1",
	Port:  8080,
	Graph: "hugegraph",
	Logger: &hgtransport.ColorLogger{
		Output:             os.Stdout,
		EnableRequestBody:  true,
		EnableResponseBody: true,
	},
})

Available Entry Points

CommonClient currently exposes the following entry points:

Entry pointPurpose
Version()Query the server version
Schema()Query the complete schema
PropertykeyCreate, GetAll, GetByName, UpdateUserdata, DeleteByName
VertexLabelCreate, GetAll, GetByName, UpdateUserdata, DeleteByName
EdgeLabelCreate, GetAll, DeleteByName
VertexCreate, BatchCreate, UpdateProperties (with WithAction: append or eliminate)
GremlinGet and Post. Post defaults language to gremlin-groovy, fills the graph/g aliases from GraphSpace and Graph, and returns the parsed result in Data. Get only returns the status code and prints the raw response to stdout.

Each operation takes functional options named With... on the operation itself, for example client.Gremlin.Post.WithGremlin(...) or client.Propertykey.GetByName.WithName(...).

resp, err := client.Gremlin.Post(
	client.Gremlin.Post.WithGremlin("g.V().limit(3)"),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(resp.StatusCode, resp.Data.Status.Code, 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.