Edit on Github

Installation

To use this client, you need a compatible Grakn Server running. Visit our Compatibility Table

<repositories>
    <repository>
        <id>repo.grakn.ai</id>
        <url>https://repo.grakn.ai/repository/maven/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        &lt;groupId&gt;io.grakn.client&lt;/groupId&gt;
        &lt;artifactId&gt;grakn-client&lt;/artifactId&gt;
        <version>{version}</version>
    </dependency>
</dependencies>

If you want to depend on snapshot versions of Client Java, by referring to the GitHub commit sha, you can add our snapshot repository to your list of Maven repositories.

<repositories>
    <repository>
        <id>repo.grakn.ai.snapshot</id>
        <name>repo.grakn.ai</name>
        <url>https://repo.grakn.ai/repository/maven-snapshot/</url>
    </repository>
</repositories>

Quickstart

First make sure, the Grakn Server is running.

Import grakn.client.Grakn, instantiate a Grakn Core client and open a session to a database.

package grakn.examples;


import grakn.client.api.GraknClient;
import grakn.client.api.GraknSession;
import grakn.client.Grakn;

public class GraknQuickstartA {
    public static void main(String[] args) {
        GraknClient client = Grakn.coreClient("localhost:1729");
        // client is open
        GraknSession session = client.session("social_network", GraknSession.Type.DATA);
        // session is open
        session.close();
        // session is closed
        client.close();
        // client is closed
    }
}

Create transactions to use for reading and writing data.

package grakn.examples;

import grakn.client.api.GraknClient;
import grakn.client.api.GraknSession;
import grakn.client.api.GraknTransaction;
import grakn.client.Grakn;

public class GraknQuickstartB {
    public static void main(String[] args) {
        GraknClient client = Grakn.coreClient("localhost:1729");

        try (GraknSession session = client.session("social_network", GraknSession.Type.DATA)) {
            // creating a write transaction
            GraknTransaction writeTransaction = session.transaction(GraknTransaction.Type.WRITE);
            // write transaction is open
            // write transaction must always be committed (closed)
            writeTransaction.commit();
    
            // creating a read transaction
            Transaction readTransaction = session.transaction(Transaction.Type.READ);
            // read transaction is open
            // read transaction must always be closed
            readTransaction.close();
        }

        client.close();
    }
}

Running basic retrieval and insertion queries.

package grakn.examples;


import grakn.client.api.GraknClient;
import grakn.client.api.GraknSession;
import grakn.client.api.GraknTransaction;
import grakn.client.Grakn;
import graql.lang.Graql;
import static graql.lang.Graql.*;
import graql.lang.query.GraqlMatch;
import graql.lang.query.GraqlInsert;
import grakn.client.api.answer.ConceptMap;

import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class GraknQuickstartC {
    public static void main(String[] args) {
        GraknClient client = Grakn.coreClient("localhost:1729");

        try (GraknSession session = client.session("social_network", GraknSession.Type.DATA)) {
            
            try (GraknTransaction writeTransaction = session.transaction(GraknTransaction.Type.WRITE)) {
                // Insert a person using a WRITE transaction
                GraqlInsert insertQuery = Graql.insert(var("x").isa("person").has("email", "x@email.com"));
                List<ConceptMap> insertedId = writeTransaction.query().insert(insertQuery).collect(Collectors.toList());
                System.out.println("Inserted a person with ID: " + insertedId.get(0).get("x").asThing().getIID());
                // to persist changes, a write transaction must always be committed (closed)
                writeTransaction.commit();
            }
            
            try (GraknTransaction readTransaction = session.transaction(GraknTransaction.Type.READ)) {
                // Read the person using a READ only transaction
                GraqlMatch.Limited getQuery = Graql.match(var("p").isa("person")).get("p").limit(10);
                Stream<ConceptMap> answers = readTransaction.query().match(getQuery);
                answers.forEach(answer -> System.out.println(answer.get("p").asThing().getIID()));
            }
        }

        client.close();
    }
}

