Edit on Github

Installation

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

npm install typedb-client

Quickstart

First make sure that the TypeDB server is running.

In your source, require typedb-client.

const { TypeDB } = require("typedb-client");

Instantiate a client and open a session.

const { TypeDB, SessionType } = require("typedb-client");

async function openSession (database) {
	const client = TypeDB.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 { TypeDB, SessionType, TransactionType } = require("typedb-client");

async function createTransactions (database) {
	const client = TypeDB.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 { TypeDB, SessionType, TransactionType } = require("typedb-client");

async function runBasicQueries(database) {
	const client = TypeDB.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").iid);
	// 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.iid);
	}

	// 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.iid);
    });

	// 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 TypeQL queries.

To view examples of running various queries using the Node.js client, head over to their dedicated documentation pages as listed below:

API Reference

Instantiating a TypeDB Core client

TypeDB.coreClient(address);

In order to communicate with TypeDB Core databases via sessions and transactions, we first need to instantiate a TypeDB Core client. The created object connects our application with the running TypeDB Server.

Accepts

Param Description Type Required Default

address

The address (host:port) on which the TypeDB Server is running

String

true

Returns

Instantiating a TypeDB Cluster client

TypeDB.clusterClient(addresses, credential)

In order to communicate with TypeDB Cluster databases via sessions and transactions, we first need to instantiate a TypeDB Cluster client. The created object connects our application with the running TypeDB Cluster. Please note that Node.js and Python clients always have TLS enabled, and therefore can only connect to a server that is setup with TLS.

Accepts

Param Description Type Required Default

addresses

All addresses (host:port) on which TypeDB Cluster nodes are running

Array of String

true

credential

User credential and TLS encryption setting

TypeDBCredential

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

TypeDBOptions

false

N/A

Returns

Retrieve all databases

await client.databases.all();

Retrieves all databases running on the TypeDB 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

Retrieve a database

client.databases.get(database);

Retrieve a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to retrieve.

string

true

N/A

Returns

Database

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

Retrieve all users

await client.users.all();

Retrieves all users running on the TypeDB server.

Returns

Array of String

Check if a user exists

await client.users.contains(user);

Checks if a user with the given name exists

Accepts

Param Description Type Required Default

user

The user name to be checked.

String

true

N/A

Create a user

await client.users.create(“user name”);

Create a user with the given name.

Accepts

Param Description Type Required Default

user

The name of the user to be created.

String

true

N/A

Returns

void

Retrieve a user

client.users.get(String user);

Retrieve a user with the given name.

Accepts

Param Description Type Required Default

user

The name of the user to retrieve.

string

true

N/A

Returns

user

Delete a user

await (await client.users.get(“user name”)).delete();

Deletes a user with the given name.

Accepts

Param Description Type Required Default

user

The name of the user 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.

TypeDBOptions

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 TypeDBOptions can be used to override the default server behaviour query processing. Use TypeDBOptions.core() to create a new TypeDB Core options object, or TypeDBOptions.cluster() for TypeDB Cluster.

The options are:

  • infer: whether to enable inference for the provided query (only settable at transaction level and above) (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, outputs reasoning tracing graphs 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)

TypeDBClusterOptions 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 TypeQL query can be executed.

Returns

Commit a write transaction

await transaction.commit();

Commits the changes made via this transaction to the TypeDB 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 TypeQL Match query

transaction.query.match(query, options);

Performs a TypeQL Match query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Match query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Match Aggregate query

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

Performs a TypeQL Match Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Match Aggregate query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Match Group query

transaction.query.matchGroup(query, options);

Performs a TypeQL Match Group query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Match Group query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Match Group Aggregate query

transaction.query.matchGroupAggregate(query, options);

Performs a TypeQL Match Group Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Match Group Aggregate query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Insert query

transaction.query.insert(query, options);

Performs a TypeQL Insert query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Insert query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Delete query

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

Performs a TypeQL Delete query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Delete query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Update query

transaction.query.update(query, options);

Performs a TypeQL Update query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Update query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Explain query

transaction.query.explain(explainable, options);

Performs a TypeQL Explain query in the transaction.

Accepts

Param Description Type Required Default

explainable

The Explainable to be explained.

ConceptMap.Explainable

true

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Define query

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

Performs a TypeQL Define query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Define query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

default TypeDBOptions - uses server defaults

Returns

Execute a TypeQL Undefine query

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

Performs a TypeQL Undefine query in the transaction.

Accepts

Param Description Type Required Default

query

The TypeQL Undefine query to be executed.

string

true

N/A

options

Specify query options

TypeDBOptions

false

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

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

NumericGroup

Retrieve the concept that is the group owner

numericGroup.owner;

Returns

Retrieve the Numeric answer of the group

numericGroup.numeric;

Returns

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(ownerVar, attributeVar);

Retrieves the explainable attribute ownership with the pair of (owner, attribute) variable names.

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

Version Compatibility

Client Node.js TypeDB TypeDB Cluster Node
2.2.0 2.1.2 to 2.3.3 2.1.2 to 2.3.0 >= 14.15
2.1.1 2.1.2 to 2.3.3 2.1.2 to 2.3.0 >= 14.15
2.1.0 2.1.0 2.1.0 >= 14.15
2.0.1 2.0.2 2.0.2 >= 14.15
2.0.0 2.0.0, 2.0.1 2.0.0, 2.0.1 >= 14.15
1.8.0 1.8.0 to 1.8.4 N/A >= 6.5