This is the multi-page printable view of this section. Click here to print.
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
<dependencies>
<dependency>
<groupId>org.apache.hugegraph</groupId>
<artifactId>hugegraph-client</artifactId>
<!-- Update to the latest release version -->
<version>1.5.0</version>
</dependency>
</dependencies>
Note: The versions of all graph components remain consistent
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",
"hugegraph")
.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) {
// If connect failed will throw a exception.
HugeClient hugeClient = HugeClient.builder("http://localhost:8080",
"hugegraph")
.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
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:
# uv is optional, you can use pip directly
uv pip install hugegraph-python # Note: may not the latest version, recommend to install from source
# 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:
git clone https://github.com/apache/incubator-hugegraph-ai.git
cd incubator-hugegraph-ai/hugegraph-python-client
# Normal install
uv pip install .
# (Optional) install the devel version
uv 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:
from pyhugegraph.client import PyHugeClient
# Initialize the client
# For HugeGraph API version ≥ v3: (Or enable graphspace function)
# - The 'graphspace' parameter becomes relevant if graphspaces are enabled.(default name is 'DEFAULT')
# - Otherwise, the graphspace parameter is optional and can be ignored.
client = PyHugeClient("127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph", graphspace="DEFAULT")
''''
Note:
Could refer to the official REST-API doc of your HugeGraph version for accurate details.
If some API is not as expected, please submit a issue or contact us.
''''
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()
print(schema.getVertexLabels())
print(schema.getEdgeLabels())
print(schema.getRelations())
# Init Graph
g = client.graph()
v_al_pacino = g.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"})
v_robert = g.addVertex("Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"})
v_godfather = g.addVertex("Movie", {"name": "The Godfather"})
v_godfather2 = g.addVertex("Movie", {"name": "The Godfather Part II"})
v_godfather3 = g.addVertex("Movie", {"name": "The Godfather Coda The Death of Michael Corleone"})
g.addEdge("ActedIn", v_al_pacino.id, v_godfather.id, {})
g.addEdge("ActedIn", v_al_pacino.id, v_godfather2.id, {})
g.addEdge("ActedIn", v_al_pacino.id, v_godfather3.id, {})
g.addEdge("ActedIn", v_robert.id, v_godfather2.id, {})
res = g.getVertexById(v_al_pacino.id).label
print(res)
g.close()
Schema Management
The hugegraph-python-client
provides comprehensive schema management capabilities.
Define Property Keys
# Define a property key
client.schema().propertyKey('name').dataType('STRING').cardinality('SINGLE').create()
Define Vertex Labels
# Define a vertex label
client.schema().vertexLabel('person').properties('name', 'age').primaryKeys('name').create()
Define Edge Labels
# Define an edge label
client.schema().edgeLabel('knows').sourceLabel('person').targetLabel('person').properties('since').create()
Define Index Labels
# Define an index label
client.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
# Create vertices
v1 = client.graph().addVertex('person').property('name', 'John').property('age', 29).create()
v2 = client.graph().addVertex('person').property('name', 'Jane').property('age', 25).create()
# Create an edge
client.graph().addEdge(v1, 'knows', v2).property('since', '2020').create()
Read Vertices and Edges
# Get a vertex by ID
vertex = client.graph().getVertexById(v1.id)
print(vertex)
# Get an edge by ID
edge = client.graph().getEdgeById(edge.id)
print(edge)
Update Vertices and Edges
# Update a vertex
client.graph().updateVertex(v1.id).property('age', 30).update()
# Update an edge
client.graph().updateEdge(edge.id).property('since', '2021').update()
Delete Vertices and Edges
# Delete a vertex
client.graph().deleteVertex(v1.id)
# Delete an edge
client.graph().deleteEdge(edge.id)
Execute Gremlin Queries
The client also supports executing Gremlin queries:
# Execute a Gremlin query
g = client.gremlin()
res = g.exec("g.V().limit(5)")
print(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
go get github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go
Implemented APIs
API | Description |
---|---|
schema | Get schema information |
version | Get version information |
Usage Instructions
1. Initialize the Client
package main
import (
"log"
"os"
"github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go"
"github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go/hgtransport"
)
func main() {
client, err := hugegraph.NewCommonClient(hugegraph.Config{
Host: "127.0.0.1",
Port: 8080,
Graph: "hugegraph",
Username: "", // Fill in the username according to the actual situation
Password: "", // Fill in the password according to the actual situation
Logger: &hgtransport.ColorLogger{
Output: os.Stdout,
EnableRequestBody: true,
EnableResponseBody: true,
},
})
if err != nil {
log.Fatalf("Error creating the client: %s\n", err)
}
// Use the client for operations...
_ = client // Avoid "imported and not used" error
}
2. Get HugeGraph Version
Get Version Information Using SDK
package main
import (
"fmt"
"log"
"os"
"github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go"
"github.com/apache/incubator-hugegraph-toolchain/hugegraph-client-go/hgtransport"
)
// initClient initializes and returns a HugeGraph client instance
func initClient() *hugegraph.CommonClient {
client, err := hugegraph.NewCommonClient(hugegraph.Config{
Host: "127.0.0.1",
Port: 8080,
Graph: "hugegraph",
Username: "",
Password: "",
Logger: &hgtransport.ColorLogger{
Output: os.Stdout,
EnableRequestBody: true,
EnableResponseBody: true,
},
})
if err != nil {
log.Fatalf("Error creating the client: %s\n", err)
}
return client
}
func getVersion() {
client := initClient()
// Assume client has a Version method that returns version information and an error
// res, err := client.Version() // Actual call
// Simulate return, as the client.Version() return type in the original README does not fully match the usage here
type VersionInfo struct {
Versions struct {
Version string `json:"version"`
Core string `json:"core"`
Gremlin string `json:"gremlin"`
API string `json:"api"`
} `json:"versions"`
// Body io.ReadCloser // Assume there is a Body to close, adjust according to the actual SDK
}
// Simulate API call and return
res := &VersionInfo{
Versions: struct {
Version string `json:"version"`
Core string `json:"core"`
Gremlin string `json:"gremlin"`
API string `json:"api"`
}{
Version: "1.0.0", // Example version
Core: "1.0.0",
Gremlin: "3.x.x",
API: "v1",
},
}
// err := error(nil) // Assume no error
// if err != nil {
// log.Fatalf("Error getting the response: %s\n", err)
// }
// defer res.Body.Close() // If there is a Body, it needs to be closed
fmt.Println(res.Versions)
fmt.Println(res.Versions.Version)
}
func main() {
getVersion()
}
Structure of the Return Value
package main
// VersionResponse defines the structure returned by the version API
type VersionResponse struct {
Versions struct {
Version string `json:"version"` // hugegraph version
Core string `json:"core"` // hugegraph core version
Gremlin string `json:"gremlin"` // hugegraph gremlin version
API string `json:"api"` // hugegraph api version
} `json:"versions"`
}