[Important] Remember that transactions always need to be closed. Committing a write transaction closes it. A read transaction, however, must be explicitly closed by calling the `close()` method on it.

Check out the Concept API to learn about the available methods on the concepts retrieved as the answers to Graql queries.

To view examples of running various Graql queries using the Grakn Client Java, head over to their dedicated documentation pages as listed below.


API Reference

Instantiating a Grakn Core client

Grakn.coreClient(String address, int parallelisation);

In order to communicate with Grakn Core databases via sessions and transactions, we first need to instantiate a Grakn Core client. The created object connects our application with the running Grakn Server.

Accepts

Param Description Type Required Default

address

The address (host:port) on which the Grakn Server is running

String

true

parallelisation

The number of threads to use for server communication

int

false

Scales based on host machine’s number of available CPU cores

Returns

Instantiating a Grakn Cluster client

Grakn.clusterClient(Set addresses, int parallelisation);

In order to communicate with Grakn Cluster databases via sessions and transactions, we first need to instantiate a Grakn Cluster client. The created object connects our application with the running Grakn Cluster.

Accepts

Param Description Type Required Default

addresses

All addresses (host:port) on which Grakn Cluster nodes are running

Set

true

parallelisation

The number of threads to use for server communication

int

false

Scales based on host machine’s number of available CPU cores

Returns

Client

Create a session for a database

client.session(String database, Session.Type sessionType, GraknOptions options);

Opens a communication tunnel (session) to the given database on the running Grakn server.

Accepts

Param Description Type Required Default

database

The name of the database with which the session connects.

String

true

N/A

type

The type of session to be created (DATA or SCHEMA)

SessionType

true

N/A

options

Options for the session.

GraknOptions

false

N/A

Returns

Retrieve all databases

client.databases().all();

Retrieves all databases running on the Grakn server.

Returns

List

Check if a database exists

client.databases().contains(String database);

Checks if a database with the given name exists

Accepts

Param Description Type Required Default

database

The database name to be checked.

String

true

N/A

Create a database

client.databases().create(String database);

Create a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to be created.

String

true

N/A

Returns

void

Retrieve a database

client.databases().get(String database);

Retrieve a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to retrieve.

String

true

N/A

Returns

Database

Delete a database

client.databases().get(String database).delete();

Deletes a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to be deleted.

String

true

N/A

Returns

void

Close a client

client.close();

Closes the client. Before instantiating a new client, the client that’s currently open should first be closed.

Returns

void

Session

Open a transaction

session.transaction(Transaction.Type transactionType, GraknOptions options);

Opens a transaction to perform read or write queries on the database connected to the session.

Accepts

Param Description Type Required Default

transactionType

The type of transaction to be created (READ or WRITE).

Transaction.Type

true

options

Options for the session.

GraknOptions

false

N/A

Returns

Check if a session is open

session.isOpen();

Checks whether a session is presently open.

Returns

boolean

Check the session's type

session.type();

Checks the current session’s type (SCHEMA or DATA)

Returns

Session.Type

Check the session's database

session.database();

Returns a string indicating what database the session is operating over.

Returns

String

Close a session

session.close();

Closes the session. Before opening a new session, the session currently open should first be closed.

Returns

void

Options

The transaction query options object GraknOptions can be used to override the default server behaviour query processing. Use GraknOptions.core() to create a new Grakn Core options object, or GraknOptions.cluster() for Grakn Cluster.

The options are:

  • infer: whether to enable inference for the provided query (only settable at transaction level) (default: false)
  • explain: whether to enable explanations for the provided query (default: false)
  • parallel: whether the server should use parallel or single-threaded execution (default: true)
  • batchSize: a guideline number of answers that the server should send before the client issues a fresh request (default: 50)
  • traceInference: if enabled, creates reasoning traces as graphs logged in the logging directory. Should be used with parallel = false. (default: false)
  • prefetch: if enabled, the first batch of answers is streamed to the client even without an explicit request for it (default: true if query type is match, otherwise false)
  • sessionIdleTimeoutMillis: this timeout allows the server to close sessions if a client terminates or becomes unresponsive (default: 10000)
  • schemaLockTimeoutAcquireMillis: how long the client should wait if opening a session or transaction is blocked by a schema write lock (default: 10000)

