iGraph SDK for Java

Updated at:

Download links

The iGraph SDK for Java enables developers to interact with the feature storage engine service. Add the SDK as a Maven dependency or download the package directly. The SDK supports J2SE 8.0 and later.

Download link 1

Download link 2

Download link 3

Procedure

To get started with the iGraph SDK for Java, follow these steps.

Step 1: Create an Alibaba Cloud account

See Alibaba Cloud account for instructions. To ensure full access to all Alibaba Cloud services, we recommend that you complete real-name verification.

Step 2: Obtain iGraph access credentials

Log in to the Alibaba Cloud console. Your iGraph access credentials are the username and password that you set on the purchase page.

If you forget your password, follow the instructions below to reset it.

The API Information panel displays your connection details. These include the internal domain name (for example, igraph-cn-xxx), public domain name, username, and password. To reset your password, click the Reset Password link next to the password field. At the bottom of the page, you can also find a link to modify the whitelist.

Step 3: Install a Java development environment

The iGraph SDK for Java supports J2SE 8.0 and later. You can download and install the Java Development Kit (JDK) from the Java official website.

Step 4: Install the Java SDK

We recommend using Apache Maven to get the latest version of the SDK. 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: Start using the SDK

The main steps for using the iGraph SDK for Java are as follows:

  1. Create a Client instance by configuring initialization parameters, such as the endpoint, and your Alibaba Cloud account username and password. This process is similar to using an open-source Gremlin client.

  2. Construct a query to read or write data.

  3. Call the submit method to send a query, update, or delete request, and then handle the response or any exceptions.

Configure parameters

Parameters

Parameter

Type

Description

src

String

A user-defined name for the scenario.

This name is used as an identifier for query source metrics to help you quickly locate and troubleshoot issues.

endpoint

String

The service endpoint for submitting queries and updates.

userName

String

The username for your authorized Alibaba Cloud account.

userPasswd

String

The password for your authorized Alibaba Cloud account.

maxConnPerRoute

int

The maximum number of HTTP connections to a single server instance. Recommended value: 8.

maxConnTotal

int

The maximum total number of HTTP connections to the service. Recommended value: 2000.

If you receive errors about exceeding the maximum number of connections, increase this value as appropriate.

connectionRequestTimeout

int

The query timeout period in milliseconds.

socketTimeout

int

A Netty parameter. Set this parameter to the same value as connectionRequestTimeout.

connectTimeout

int

A Netty parameter. Set this parameter to the same value as connectionRequestTimeout.

retryTimes

int

The number of retries for timeouts or other retryable exceptions. Recommended value: 3.

Initialize the client

  • To improve connection pool reuse, create a single Client object and reuse it throughout your application.

// 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 not specified, the client uses 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();

Gremlin query, update, and delete data

For more information about Gremlin syntax and operators, see Feature overview.

For compatibility details, see Compatibility with Gremlin steps.

Query data

API query

  • The following code shows an example of a simple single-hop query.

  • First, import static com.aliyun.iGraph.client.gremlin.gremlin_api.GraphTraversalSource.g. iGraph supports cross-graph queries, which you can perform by specifying a graph name.

  • The client API performs basic syntax validation for each step.

// Execute a query and print the result.
GraphTraversal gt = g("your_graph_name").V("your_id").hasLabel("your_label");
// Call the query interface to get the result set.
ResultSet resultSet = client.submit(gt);
List<Result> resultList = resultSet.all().join();
resultList.forEach(p -> System.out.println(p.getObject()));
// Close the client.
cluster.close();

Plaintext queries

  • Build a query directly by using a plaintext string.

  • On the client, you can use bindings to replace variable parameters, such as keys, in your Gremlin query. This practice allows the iGraph server to cache the parsed query syntax tree, reducing client response time (RT) by 4% to 8%.

  • Note:

    • This optimization supports only queries composed of steps such as g, E, V, filter, fields, order, range, join, and alias.

    • This optimization can only replace the ID after V() or E(), the expression after filter(), and the upper and lower boundary values after range().

    • Binding keys must start with a $ character, such as $para1 or $1.

  • You can construct a RequestOption object to specify bindings and other custom parameters.

// Call the plaintext query interface to get results.
String gt = "g(\"your_graph_name\").V(\"your_id\").hasLabel(\"your_label\")";
ResultSet resultSet = client.submit(gt);
// Specify bindings.
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);
// Specify custom parameters by using RequestOptions.
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 supports insert and delete operations in Gremlin, but does not support updating vertices during a traversal.

  • When you update a vertex or edge, you must specify all of its properties.

  • When you delete data, you only need to specify the primary key (pkey).

  • The returned ResultSet contains information about the request.

// Insert a vertex with a single property value.
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 the 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 update and delete examples

// Insert an edge with two property values.
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 multiple edges match, all are deleted.
gt = g("graph_name").E("pk1").hasLabel("label").drop();
// Delete the edge with the specified pkey and skey.
gt = g("graph_name").E("pk1:sk1").hasLabel("label").drop();

