Dependencies

The only dependency for getting started with Grakn Client Java is Grakn >= 1.3.0 added as a dependency in your Java project.

[tab:Grakn Core] ```xml <dependency> <groupId>ai.grakn</groupId> <artifactId>client-java</artifactId> <version>1.4.3</version> </dependency> ``` [tab:end] [tab:Grakn KGMS] ```xml <dependency> <groupId>ai.grakn.kgms</groupId> <artifactId>client</artifactId> <version>1.4.3</version> </dependency> ``` [tab:end]

Quickstart

First make sure, the Grakn server is running.

In the interpreter or in your source, import grakn.

Instantiate a client and open a session.

import ai.grakn.Keyspace;
import ai.grakn.client.Grakn;
import ai.grakn.util.SimpleURI;

public class GraknQuickstart {
    public static void main(String[] args) {
        SimpleURI localGrakn = new SimpleURI("localhost", 48555);
        Keyspace keyspace = Keyspace.of("genealogy");
        Grakn grakn = new Grakn(localGrakn);
        Grakn.Session session = grakn.session(keyspace);
        // session is open
        session.close();
        // session is closed
    }
}

[KGMS ONLY] We can also pass the credentials, as specified when configuring authentication via Grakn Console.

SimpleURI localGrakn = new SimpleURI("localhost", 48555);
Grakn grakn = new ClientFactory(localGrakn, "<username>", "<password>").client();

Create transactions to use for reading and writing data.

import ai.grakn.GraknTxType;
import ai.grakn.Keyspace;
import ai.grakn.client.Grakn;
import ai.grakn.util.SimpleURI;

public class GraknQuickstart {
    public static void main(String[] args) {
        SimpleURI localGrakn = new SimpleURI("localhost", 48555);
        Keyspace keyspace = Keyspace.of("genealogy");
        Grakn grakn = new Grakn(localGrakn);
        Grakn.Session session = grakn.session(keyspace);

        // creating a write transaction
        Grakn.Transaction writeTransaction = session.transaction(GraknTxType.WRITE);
        // write transaction is open
        // write transaction must always be committed (closed)
        writeTransaction.commit();

        // creating a read transaction
        Grakn.Transaction readTransaction = session.transaction(GraknTxType.READ);
        // read transaction is open
        // read transaction must always be closed
        readTransaction.close();

        session.close();
    }
}

Running basic retrieval and insertion queries.

import ai.grakn.GraknTxType;
import ai.grakn.Keyspace;
import ai.grakn.client.Grakn;
import ai.grakn.graql.GetQuery;
import ai.grakn.graql.Graql;
import ai.grakn.graql.InsertQuery;
import ai.grakn.graql.answer.ConceptMap;
import ai.grakn.util.SimpleURI;
import java.util.List;
import java.util.stream.Stream;

public class GraknQuickstart {
  public static void main(String[] args) {
    SimpleURI localGrakn = new SimpleURI("localhost", 48555);
    Keyspace keyspace = Keyspace.of("phone_calls");
    Grakn grakn = new Grakn(localGrakn);
    Grakn.Session session = grakn.session(keyspace);

    // Insert a person using a WRITE transaction
    Grakn.Transaction writeTransaction = session.transaction(GraknTxType.WRITE);
    InsertQuery insertQuery = Graql.insert(var("p").isa("person").has("first-name", "Elizabeth"));
    List<ConceptMap> insertedId = insertQuery.withTx(writeTransaction).execute();
    System.out.println("Inserted a person with ID: " + insertedId.get(0).get("p").id());
    // to persist changes, a write transaction must always be committed (closed)
    writeTransaction.commit();

    // Read the person using a READ only transaction
    Grakn.Transaction readTransaction = session.transaction(GraknTxType.READ);
    GetQuery query = Graql.match(var("p").isa("person")).limit(10).get();
    Stream<ConceptMap> answers = query.withTx(readTransaction).stream();
    answers.forEach(answer -> System.out.println(answer.get("p").id()));

    // a read transaction and session must always be closed
    readTransaction.close();
    session.close();
  }
}
[Important] Remember that transactions always need to be closed. Commiting a write transaction closes it. A read transaction, however, must be explicitly clased 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

Creating an instance of Grakn

new Grakn(new SimpleURI(host, port));

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

Accepts

Param Description Type Required Default

host

The host address on which the Grakn Server is running

String

true

localhost

port

The port on which the Grakn server is running

int

true

48555

Returns

Client object

Client

Create a session/keyspace

client.session(Keyspace.of(String keyspace));

Creates a communication channel to the given keyspace on the Grakn server. If no keyspace with the given name exists, a new one is created.

Accepts

Param Description Type Required Default

keyspace

The keyspace with which the session connects.

Keyspace (Keyspace.of("name-of-keyspace"))

true

N/A

Returns

Session object

Delete a keyspace

client.keyspaces().delete(Keyspace.of(String keyspace));

Deletes a keyspace with the given name.

Accepts

Param Description Type Required Default

keypsace

The keyspace to be deleted.

Keyspace

true

N/A

Session

Create a transaction

session.transaction(GraknTxType type)

Creates a transaction to execute read and write operations on the keyspace connected to the session.

Accepts

Param Description Type Required Default

type

The type of the transaction to be created - read or write.