GraknClusterOptions has an additional option:

  • readAnyReplica: enables reading data from any replica, potentially boosting read throughput (default: false)

Explicitly enable or disable inference

options.setInfer(boolean enabled)

Override the server defaults to enable or disable inference for the provided query

Accepts

Param Description Type Required Default

enabled

explicitly set inference on or off for this query

boolean

true

Returns

Explicitly enable or disable explanations

options.setExplain(boolean enabled)

Override the server defaults to enable or disable explanation availability for the provided query.

Accepts

Param Description Type Required Default

enabled

explicitly set explanations on or off for this query

boolean

true

Returns

Force the server parallelism

options.setParallel(boolean parallel)

Override the server defaults to use parallel or single-threaded query execution

Accepts

Param Description Type Required Default

parallel

use parallel or single-threaded query execution

boolean

true

Returns

Explicitly set query batch iteration to a certain size

options.setBatchSize(int size)

Override the server defaults for answer batch streaming. This tells the server to pre-compute and stream this number of answers at a time. These are buffered in the client until read. A larger batch size causes the server to compute more answers at a time, blocking the transaction until the batch is computed.

Accepts

Param Description Type Required Default

size

int

true

Returns

Trace and log reasoning inference

options.setTraceInference(boolean traceInference)

Create reasoning traces as graphs logged in the logging directory. Should be used with parallel = false

Accepts

Param Description Type Required Default

traceInference

trace reasoning execution as graphs in log directory

boolean

true

Returns

Explicitly enable or disable prefetch

options.setPrefetch(boolean prefetch)

If enabled, the first batch of answers is streamed to the client even without an explicit request for it

Accepts

Param Description Type Required Default

prefetch

if set to true, the first batch of answers is streamed to the client even without an explicit request for it

boolean

true

Returns

Override default session idle timeout

options.setSessionIdleTimeoutMillis(int timeout)

This timeout allows the server to close sessions if a client terminates or becomes unresponsive

Accepts

Param Description Type Required Default

timeout

int

true

Returns

Override default schema lock acquire timeout

options.setSchemaLockAcquireTimeoutMillis(int timeout)

This timeout allows the server to close sessions if a client terminates or becomes unresponsive

Accepts

Param Description Type Required Default

timeout

int

true

Returns

Enable reading data from any replica

clusterOptions.setReadAnyReplica(bool readAnyReplica)

Used to enable reading data from any replica, potentially boosting read throughput

Accepts

Param Description Type Required Default

readAnyReplica

boolean

true

Returns

Transaction

Check the transaction's type

transaction.type();

Checks the transaction’s type (READ or WRITE)

Returns

Transaction.Type

Check if the transaction is open

transaction.isOpen();

Returns

boolean

Access Concept API methods

transaction.concepts();

Gets the ConceptManager for this Transaction, providing access to all Concept API methods.

Returns

Access Concept API - Logic methods

transaction.logic();

Gets the LogicManager for this Transaction, providing access to all Concept API - Logic methods.

Returns

Access Query API methods

transaction.query();

Gets the QueryManager for this Transaction, from which any Graql query can be executed.

Returns

Commit a write transaction

transaction.commit();

Commits the changes made via this transaction to the Grakn database. Whether or not the transaction is commited successfully, it gets closed after the commit call.

Returns

void

Rollback a write transaction

transaction.rollback();

Rolls back the uncommitted changes made via this transaction.

Returns

void

Close a read transaction

transaction.close();

Closes the transaction.

Returns

void

Graql

Graql, the query language for Grakn, is written in Java and its API can be used to programmatically construct Graql queries.

