Edit on Github

Dependencies

Client Java Grakn Core Grakn KGMS
1.5.2 1.5.2, 1.5.3 1.5.2
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
[tab:Grakn Core] ```xml repo.grakn.ai https://repo.grakn.ai/repository/maven/ <groupId>io.grakn.client</groupId> <artifactId>api</artifactId> 1.5.2 <groupId>io.grakn.core</groupId> <artifactId>concept</artifactId> 1.5.3 <groupId>io.graql</groupId> <artifactId>lang</artifactId> 1.0.1 ``` [tab:end] [tab:Grakn KGMS] ```xml mavencentral https://oss.sonatype.org/content/repositories/releases <groupId>ai.grakn.kgms</groupId> <artifactId>client</artifactId> 1.4.3 ``` [tab:end]

Quickstart

First make sure, the Grakn Server is running.

Import grakn.client.GraknClient, instantiate a client and open a session to a keyspace.

package grakn.examples;

import grakn.client.GraknClient;

public class GraknQuickstartA {
    public static void main(String[] args) {
        GraknClient client = new GraknClient("localhost:48555");
        // client is open
        GraknClient.Session session = client.session("social_network");
        // session is open
        session.close();
        // session is closed
        client.close();
        // client is closed
    }
}

[KGMS ONLY] Using Client Java 1.4.3, 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.

package grakn.examples;

import grakn.client.GraknClient;

public class GraknQuickstartB {
    public static void main(String[] args) {
        GraknClient client = new GraknClient("localhost:48555");
        GraknClient.Session session = client.session("social_network");

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

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

        session.close();
        client.close();
    }
}

Running basic retrieval and insertion queries.

package grakn.examples;

import grakn.client.GraknClient;
import graql.lang.Graql;
import static graql.lang.Graql.*;
import graql.lang.query.GraqlGet;
import graql.lang.query.GraqlInsert;
import grakn.core.concept.answer.ConceptMap;

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

public class GraknQuickstartC {
  public static void main(String[] args) {
    GraknClient client = new GraknClient("localhost:48555");
    GraknClient.Session session = client.session("social_network");

    // Insert a person using a WRITE transaction
    GraknClient.Transaction writeTransaction = session.transaction().write();
    GraqlInsert insertQuery = Graql.insert(var("x").isa("person").has("email", "x@email.com"));
    List<ConceptMap> insertedId = writeTransaction.execute(insertQuery);
    System.out.println("Inserted a person with ID: " + insertedId.get(0).get("x").id());
    // to persist changes, a write transaction must always be committed (closed)
    writeTransaction.commit();

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

    // transactions, sessions and clients must always be closed
    readTransaction.close();
    session.close();
    client.close();
  }
}

[Important] Remember that transactions always need to be closed. Commiting 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 client

new GraknClient(String uri);

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

uri

The host:port on which the Grakn Server is running

String

true

localhost:48555

Returns

Client object

Client

Create a session/keyspace

client.session(String keyspace);

Opens a communication tunnel (session) to the given keyspace on the running Grakn server. If no keyspace with the given name exists, a new one is created.

Accepts

Param Description Type Required Default

keyspace

The name of the keyspace with which the session connects.

String

true

N/A

Returns

Session object

Retrieve all keyspaces

client.keyspaces().retrieve();

Retrieves the name of all keyspaces running on the Grakn server.

Returns

List of Strings

Delete a keyspace

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

Deletes a keyspace with the given name.

Accepts

Param Description Type Required Default

keypsace

The name of the keyspace to be deleted.

String

true

N/A

Returns

void

Close a client

client.close();

Before instantiating a new client, the currently open client should first be closed.

Returns

void

Session

Open a read transaction

session.transaction().read();

Opens a read transaction to perform read queries on the keyspace connected to the session.

Returns

Transaction object

Open a write transaction

session.transaction().write();

Opens a write transaction to perform write queries on the keyspace connected to the session.

Returns

