Edit on Github

Installation

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

npm install grakn-client

Quickstart

First make sure that the Grakn server is running.

In your source, require grakn-client/GraknClient.

const { GraknClient } = require("grakn-client/GraknClient");

Instantiate a client and open a session.

const { GraknClient, SessionType, TransactionType } = require("grakn-client/GraknClient");

async function openSession (database) {
	const client = Grakn.coreClient("localhost:1729");
	const session = await client.session(database, SessionType.DATA);
	// session is open
	await session.close();
	//session is closed
	client.close();
};

openSession("social_network");

Create transactions to use for reading and writing data.

const { GraknClient, SessionType, TransactionType } = require("grakn-client/GraknClient");

async function createTransactions (database) {
	const client = Grakn.coreClient("localhost:1729");
	const session = await client.session(database, SessionType.DATA);

	// creating a write transaction
	const writeTransaction = await session.transaction(TransactionType.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(TransactionType.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 { Grakn } = require("grakn-client/Grakn");
const { SessionType } = require("grakn-client/api/GraknSession");
const { TransactionType } = require("grakn-client/api/GraknTransaction");

async function runBasicQueries(database) {
	const client = Grakn.coreClient("localhost:1729");
	const session = await client.session(database, SessionType.DATA);

	// Insert a person using a WRITE transaction
	const writeTransaction = await session.transaction(TransactionType.WRITE);
	const insertStream = await writeTransaction.query().insert('insert $x isa person, has email "x@email.com";');
	const conceptMaps = await insertStream.collect();
	console.log("Inserted a person with ID: " + conceptMaps[0].get("x").getIID());
	// 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(TransactionType.READ);

	// We can either query and consume the iterator lazily
	let answerStream = await readTransaction.query().match("match $x isa person; get $x; limit 10;");
	for await (const aConceptMapAnswer of answerStream) {
		const person = aConceptMapAnswer.get("x");
		console.log("Retrieved person with id " + person.getIID());
	}

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

	// 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 Core client

Grakn.coreClient(address);

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

Returns

Instantiating a Grakn Cluster client

Grakn.clusterClient(addresses);

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

Array of String

true

Returns

Client

Create a session for a database

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

await client.databases().all();

Retrieves all databases running on the Grakn server.

Returns

Array of String

Check if a database exists

await client.databases().contains(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

await client.databases().create(“database name”);

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

Delete a database

await (await client.databases().get(“database name”)).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

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

await 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

SessionType

Check the session's database

session.database();

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

Returns

String

Close a session

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

Transaction

Check the transaction's type

transaction.type();

Checks the transaction’s type (READ or WRITE)

Returns

TransactionType

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

await 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

await transaction.rollback();

Rolls back the uncommitted changes made via this transaction.

Returns

void

Close a read transaction

await transaction.close();

Closes the transaction.

Returns

void

QueryManager

Execute a Graql Match query

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

Performs a Graql Match query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Match Aggregate query

await transaction.query().matchAggregate(query, 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.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Match Group query

transaction.query().matchGroup(query, 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.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Match Group Aggregate query

transaction.query().matchGroupAggregate(query, 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.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Insert query

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

Performs a Graql Insert query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Insert query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Delete query

await transaction.query().delete(query, options);

Performs a Graql Delete query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Delete query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Update query

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

Performs a Graql Update query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Update query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Explain query

transaction.query().explain(explainable, 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

Execute a Graql Define query

await transaction.query().define(query, options);

Performs a Graql Define query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Define query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Undefine query

await transaction.query().undefine(query, options);

Performs a Graql Undefine query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Undefine query to be executed.

string

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 an iterator of all the concepts in this ConceptMap.

Returns

Iterator of Concept

Retrieve a concept corresponding to a specific variable

concept_map.get(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

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

numeric.asNumber();

Returns

number

Checks if the type of an aggregate answer is a number

numeric.isNumber();

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

Array of ConceptMaps

Explainables

Retrieve explainable relation

conceptMap.explainables().relation(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(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(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

number

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

Stream

Some transaction queries return streams of answers. In addition to the method below, the items in a stream can be consumed individually using the for await (const element of stream) method.

Convert the stream into array

await iterator.collect();

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

Returns

Array

Convert the stream via a supplied function

iterator.map(function);

Transforms the stream into a new stream by running the supplied function on all the elements.

Returns

Stream

Dependencies

Client Node.js Grakn Core Grakn Cluster Node
2.0.0 2.0.0 2.0.0 >= 14.15
1.8.0 1.8.0 to 1.8.4 N/A >= 6.5
1.7.0 1.7.1, 1.7.2 N/A >= 6.5
1.6.0 1.6.0 to 1.6.2 1.6.2 >= 6.5
1.5.6 1.5.8, 1.5.9 1.5.8 >= 6.5
1.5.5 1.5.8, 1.5.9 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