To use Graql, we first add it as a dependency to our pom.xml.

<repositories>
    <repository>
        <id>repo.grakn.ai</id>
        <url>https://repo.grakn.ai/repository/maven/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>io.graql</groupId>
        <artifactId>graql-lang</artifactId>
        <version>{version}</version>
    </dependency>
</dependencies>

The latest version of graql-lang can be found in the Grakn public Maven repository.

The we import Graql.

import graql.lang.Graql;

We are now ready to construct Graql queries, using the methods available on the Graql class. Check out the following pages to learn, by example, how the Graql API allows construction of various Graql queries:

QueryManager

Execute a Graql Match query

transaction.query().match(GraqlMatch query, GraknOptions options);

Performs a Graql Match query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match query to be executed.

GraqlMatch

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<ConceptMap>

Execute a Graql Match Aggregate query

transaction.query().match(GraqlMatch.Aggregate query, GraknOptions options);

Performs a Graql Match Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Aggregate query to be executed.

GraqlMatch.Aggregate

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Match Group query

transaction.query().match(GraqlMatch.Group query, GraknOptions options);

Performs a Graql Match Group query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Group query to be executed.

GraqlMatch.Group

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<ConceptMapGroup>

Execute a Graql Match Group Aggregate query

transaction.query().match(GraqlMatch.Group.Aggregate query, GraknOptions options);

Performs a Graql Match Group Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Group Aggregate query to be executed.

GraqlMatch.Group.Aggregate

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<NumericGroup>

Execute a Graql Insert query

transaction.query().insert(GraqlInsert query, GraknOptions options);

Performs a Graql Insert query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Insert query to be executed.

GraqlInsert

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<ConceptMap>

Execute a Graql Delete query

transaction.query().delete(GraqlDelete query, GraknOptions options);

Performs a Graql Delete query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Delete query to be executed.

GraqlDelete

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Update query

transaction.query().update(GraqlUpdate query, GraknOptions options);

Performs a Graql Update query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Update query to be executed.

GraqlUpdate

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<ConceptMap>

Execute a Graql Explain query

transaction.query().explain(ConceptMap.Explainable explainable, GraknOptions options);

Performs a Graql Explain query in the transaction.

Accepts

Param Description Type Required Default

explainable

The Explainable to be explained.

ConceptMap.Explainable

true

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Stream<Explanation>

Execute a Graql Define query

transaction.query().define(GraqlDefine query, GraknOptions options);

Performs a Graql Define query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Define query to be executed.

GraqlDefine

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Undefine query

transaction.query().undefine(GraqlUndefine query, GraknOptions options);

Performs a Graql Undefine query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Undefine query to be executed.

GraqlUndefine

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Answer

The type of answers returned by execution of a query depends on the type of query executed. The table below illustrates the answer types mapped to query types.

Query Type Answer Type
match

Stream/Iterator of ConceptMap

match aggregate (count/min/max/sum/mean/std)

QueryFuture of Numeric

match group

Stream/Iterator of ConceptMapGroup

match group aggregate

Stream/Iterator of NumericGroup

insert

Stream/Iterator of ConceptMap

delete

QueryFuture

update

Stream/Iterator of ConceptMap

explain

Stream/Iterator of Explanation

define

QueryFuture

undefine

QueryFuture

ConceptMap

Retrieve a mapping of variables to concepts

conceptMap.map();

Produces a Map where keys are variable names and values are concepts.

Returns

Map<String, Concept>

Retrieve concepts

conceptMap.concepts();

Return a collection of all the concepts in this ConceptMap.

Returns

Collection

Retrieve a concept corresponding to a specific variable

conceptMap.get(String var)

Retrieve a concept for a given variable name

Accepts

Param Description Type Required Default

var

The string representation of a variable

String

Returns

Retrieve explainable concepts

conceptMap.explainables()

Gets the Explainables object for this ConceptMap, exposing which of the Concepts in this ConceptMap are explainable

Returns

Numeric