Transaction object

Close a session

session.close();

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

Returns

void

Transaction

Lazily execute a Graql query

transaction.stream(GraqlQuery query, boolean infer);

Performs a Graql query on the and retrieves answers lazily.

Accepts

Param Description Type Required Default

query

The Graql query to be executed.

GraqlQuery or one of its subtypes

true

N/A

infer

Determines if the query should apply inference.

boolean

true

true

Returns

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

Eagerly execute a Graql query

transaction.execute(GraqlQuery query, boolean infer);

Executes a Graql query and retrieves all answers at once.

Accepts

Param Description Type Required Default

query

The Graql query to be executed.

GraqlQuery or one of its subtypes

true

N/A

infer

Determines if the query should apply inference.

boolean

false

true

Returns

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

Commit a write transaction

transaction.commit();

Commits the changes made on the local keyspace (via the caller transaction), to the original keyspace. Whether or not the transaction is commited successfully, it gets closed after the commit call.

Returns

void

Close a read transaction

transaction.close();

Closes the transaction. The currently open transaction must always be closed before opening another one.

Returns

void

Retrieve a concept by id

transaction.getConcept(ConceptId.of(String id));

Retrieves the concept that has the given Grakn id. The concept in question, may be a concept type or an instance of one.

Accepts

Param Description Type Required Default

id

The id of the concept to retrieve.

String

true

N/A

Returns

<T extends Concept> object or NULL

Retrieve a schema concept by label

transaction.getSchemaConcept(Label.of(String label));

Accepts

Param Description Type Required Default

label

The label of the schema concept to retrieve.

String

true

N/A

Returns

Type object

Retrieve an attribute by value

transaction.getAttributesByValue(Object value);

Accepts

Param Description Type Required Default

value

The value of the attribute to retrieve.

String | Date | long | double | boolean

true

N/A

Returns

Create or retrieve an EntityType

transaction.putEntityType(Label.of(String label));

Creates a new EntityType if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the EntityType to create or retrive.

String

true

N/A

Returns

EntityType object

Create or retrieve a RelationType

transaction.putRelationType(Label.of(String label));

Creates a new RelationType if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the RelationType to create or retrive.

String

true

N/A

Returns

RelationType object

Create or retrieve an AttributeType

transaction.putAttributeType(Label.of(String label), AttributeType.DataType dataType)

Creates a new AttributeType if none exists with the given label, or retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the AttributeType to create or retrive.

String

true

N/A

datatype

The datatype of the attribute to create or retrieve.

AttributeType.DataType<String | Date | long | double | boolean>

true

N/A

Returns

AttributeType object

Create or retrieve a Role

transaction.putRole(Label.of(String label));

Creates a new Role if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the Role to create or retrive.

String

true

N/A

Returns

Role object

Create or retrieve a Rule

transaction.putRule(Label.of(String label), Pattern when, Pattern then);

Creates a new Rule if none exists with the given label, or retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the Rule to create or retrive.

String

true

N/A

when

The pattern describing the when body of the rule.

graql.lang.pattern.Pattern

true

N/A

then

The pattern describing the then body of the rule.

graql.lang.pattern.Pattern

true

N/A

Returns

Rule object

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>lang</artifactId>
        <version>1.0.1</version>
    </dependency>
</dependencies>

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:

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

Numeric

aggregate group

AnswerGroup

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

Numeric

compute path

ConceptList

compute cluster

ConceptSet

compute centrality

ConceptSetMeasure

ConceptMap

Retrieve a mapping of variables to concepts

answer.map();

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

Returns

Map<Variable, Concept>

Retrieve a concept corresponding to a specific variable

answer.get(var)

Retrieve a concept for a given variable name without explicitly retriving the map

Accepts

Param Description Type Required Default

var

The string representation of a variable

String

Returns

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

Numeric

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

explanation.getPattern();

Returns

Retrieve source facts of inference

explanation.getAnswers();

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

Returns