Download iGraph SDK for Java
iGraph SDK for Java allows Java developers to easily integrate Graph Compute with Java programs. You can add the SDK as a dependency to your Maven project. You can also download the installation package of the SDK to a local directory. iGraph SDK for Java supports Java 2 Platform, Standard Edition (J2SE) 8.0 and later.
Use iGraph SDK for Java
To use iGraph SDK for Java, perform the following steps:
Step 1: Create an Alibaba Cloud account
We recommend that you complete real-name verification at your earliest opportunity. Otherwise, you cannot use some Alibaba Cloud services.
Step 2: Obtain the password for accessing your Graph Compute instance
Log on to the Graph Compute console. In the left-side navigation pane, click Instances. Click the instance that you want to use. On the instance details page, you can view the username and reset the password in the API Information section. The username and password are configured when you purchase the instance. Use the username and password to access the Graph Compute instance.
If you forget your password, you can click Reset Password to reset your password.
Step 3: Install a Java development environment
iGraph SDK for Java supports J2SE 8.0 and later. You can visit the Java official website to download and install J2SE.
Step 4: Install iGraph SDK for Java
We recommend that you import the latest version of the SDK by using Apache Maven. You can add the following dependency to your Maven project:
<dependency>
<groupId>com.aliyun.igraph</groupId>
<artifactId>aliyun-sdk-igraph</artifactId>
<version>{lastest-sdk-version}</version>
</dependency>Step 5: Use iGraph SDK for Java
The following procedure shows the main steps to use iGraph SDK for Java:
Configure initialization parameters and create a
clientinstance in the same way that you use an open source Gremlin client. You must specify theendpointin addition to the username and password for accessing your Graph Compute instance.Compose the statement to query, update, or delete data.
Call the submit method to send a request to query, update, or delete data. Then, handle the response or any exceptions.
Configure parameters
Parameter description
Parameter | Type | Description |
src | String | The custom scenario name. You can specify a custom scenario name as a specific identifier of the source data. This helps you identify and troubleshoot issues with ease. |
endpoint | String | The endpoint of the Graph Compute instance in which you want to query or update data. |
userName | String | The username that is used to access the Graph Compute instance. |
userPasswd | String | The password that is used to access the Graph Compute instance. |
maxConnPerRoute | int | The maximum number of connections to a single HTTP server. We recommend that you set this parameter to 8. |
maxConnTotal | int | The maximum number of connections to all HTTP servers. We recommend that you set this parameter to 2000. If an error occurs because the number of connections exceeds the maximum value, you can raise the limit. |
connectionRequestTimeout | int | The timeout period of a connection request. Unit: millisecond. |
socketTimeout | int | The Netty-related parameter. Set this parameter to the same value as that of the connectionRequestTimeout parameter. |
connectTimeout | int | The Netty-related parameter. Set this parameter to the same value as that of the connectionRequestTimeout parameter. |
retryTimes | int | The maximum number of retries that the SDK makes if a timeout or an exception occurs. We recommend that you set this parameter to 3. |
Initialize an SDK client
We recommend that you create and reuse a
clientobject to enhance the reusability of the connection pool.
// Configure the client.
Cluster.Builder builder = Cluster.build();
// Required. Specify the endpoint, username, and password.
builder.addContactPoint("your_endpoint")
.userName("your_user_name")
.userPasswd("your_user_passwd");
// Optional. If you do not specify the following parameters, the client uses the default values.
builder.src("your_src")
.socketTimeout(100)
.connectTimeout(100)
.connectionRequestTimeout(100)
.maxConnTotal(10000)
.maxConnPerRoute(5000)
.retryTimes(3);
Cluster cluster = builder.create();
Client client = cluster.connect();Use the Gremlin syntax to query, update, and delete data
For more information about the syntax and operators of Gremlin, see Overview.
For more information about the compatibility with Gremlin, see Compatibility with Gremlin steps.
Query data
Use a GraphTraversal object to construct a query
In the following sample code, a simple one-level deep query is performed.
To use a GraphTraversal object to construct a query, you must add
import static com.aliyun.iGraph.client.gremlin.gremlin_api.GraphTraversalSource.gto your project code. iGraph allows you to specify graph names to implement a multi-graph query.The client API performs simple syntax verification on each step.
// Complete a query and display the result.
GraphTraversal gt = g("your_graph_name").V("your_id").hasLabel("your_label");
// Call the submit method to submit the query and obtain a ResultSet.
ResultSet resultSet = client.submit(gt);
List<Result> resultList = resultSet.all().join();
resultList.forEach(p -> System.out.println(p.getObject()));
// Close the client.
cluster.close();Initiate a plaintext query
You can directly initiate a query in plaintext.
You can define a map on the client and replace the variables such as keys in a Gremlin query with the values in the map. The iGraph server can cache the syntax tree generated for Gremlin queries to decrease the response time of the client by 4% to 8%.
Note:
This optimization supports only queries that are composed of Gremlin steps such as
g(),E(),V(),filter(),fields(),order(),range(),join(), andalias().You can replace only the IDs in
V() or E()steps, the expressions infilter()steps, and the limits of the returned vertices inrange()steps.The name of a variable must start with
$. Examples:$para1and$1.
You can also use a
RequestOptionobject to define custom parameters.
// Initiate a plaintext query.
String gt = "g(\"your_graph_name\").V(\"your_id\").hasLabel(\"your_label\")";
ResultSet resultSet = client.submit(gt);
// Use a map to replace variables in a plaintext query.
String gt = "g(\"your_graph_name\").V($1).hasLabel(\"your_label\")";
Map<String, Object> bind = new HashMap<>();
bind.put("$1", "1");
ResultSet resultSet = client.submit(gt, bind);
// Use a RequestOptions object to define custom parameters.
String gt = "g(\"your_graph_name\").V($1).hasLabel(\"your_label\")";
RequestOptions requestOptions = RequestOptions.build()
.src("your_src")
.timeout(1000)
.retryTimes(2)
.addParameter("$1", "1")
.create();
ResultSet resultSet = client.submit(gt,requestOptions);Update and delete data
iGraph allows you to insert or delete data by using the Gremlin syntax. However, you cannot update the vertices involved in a query.
You must specify all properties of a vertex or an edge when you update the vertex or edge.
You need to only specify the primary key (pkey) when you delete data.
The information about the request is saved in the returned
ResultSet.
// Add a vertex with only one property.
GraphTraversal gt = g("your_graph_name").addV("your_label").property("pkey", "pk_value").property("value", "0.5");
ResultSet resultSet = client.submit(gt);
List<Result> resultList = resultSet.all().join();
resultList.forEach(p -> System.out.println(p.getObject()));
// Delete a vertex.
gt = g("your_graph_name").V("pk_value").hasLabel("your_label").drop();
resultSet = client.submit(gt);
resultList = resultSet.all().join();
resultList.forEach(p -> System.out.println(p.getObject()));More examples
// Add an edge with two properties.
gt = g("graph_name").addE("label").property("pkey", "pk_value").property("skey","sk_value").property("value1", "abc").property("value2", "0.5");
// Delete the edge with the specified pkey. If the pkey is assigned to multiple edges, all the edges are deleted.
gt = g("graph_name").E("pk1").hasLabel("label").drop();
// Delete the edge with the specified pkey and secondary key (skey).
gt = g("graph_name").E("pk1:sk1").hasLabel("label").drop();Parse query results
ResultSet
A
ResultSetis returned for each query. The methods for obtaining results are the same as those in TinkerPop.
// Obtain all the results of the request. All the results are returned to iGraph SDK at a time. We recommend that you call this method to obtain the results.
CompletableFuture<List<Result>> futureList = resultSet.all();
// Obtain some results of the request.
CompletableFuture<List<Result>> futureList = resultSet.some(int i);
// Obtain one result of the request.
Result result = resultSet.one();Resultrepresents a result. You can call a specific method to obtain the value of a result based on the data type of the result. The following table describes the methods.
Method | Description |
String getString() | Returns a value of the string type. |
int getInt() | Returns a value of the int type. |
byte getByte() | Returns a value of the byte type. |
short getShort() | Returns a value of the short type. |
long getLong() | Returns a value of the long type. |
float getFloat() | Returns a value of the float type. |
double getDouble() | Returns a value of the double type. |
boolean getBoolean() | Returns a value of the boolean type. |
Vertex getVertex() | Returns a vertex. |
Edge getEdge() | Returns an edge. |
Element getElement() | Returns an element, which can be a vertex or an edge. |
Path getPath() | Returns a path. |
<V> Property<V> getProperty() | Returns a property. |
<V> VertexProperty<V> getVertexProperty() | Returns a property of a vertex. |
<T> T get(final Class<? extends T> clazz) | Returns a generic value, which can be of an extended type of iGraph. |
Object getObject() | Returns an object. You can call this method if you do not know the data type of the result. |
You can call the
<T> T get(final Class<? extend T> clazz)method to obtain values of special data types such as multi-value types, map, set, and BulkSet. Examples:
// Returns a list.
List<Result> vecValue = result.get(List.class);
// Returns a map entry.
Map.Entry<Result, Result> entry = result.get(Map.Entry.class);
// Returns a set.
Set<Result> setValue = result.get(Set.class);
// Returns a map.
Map<Object, Result> mapValue = result.get(Map.class);
// Returns a BulkSet.
BulkSet bulkSet = result.get(BulkSet.class);
Map<Result, Long> value = bulkSet.getValue();
// Returns a value of a multi-value type.
List<Byte> multiValues = result.get(MultiByte.class).getValue();
List<Short> multiValues = result.get(MultiShort.class).getValue();
List<Integer> multiValues = result.get(MultiInt.class).getValue();
List<Long> multiValues = result.get(MultiLong.class).getValue();
List<Integer> multiValues = result.get(MultiUInt8.class).getValue();
List<Integer> multiValues = result.get(MultiUInt16.class).getValue();
List<Long> multiValues = result.get(MultiUInt32.class).getValue();
List<Long> multiValues = result.get(MultiUInt64.class).getValue();
List<Float> multiValues = result.get(MultiFloat.class).getValue();
List<Double> multiValues = result.get(MultiDouble.class).getValue();
List<String> values = result.get(MultiString.class).getValue();Path
Pathrepresents one or multiple paths in a graph. A path records the information about the vertices or edges involved in a multi-hop query. The following table describes the methods that are provided byPath.You can call the
objects()method to obtain the elements in a path.
Method | Description |
int size() | Returns the number of elements in a path. |
boolean isEmpty() | Checks whether a path is empty. |
<A> A head() | Returns the start element of a path. |
<A> A get(String label) | Returns an element or a list of the elements with a specific label. |
<A> A get(Pop pop, String label) | Returns some of the elements or a part of the list of the elements with a specific label. |
<A> A get(int index) | Returns an element with a specific index in a path. |
boolean hasLabel(String label) | Checks whether a path contains elements with a specific label. |
List<Object> objects() | Returns a list of the elements in a path. |
List<Set<String>> labels() | Returns a list of the labels in a path. |
Path clone() | Clones a path. |
boolean isSimple() | Checks whether a path is a simple path. |
Iterator<Object> iterator() | Returns the iterator of a path. |
void forEach(BiConsumer<Object, Set<String>> consumer) | A generic method. |
Stream<Pair<Object, Set<String>>> stream() | Returns the traversal stream of a path. |
boolean popEquals(Pop pop, Object other) | Checks whether two paths are equal. |
Path subPath(String fromLabel, String toLabel) | Returns a sub-path. |
Vertex and Egde
VertexorEdgerepresents a vertex or an edge. A vertex or an edge is an element in iGraph. The following table describes the methods that are provided by Vertex and Edge.Method
Description
String label()
Returns a label of an element.
Set<String> keys()
Returns the keys of the properties of an element.
<V> Property<V> property(String key)
Returns the property with a specific key.
<V> V value(String key)
Returns the property value of a specific key.
<V> Iterator<V> values(String... propertyKeys)
Returns the values of properties with specific keys.
<V> Iterator<VertexProperty<V>> properties(final String... propertyKeys)
Returns the properties with specific keys.
You can call the
value(String key)method to obtain property values of multiple data types based on the specific query.
Property and VertexProperty
Both
PropertyandVertexPropertyrepresents a property. You can call theVertex.property(String key)method to obtain aVertexPropertyobject. The following table describes the methods that are provided by Property and VertexProperty.Method
Description
String key()
Returns the key of a property.
V value()
Returns the value of a property.
boolean isPresent()
Checks whether a property exists.
void ifPresent(final Consumer<? super V> consumer)
Assigns the value of a property to a Consumer object if the property exists.
V orElse(final V otherValue)
Returns the value of a property if the property exists. Otherwise, returns the value specified by the otherValue parameter.
V orElseGet(final Supplier<? extends V> valueSupplier)
Returns the value of a property if the property exists. Otherwise, returns the value of a Supplier object.
<E extends Throwable> V orElseThrow(final Supplier<? extends E> exceptionSupplier) throws E
Returns the value of a property if the property exists. Otherwise, throws the exception specified by a Supplier object.
Element element()
Returns the element to which a property belongs. The property must be a property that is queried from an element.
You can call the
value()method to obtain property values of multiple data types based on the specific query