GraknTxType.READ or GraknTxType.WRITE

true

N/A

Returns

Transaction object

Close a session

session.close();

Closes the session once it is no longer being used.

Returns

void

Transaction

Commit a write transaction

transaction.commit();

Commits the inserted or deleted data instances or schema concepts to the keyspace attached to the session from which this transaction originated. The transaction is also closed on commit.

Returns

void

Close a read transaction

transaction.close();

Closes the transaction which has been used to read from the keyspace.

Returns

void

Graql

Manipulate the schema programatically

.define(VarPattern… varPatterns); .undefine(VarPattern… varPatterns);

Manipulates the schema concepts using a list of variable patterns. See examples for defining and undefining schema concepts.

Accepts

Param Description Type Required Default

varPatterns

The statements that describe what is to be un/defined. See examples for defining and undefining schema concepts.

VarPattern…

true

N/A

Returns

DefineQuery object

Match patterns in data

.match(Pattern… patterns);

Matches the data that conforms to the given pattern. See various examples of mactch clauses.

Accepts

Param Description Type Required Default

patterns

The statements that describes the pattern to be matched. See examples for various match clauses.

Pattern…

true

N/A

Returns

Match object

Insert data instances

.insert(VarPattern… varPatterns); .match(Pattern… patterns).insert(VarPattern… varPatterns);

Inserts new instances of data using variable pattern(s). See examples for insert queries.

Accepts

Param Description Type Required Default

varPatterns

The statements that describe the pattern for the data to be inserted. See examples for insert queries.

VarPattern…

true

N/A

Returns

InsertQuery object

Retrieve data instances

.match(Pattern… patterns).get(Var… vars);

Retrieves instances of data that matched the preceding clause. See examples for get queries.

Accepts

Param Description Type Required Default

vars

The variables whose contained instances are to be retrieved. See examples for get queries.

Var…

false

all variables in the match cluse

Returns

GetQuery object

Delete data instances

.match(Pattern… patterns).delete(Var… vars);

Deletes instances of data that matched the preceding match clause. See examples for delete queries.

Accepts

Param Description Type Required Default

vars

The variables whose contained instances are to be deleted. See examples for delete queries.

Var…

true

N/A

Returns

DeleteQuery object

Aggregate values

.match(Pattern… patterns).aggregate(Aggregate<T> aggreagate);

Aggregates a given function over the data that matched the preceding match clause. See examples for delete queries.

Accepts

Param Description Type Required Default

aggreagate

The aggregate function to perform on the match instances. See examples for aggregate queries.

Aggregate<T>

true

N/A

Returns

AggregateQuery<?> object (type of the AggregateQuery may be Value or AnswerGroup<ConceptMap>, depedning on the given aggreagte function)

Compute values

.compute(Method<T> method);

Computes values over a large dataset using a variable pattern. For a complete set of parameters and methods available on compute(), see examples of compute queries.

Accepts

Param Description Type Required Default

method

The method used for computation. See examples for compute queries.

GraqlSyntax.Compute.Method

true

N/A

Returns

ComputeQuery<?> object(type of the ComputeQuery is dependent on the type of the compute method)

Query

Attach transaction to query

.withTx(Transaction transaction)

Attaches a previously instantiated transaction to the query, preparing it for lazy or eager execution.

Accepts

Param Description Type Required Default

transaction

The read or write transaction that is responsible for executing the query.

Transaction

true

N/A

Lazy executation of a Graql query

.withTx(Transaction transaction).stream(String query)

Executes a Graql query lazily on the keyspace where the session is connected to.

Returns

Stream<?> (type of elements in the stream is dependent on the type of the query object)

Eager executation of a Graql query

.withTx(Transaction transaction).execute()

Executes a Graql query eagerly on the keyspace where the session is connected to.

Returns

List<?> (type of elements in the list is dependent on the type of the query object)

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
define

ConceptMap

undefine

ConceptMap

get

ConceptMap

insert

ConceptMap

delete

ConceptMap

aggregate count/min/max/sum/mean/std

Value

aggregate group

AnswerGroup

compute count/min/max/sum/mean/std

Value

compute path

ConceptList

compute cluster

ConceptSet

compute centrality

ConceptSetMeasure

ConceptMap

Retrieve a map of Variable => Concept from the ConceptMap answer

answer.map();

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

Returns

Map ({variable_name: Concept})

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

Value

Retrieve nummeric value of an aggregate/computed answer

answer.number();

Returns

int

|

float

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptList

Retrieve ids of all concepts in a ConceptList answer

answer.list();

Returns

Array of String

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptSet

Retrieve set of ids of concepts after a cluster computation

answer.set();

Returns

Set of String

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptSetMeasure

Retrieve the numeric value of a centrality computation

answer.measurement();

Returns

int

|

float

Retrieve a set of ids of concepts after a centrality computation

answer.set();

Returns

Set of String

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

AnswerGroup

Retrieve the concept that is the group owner

answer.owner();

Returns

Retrieve the answers of the group

answer.answers();

Returns

Array of Answer

Explaining an inferred answer

answer.explanation();

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

Explanation

Retrieve a Graql explanation of the answer

answer.query_pattern();

Returns

String

Retrieve source facts of inference

answer.answers()

Provides a list of answers from which the inferred answer is derived.

Returns

Array of Answer