Read query results

ResultSet

  • Each query returns a ResultSet object. The methods for retrieving results are identical to those in TinkerPop. You can use the following methods:

// Get all results from the request. The iGraph SDK is not stream-based and returns all results at once. We recommend using this method.
CompletableFuture<List<Result>> futureList = resultSet.all();
// Get some of the results from the request.
CompletableFuture<List<Result>> futureList = resultSet.some(int i);
// Get a single result from the request.
Result result = resultSet.one();
  • Each Result object represents a single result. You must call the appropriate method based on the result's data type:

Method

Description

String getString()

Gets a String result.

int getInt()

Gets an int result.

byte getByte()

Gets a byte result.

short getShort()

Gets a short result.

long getLong()

Gets a long result.

float getFloat()

Gets a float result.

double getDouble()

Gets a double result.

boolean getBoolean()

Gets a boolean result.

Vertex getVertex()

Gets a vertex.

Edge getEdge()

Gets an edge.

Element getElement()

Gets an element, which can be a vertex or an edge.

Path getPath()

Gets a path.

<V> Property<V> getProperty()

Gets a property.

<V> VertexProperty<V> getVertexProperty()

Gets a vertex property.

<T> T get(final Class<? extends T> clazz)

Gets a generic result, including iGraph-extended data types.

Object getObject()

Gets an Object. Use this generic method when you are unsure of the result type.

  • Use the <T> T get(final Class<? extends T> clazz) method to retrieve special data types such as multi-value types, Maps, Sets, and BulkSets. See the following examples:

// Get a List.
List<Result> vecValue = result.get(List.class);
// Get a Map.Entry.
Map.Entry<Result, Result> entry = result.get(Map.Entry.class);
// Get a Set.
Set<Result> setValue = result.get(Set.class);
// Get a Map.
Map<Object, Result> mapValue = result.get(Map.class);
// Get a BulkSet.
BulkSet bulkSet = result.get(BulkSet.class);
Map<Result, Long> value = bulkSet.getValue();
// Get multi-value results.
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

  • A Path object represents the traversal path of a multi-hop query, containing the vertices or edges traversed. The specific contents are determined by the query. The Path interface is as follows:

  • Call objects() to get the contents of the path.

Method

Description

int size()

Gets the number of elements in the path.

boolean isEmpty()

Checks if the path is empty.

<A> A head()

Gets the head (start) of the path.

<A> A get(String label)

Gets the element or list of elements for the specified label.

<A> A get(Pop pop, String label)

Gets some of the elements or a part of the list of elements for the specified label.

<A> A get(int index)

Gets an element at a specific index in the path.

boolean hasLabel(String label)

Checks if the path has an element with the specified label.

List<Object> objects()

Gets the list of elements in the path.

List<Set<String>> labels()

Gets the list of labels for the elements in the path.

Path clone()

Clones the current path.

boolean isSimple()

Checks if the current path is a simple path (no repeated elements).

Iterator<Object> iterator()

Gets an iterator for the path.

void forEach(BiConsumer<Object, Set<String>> consumer)

Performs the given action for each element in the path.

Stream<Pair<Object, Set<String>>> stream()

Gets a stream for the path.

boolean popEquals(Pop pop, Object other)

Checks if two paths are equal.

Path subPath(String fromLabel, String toLabel)

Gets a subpath.

Vertex/Edge

  • A Vertex object represents a vertex, and an Edge object represents an edge. Each corresponds to a record in iGraph. The interfaces are as follows:

    Method

    Description

    String label()

    Gets the label of the element.

    Set<String> keys()

    Gets the property keys of the element.

    <V> Property<V> property(String key)

    Gets the property for the specified key.

    <V> V value(String key)

    Gets the property value for the specified key.

    <V> Iterator<V> values(String... propertyKeys)

    Gets the property values for the specified keys.

    <V> Iterator<VertexProperty<V>> properties(final String... propertyKeys)

    Gets the properties for the specified keys.

    • The property value retrieved by calling value(String key) can be of various data types, depending on the query.

Property/VertexProperty

  • Property and VertexProperty both represent properties. A VertexProperty is retrieved by calling Vertex.property(String key). The interfaces are as follows:

    Method

    Description

    String key()

    Gets the property key.

    V value()

    Gets the property value.

    boolean isPresent()

    Checks if the property value is present.

    void ifPresent(final Consumer<? super V> consumer)

    If the value is present, passes it to the specified consumer.

    V orElse(final V otherValue)

    Returns the value if present, otherwise returns otherValue.

    V orElseGet(final Supplier<? extends V> valueSupplier)

    Returns the value if present, otherwise returns the result produced by a supplier.

    <E extends Throwable> V orElseThrow(final Supplier<? extends E> exceptionSupplier) throws E

    Returns the value if present, otherwise throws an exception produced by a supplier.

    Element element()

    Gets the element that this property belongs to. This is supported only for properties retrieved from an element query.

    • The property value retrieved by calling value() can be of various data types, depending on the query.