Skip to content

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

Return to the regular view of this page.

HugeGraph Client

1 - HugeGraph-Java-Client

1 Overview Of Hugegraph

HugeGraph-Client sends HTTP request to HugeGraph-Server to get and parse the execution result of Server. We support HugeGraph-Client for Java/Go/Python language. You can use Client-API to write code to operate HugeGraph, such as adding, deleting, modifying, and querying schema and graph data, or executing gremlin statements.

HugeGraph client SDK tool based on Go language (version >=1.2.0)

2 What You Need

  • Java 11 (also supports Java 8)
  • Maven 3.5+

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        <!-- Update to the latest release version -->
6        <version>1.5.0</version>
7    </dependency>    
8</dependencies>

Note: The versions of all graph components remain consistent

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

The hugegraph-python-client is a Python client/SDK for HugeGraph Database.

It is used to define graph structures, perform CRUD operations on graph data, manage schemas, and execute Gremlin queries. Both the hugegraph-llm and hugegraph-ml modules depend on this foundational library.

Installation

Install the released package (Stable)

To install the hugegraph-python-client, you can use uv/pip or source code building:

1# uv is optional, you can use pip directly
2uv pip install hugegraph-python # Note: may not the latest version, recommend to install from source
3# WIP: we will use 'hugegraph-python-client' as the package name soon

Install from Source (Latest Code)

To install from the source, clone the repository and install the required dependencies:

1git clone https://github.com/apache/incubator-hugegraph-ai.git
2cd incubator-hugegraph-ai/hugegraph-python-client
3
4# Normal install 
5uv pip install .
6
7# (Optional) install the devel version
8uv pip install -e .

Usage

Defining Graph Structures

You can use the hugegraph-python-client to define graph structures. Below is an example of how to define a graph:

 1from pyhugegraph.client import PyHugeClient
 2
 3# Initialize the client
 4# For HugeGraph API version ≥ v3: (Or enable graphspace function)  
 5# - The 'graphspace' parameter becomes relevant if graphspaces are enabled.(default name is 'DEFAULT')
 6# - Otherwise, the graphspace parameter is optional and can be ignored. 
 7client = PyHugeClient("127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph", graphspace="DEFAULT")
 8
 9''''
10Note:
11Could refer to the official REST-API doc of your HugeGraph version for accurate details.
12If some API is not as expected, please submit a issue or contact us.
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# Init Graph
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 Management

The hugegraph-python-client provides comprehensive schema management capabilities.

Define Property Keys

1# Define a property key
2client.schema().propertyKey('name').dataType('STRING').cardinality('SINGLE').create()

Define Vertex Labels

1# Define a vertex label
2client.schema().vertexLabel('person').properties('name', 'age').primaryKeys('name').create()

Define Edge Labels

1# Define an edge label
2client.schema().edgeLabel('knows').sourceLabel('person').targetLabel('person').properties('since').create()

Define Index Labels

1# Define an index label
2client.schema().indexLabel('personByName').onV('person').by('name').secondary().create()

CRUD Operations

The client allows you to perform CRUD operations on the graph data. Below are examples of how to create, read, update, and delete vertices and edges:

Create Vertices and Edges

1# Create vertices
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# Create an edge
6client.graph().addEdge(v1, 'knows', v2).property('since', '2020').create()

Read Vertices and Edges

1# Get a vertex by ID
2vertex = client.graph().getVertexById(v1.id)
3print(vertex)
4
5# Get an edge by ID
6edge = client.graph().getEdgeById(edge.id)
7print(edge)

Update Vertices and Edges

1# Update a vertex
2client.graph().updateVertex(v1.id).property('age', 30).update()
3
4# Update an edge
5client.graph().updateEdge(edge.id).property('since', '2021').update()

Delete Vertices and Edges

1# Delete a vertex
2client.graph().deleteVertex(v1.id)
3
4# Delete an edge
5client.graph().deleteEdge(edge.id)

Execute Gremlin Queries

The client also supports executing Gremlin queries:

1# Execute a Gremlin query
2g = client.gremlin()
3res = g.exec("g.V().limit(5)")
4print(res)

Other info is under 🚧 (Welcome to add more docs for it, users could refer java-client-doc for similar usage)

Contributing

  • Welcome to contribute to hugegraph-python-client. Please see the Guidelines for more information.
  • Code format: Please run ./style/code_format_and_analysis.sh to format your code before submitting a PR.

Thank you to all the people who already contributed to hugegraph-python-client!

Contact Us

  • GitHub Issues: Feedback on usage issues and functional requirements (quick response)

3 - HugeGraph Go Client Quick Start

A HugeGraph Client SDK tool based on the Go language.

Software Architecture

(Software architecture description)

Installation Tutorial

1go get github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go

Implemented APIs

APIDescription
schemaGet schema information
versionGet version information

Usage Instructions

1. Initialize the Client

 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: "", // Fill in the username according to the actual situation
17		Password: "", // Fill in the password according to the actual situation
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	// Use the client for operations...
30	_ = client // Avoid "imported and not used" error
31}

2. Get HugeGraph Version

Get Version Information Using 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 initializes and returns a HugeGraph client instance
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	// Assume client has a Version method that returns version information and an error
35	// res, err := client.Version() // Actual call
36	// Simulate return, as the client.Version() return type in the original README does not fully match the usage here
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 // Assume there is a Body to close, adjust according to the actual SDK
45	}
46
47	// Simulate API call and return
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", // Example version
56			Core:    "1.0.0",
57			Gremlin: "3.x.x",
58			API:     "v1",
59		},
60	}
61	// err := error(nil) // Assume no error
62
63	// if err != nil {
64	// 	log.Fatalf("Error getting the response: %s\n", err)
65	// }
66	// defer res.Body.Close() // If there is a Body, it needs to be closed
67
68	fmt.Println(res.Versions)
69	fmt.Println(res.Versions.Version)
70}
71
72func main() {
73	getVersion()
74}

Structure of the Return Value

 1package main
 2
 3// VersionResponse defines the structure returned by the version 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}

API Reference