Dependencies

Before installing the grakn node module, make sure the following dependencies are installed.

Installation

npm install grakn

Quickstart

First make sure, the Grakn server is running..

In your source, require grakn.

const Grakn = require("grakn");

Instantiate a client and open a session.

const client = new Grakn("localhost:48555");
const session = client.session("keyspace");

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 Grakn("localhost:48555", { "username": "<username>", "password": "<password>" });

Create transactions to use for reading and writing data.

const client = new Grakn("localhost:48555");
const session = client.session("keyspace");

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

// creating a read transaction
const readTx = await session.transaction(Grakn.txType.READ); // read transaction is open
// read transaction must always be closed
readTx.close();

Running basic retrieval and insertion queries.

const Grakn = require("grakn");
const client = new Grakn("localhost:48555");
const session = client.session("keyspace");

async function runBasicQueries() {
  // Insert a person using a WRITE transaction
  const writeTransaction = await session.transaction(Grakn.txType.WRITE);
  const insertIterator = await writeTransaction.query("insert $x isa person;");
  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(Grakn.txType.READ);

  // We can either query and consume the iterator lazily
  let answerIterator = await readTransaction.query("match $x isa person; limit 10; get;");
  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
  // - consume it all immediately
  answerIterator = await readTransaction.query("match $x isa person; limit 10; get;");
  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();
}

runBasicQueries();
[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

Creating an instance of Grakn

new Grakn(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

credentials

The username and password required for connecting to the Grakn Server

true

credentials

The username and password required for connecting to the Grakn Server

{ username: “”, password: “” }

true

Returns

Client object

Client

Create a session/keyspace

client.session(“keyspace name”)

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 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

Array of Strings

Delete a keyspace

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

Session

Create a transaction

session.transaction(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.

grakn.TxType.READ or grakn.TxType.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

Lazily execute a Graql query

async transaction.query(query, options);

Prepare a Graql query to be executed on the keyspace where the session is connected to (answers are only computed when we ask for an answer, hence lazy).

Accepts

Param Description Type Required Default

options

Determines if the query should apply inference.

{ infer: true }

true

{ infer: true }

Returns

Iterator of Answer

Close a read transaction

async transaction.close();

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

Returns

void

Retrive a concept by ID

async transaction.getConcept(conceptId)

Accepts

Param Description Type Required Default

conceptId

The id of the concept to retrieve

String

true

N/A

Returns

Concept object

Retrive a schema concept by label

async 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

Retrive an attribute by value

async transaction.getAttributesByValue(value, datatype);

Accepts

Param Description Type Required Default

datatype

The datatype of the attribute to retrieve

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

true

N/A

Returns

Create or retrievie an EntityType

async transaction.putEntityType(label);

Creates a new EntityType if none exists with the given label, or 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 RelationshipType

async transaction.putRelationshipType(label);

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

Accepts

Param Description Type Required Default

label

The label of the RelationshipType to create or retrive.

String

true

N/A

Returns

Create or retrieve an AttributeType

async 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

datatype

The datatype of the attribute to create retrieve

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

true

N/A

Returns

AttributeType object

Create or retrieve a Role

async transaction.putRole(label);

Creates a new Role if none exists with the given label, or 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

async 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

then

The then body of the rule to create.

String

true

N/A

Returns

Rule object

Iterator

In addition to the methods below, the items in an Iterator can be consumed individually using async iterator.next() method.

Convert the iterator into array

async iterator.collect();

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

Returns

Array of IteratorEelement

Consume the iterator eagerly

async 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

Value

aggregate group

AnswerGroup

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

Value

compute path

ConceptList

compute cluster

ConceptSet

compute centrality

ConceptSetMeasure

ConceptMap

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

answer.map();

Produces a Javascript object 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

Retrive 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

Retrive 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

Retrive 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

Retrive 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

Retrive 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

answer.answers()

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

Returns

Array of Answer