Edit on Github

Dependencies

Client Node.js Grakn Core Grakn KGMS Node
1.5.5 1.5.8 1.5.8 >= 6.5
1.5.3 1.5.2 to 1.5.7 1.5.2 to 1.5.7 >= 6.5
1.5.1 1.5.0, 1.5.1 N/A >= 6.5
1.2.4 to 1.3.1 1.3.0, 1.4.0, 1.4.2, 1.4.3 1.2.0 >= 6.5
1.2.0 to 1.2.2 1.2.0 1.2.0 >= 6.5

Installation

npm install grakn-client

Quickstart

First make sure, the Grakn server is running..

In your source, require grakn-client.

const GraknClient = require("grakn-client");

Instantiate a client and open a session.

const GraknClient = require("grakn-client");

async function openSession (keyspace) {
	const client = new GraknClient("localhost:48555");
	const session = await client.session(keyspace);
	// session is open
	await session.close();
	//session is closed
	client.close();
};

openSession("social_network");

We can also pass the credentials, as specified when configuring authentication via Grakn Console, into the initial constructor as a Javascript object.

const client = new GraknClient("localhost:48555", { "username": "<username>", "password": "<password>" });

Create transactions to use for reading and writing data.

const GraknClient = require("grakn-client");

async function createTransactions (keyspace) {
	const client = new GraknClient("localhost:48555");
	const session = await client.session(keyspace);

	// creating a write transaction
	const writeTransaction = await session.transaction().write(); // write transaction is open
	// to persist changes, write transaction must always be committed/closed
	await writeTransaction.commit();

	// creating a read transaction
	const readTransaction = await session.transaction().read(); // read transaction is open
	// read transaction must always be closed
	await readTransaction.close();
	// a session must always be closed
	await session.close();
	// a client must always be closed
	client.close();
}

createTransactions("social_network");

Running basic retrieval and insertion queries.

const GraknClient = require("grakn-client");

async function runBasicQueries (keyspace) {
	const client = new GraknClient("localhost:48555");
	const session = await client.session(keyspace);

	// Insert a person using a WRITE transaction
	const writeTransaction = await session.transaction().write();
	const insertIterator = await writeTransaction.query('insert $x isa person, has email "x@email.com";');
	const concepts = await insertIterator.collectConcepts()
	console.log("Inserted a person with ID: " + concepts[0].id);
	// to persist changes, a write transaction must always be committed (closed)
	await writeTransaction.commit();

	// Retrieve persons using a READ only transaction
	const readTransaction = await session.transaction().read();

	// We can either query and consume the iterator lazily
	let answerIterator = await readTransaction.query("match $x isa person; get; limit 10;");
	let aConceptMapAnswer = await answerIterator.next();
	while (aConceptMapAnswer != null) {
		// get the next `x`
		const person = aConceptMapAnswer.map().get("x");
		console.log("Retrieved person with id "+ person.id);
		aConceptMapAnswer = await answerIterator.next();
	}

	// Or query and consume the iterator immediately collecting all the results
	answerIterator = await readTransaction.query("match $x isa person; get; limit 10;");
	const persons = await answerIterator.collectConcepts();
	persons.forEach( person => { console.log("Retrieved person with id "+ person.id) });

	// a read transaction must always be closed
	await readTransaction.close();
	// a session must always be closed
	await session.close();
	// a client must always be closed
	client.close();
}

runBasicQueries("social_network");
[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 Node.js, head over to their dedicated documentation pages as listed below:

API Reference

Instantiating a Grakn client

new GraknClient(uri, credentials);

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

credentials

The username and password required for connecting to the Grakn Server

{ username: “”, password: “” }

false

N/A

Returns

Client object

Client

Create a session/keyspace

await client.session(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

await client.keyspaces().retrieve();

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

Returns

Array of Strings

Delete a keyspace

await client.keyspaces().delete(“keyspace name”);

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

await 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

await session.transaction().write();

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

Returns

Transaction object

Close a session

await 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

await transaction.query(query, options);

Performs a Graql query on the and retrieves answers lazily.

Accepts

Param Description Type Required Default

query

The Graql query to be executed.

String

true

N/A

options

Determines if the query should apply inference.

{ infer: true }

true

{ infer: true }

Returns

Iterator of Answer

Commit a write transaction

await 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

await transaction.close();

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

Returns

void

Retrieve a concept by id

await transaction.getConcept(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

Concept object or null

Retrieve a schema concept by label

await transaction.getSchemaConcept(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

await transaction.getAttributesByValue(value, datatype);

Accepts

Param Description Type Required Default

value

The value of the attribute to retrieve.

String, long, double, boolean or date

true

N/A

datatype

The datatype of the attribute to retrieve

grakn.DataType.STRING | LONG | DOUBLE | BOOLEAN | DATE

true

N/A

Returns

Iterator of Attributes

Create or retrieve an EntityType

await transaction.putEntityType(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

await transaction.putRelationType(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

await transaction.putAttributeType(label);

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.

grakn.DataType.STRING | LONG | DOUBLE | BOOLEAN | DATE

true

N/A

Returns

AttributeType object

Create or retrieve a Role

await transaction.putRole(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

await transaction.putRule(label, when, 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 when body of the rule to create.

String

true

N/A

then

The then body of the rule to create.

String

true

N/A

Returns

Rule object

Iterator

Transaction queries return iterators of answers. In addition to the method below, the items in an Iterator can be consumed individually using await iterator.next() method.

Convert the iterator into array

await iterator.collect();

Consumes the iterator and collects all the elements into an array.

Returns

Array of IteratorElement

Consume the iterator eagerly

await iterator.collectConcepts();

Consumes the iterator and collects all Concepts into an array.

Returns

Array of Concept

Answer

The type of answers contained in the iterator depends on the type of the query that has returned the iterator. 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 Javascript object where keys are variable names and values are concepts

Returns

Map<String, 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

Numeric

Retrieve nummeric value of an aggregate/computed answer

answer.number();

Returns

number

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

number

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.queryPattern();

Returns

String

Retrieve source facts of inference

explanation.answers();

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

Returns

Array of ConceptMap