Retrieve numeric value of an aggregate answer as a long

numeric.asLong();

Returns

long

Retrieve numeric value of an aggregate answer as a double

numeric.asDouble();

Returns

double

Retrieve numeric value of an aggregate answer

numeric.asNumber();

Returns

Number

Checks if the type of an aggregate answer is a long

numeric.isLong();

Returns

boolean

Checks if the type of an aggregate answer is a double

numeric.isDouble();

Returns

boolean

Checks if the type of an aggregate answer is not a number

conceptMapGroup.isNaN();

Returns

boolean

ConceptMapGroup

Retrieve the concept that is the group owner

conceptMapGroup.owner();

Returns

Retrieve the ConceptMaps of the group

conceptMapGroup.conceptMaps();

Returns

List<ConceptMap>

Explainables

Retrieve explainable relation

conceptMap.explainables().relation(String variable);

Retrieves the explainable relation with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable attribute

conceptMap.explainables().attribute(String variable);

Retrieves the explainable attribute with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable ownership

conceptMap.explainables().ownership(String variable);

Retrieves the explainable attribute ownership with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable relations

conceptMap.explainables().relations();

Retrieves all of this ConceptMap’s explainable relations.

Returns

Map<String, ConceptMap.Explainable>

Retrieve explainable attributes

conceptMap.explainables().attributes();

Retrieves all of this ConceptMap’s explainable attributes.

Returns

Map<String, ConceptMap.Explainable>

Retrieve explainable ownerships

conceptMap.explainables().ownerships();

Retrieves all of this ConceptMap’s explainable attribute ownerships.

Returns

Map<String, ConceptMap.Explainable>

Explainable

Retrieve conjunction

explainable.conjunction()

Retrieves the subquery of the original query that is actually being explained.

Returns

String

Retrieve ID

explainable.id()

Retrieves the unique ID that identifies this Explainable.

Returns

long

Explanation

Retrieve the rule

explanation.rule();

Retrieves the Rule for this Explanation.

Returns

Rule

Retrieve the conclusion

explanation.conclusion()

Retrieves the Conclusion for this Explanation.

Returns

ConceptMap

Retrieve the condition

explanation.condition()

Retrieves the Condition for this Explanation.

Returns

ConceptMap

Retrieve the variable mapping

explanation.variableMapping()

Retrieves the mapping between rule variables and query variables for this Explanation.

Returns

Map<String, Set>

QueryFuture

Transaction queries that return single answers or empty responses are executed asynchronously on the server. To wait for a query to finish execution, and return its result if there is one, use the ‘get()’ function.

Get the query result

future.get()

Waits for the query to finish execution, and returns its result, if present.

Returns

Returns according to type of query executed

Map the query result

future.map(function)

Transforms the QueryFuture into a new QueryFuture by running the supplied function on the query result when it is returned.

Returns

Return type of supplied function

Dependencies

Client Java Grakn Core Grakn Cluster
2.0.0 2.0.0 2.0.0
1.8.3 1.8.0 to 1.8.4 N/A
1.8.2 1.8.0, 1.8.1 N/A
1.8.1 1.8.0 N/A
1.8.0 1.8.0 N/A
1.7.3 1.7.1, 1.7.2 N/A
1.7.2 1.7.1, 1.7.2 N/A
1.6.2 1.6.2 1.6.2
1.6.1 1.6.0, 1.6.1 N/A
1.5.5 1.5.8, 1.5.9 1.5.8
1.5.4 1.5.8, 1.5.9 1.5.8
1.5.3 1.5.2 to 1.5.7 1.5.2 to 1.5.7
1.5.2 1.5.2, 1.5.3 1.5.2 to 1.5.4
1.5.0 1.5.0 N/A
1.4.3 1.4.3 1.4.3
1.4.2 1.4.2 1.2.0
1.4.1 1.4.0 1.2.0
1.4.0 1.4.0 1.2.0
1.3.0 1.3.0 1.2.0