Edit on Github

Installation

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

pip install typedb-client

If multiple Python versions are available, you may wish to use

pip3 install typedb-client

Resources

Quickstart

First make sure, the TypeDB server is running and that you have created the social network database as detailed in the quickstart example before running the following.

In the interpreter or in your source, import everything from typedb.client.

from typedb.client import *

Instantiate a client and open a session.

from typedb.client import *

with TypeDB.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## session is open
        pass
    ## session is closed
## client is closed

Create transactions to use for reading and writing data.

from typedb.client import *

with TypeDB.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## creating a write transaction
        with session.transaction(TransactionType.WRITE) as write_transaction:
            ## write transaction is open
            ## write transaction must always be committed (closed)
            write_transaction.commit()

        ## creating a read transaction
        with session.transaction(TransactionType.READ) as read_transaction:
            ## read transaction is open
            ## if not using a `with` statement, we must always close the read transaction like so
            # read_transaction.close()
            pass

Running basic retrieval and insertion queries.

from typedb.client import *

with TypeDB.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## Insert a Person using a WRITE transaction
        with session.transaction(TransactionType.WRITE) as write_transaction:
            insert_iterator = write_transaction.query().insert('insert $x isa person, has email "x@email.com";')
            concepts = [ans.get("x") for ans in insert_iterator]
            print("Inserted a person with ID: {0}".format(concepts[0].get_iid()))
            ## to persist changes, write transaction must always be committed (closed)
            write_transaction.commit()

        ## Read the person using a READ only transaction
        with session.transaction(TransactionType.READ) as read_transaction:
            answer_iterator = read_transaction.query().match("match $x isa person; get $x; limit 10;")

            for answer in answer_iterator:
                person = answer.get("x")
                print("Retrieved person with id " + person.get_iid())

        ## Or query and consume the iterator immediately collecting all the results
        with session.transaction(TransactionType.READ) as read_transaction:
            answer_iterator = read_transaction.query().match("match $x isa person; get $x; limit 10;")
            persons = [ans.get("x") for ans in answer_iterator]
            for person in persons:
                print("Retrieved person with id " + person.get_iid())

        ## if not using a `with` statement, then we must always close the session and the read transaction
        # read_transaction.close()
        # session.close()
        # client.close()
[Important] Remember that transactions always need to be closed. The safest way is to use the `with ...` syntax which auto-closes at the end of the `with` block. Otherwise, remember to call `transaction.close()` explicitly.

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 Python client, head over to their dedicated documentation pages as listed below.


API Reference

Instantiating a TypeDB Core client

TypeDB.core_client(address, parallelisation)

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

parallelisation

The number of threads to use for server communication

int

false

2

Returns

Instantiating a TypeDB Cluster client

TypeDB.cluster_client(addresses, credential, parallelisation)

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. When instantiating a TypeDB Cluster client, it is sufficient to supply the address of just one server, as the addresses of the other servers will be relayed back to the client. However, to avoid failure in the unlikely event that the single server whose address is provided fails before communicating the addresses of the others, it is best practice to supply addresses of all the servers.

Accepts

Param Description Type Required Default

addresses

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

list of String

true

credential

User credential and TLS encryption setting

TypeDBCredential

true

parallelisation

The number of threads to use for server communication

int

false

2

Returns

Client

Create a session for a database

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

client.databases().all()

Retrieves all databases running on the TypeDB server.

Returns

list of Database

Check if a database exists

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

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

None

Retrieve a database

client.databases().get(“database name”);

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

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

None

Retrieve all users

client.users().all()

Retrieves all users running on the TypeDB server.

Returns

list of User

Check if a user exists

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

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

None

Retrieve a user

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

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

client.users().delete(“username”)

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

None

Set a user's password

client.users().passwordSet(“username”, “password”)

Deletes a user with the given name.

Accepts

Param Description Type Required Default

user

The name of the user to update the password of.

String

true

N/A

password

User’s new password.

String

true

N/A

Returns

None

Close a client

client.close()

Closes the client. Before instantiating a new client, the client that’s currently open should first be closed.

Returns

None

Session

Open a transaction

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

session.is_open()

Checks whether a session is presently open.

Returns

boolean

Check the session's type

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

session.close()

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

Returns

None

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, and only affects read transactions) (default: False)
  • explain: whether to enable explanations for the provided query (only affects read transactions) (default: False)
  • parallel: whether the server should use parallel or single-threaded execution (default: True)
  • prefetch_size: a guideline number of answers that the server should send before the client issues a fresh request (default: 50)
  • trace_inference: 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)
  • session_idle_timeout_millis: this timeout allows the server to close sessions if a client terminates or becomes unresponsive (default: 30_000)
  • transaction_timeout_millis: this timeout will automatically kill transactions, preventing memory leaks in unclosed transactions (default: 300_000)
  • schema_lock_acquire_timeout_millis: how long the client should wait if opening a session or transaction is blocked by a schema write lock (default: 10_000)

TypeDBClusterOptions has an additional option:

  • read_any_replica: enables reading data from any replica, potentially boosting read throughput (default: False)

Transaction

Check the transaction's type

transaction.transaction_type()

Checks the transaction’s type (READ or WRITE)

Returns

TransactionType

Check if the transaction is open

transaction.is_open()

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

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

None

Rollback a write transaction

transaction.rollback()

Rolls back the uncommitted changes made via this transaction.

Returns

None

Close a read transaction

transaction.close()

Closes the transaction.

Returns

None

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

Iterator of ConceptMap

Execute a TypeQL Match Aggregate query

transaction.query().match_aggregate(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().match_group(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

Iterator of ConceptMapGroup

Execute a TypeQL Match Group Aggregate query

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

Iterator of NumericGroup

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

Iterator of ConceptMap

Execute a TypeQL Delete query

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

Iterator of ConceptMap

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

Iterator of Explanation

Execute a TypeQL Define query

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

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

concept_map.map()

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

Returns

Dictionary of String to Concept

Retrieve concepts

concept_map.concepts()

Return an iterable collection of all the concepts in this ConceptMap.

Returns

Iterable of Concept

Retrieve a concept corresponding to a specific variable

conceptMap.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 as an integer

numeric.as_int();

Returns

int

Retrieve numeric value of an aggregate answer as a float

numeric.as_float();

Returns

float

Checks if the type of an aggregate answer is an integer

numeric.is_int();

Returns

boolean

Checks if the type of an aggregate answer is a float

numeric.is_float();

Returns

boolean

Checks if the type of an aggregate answer is not a number

concept_map_group.is_NaN()

Returns

boolean

ConceptMapGroup

Retrieve the concept that is the group owner

concept_map_group.owner()

Returns

Retrieve the ConceptMaps of the group

concept_map_group.concept_maps();

Returns

List of ConceptMaps

NumericGroup

Retrieve the concept that is the group owner

numeric_group.owner()

Returns

Retrieve the Numeric answer of the group

numeric_group.numeric()

Returns

Explainables

Retrieve explainable relation

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

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

concept_map.explainables().ownership(owner_var, attribute_var);

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

concept_map.explainables().relations();

Retrieves all of this ConceptMap’s explainable relations.

Returns

Dictionary of String to ConceptMap.Explainable

Retrieve explainable attributes

concept_map.explainables().attributes();

Retrieves all of this ConceptMap’s explainable attributes.

Returns

Dictionary of String to ConceptMap.Explainable

Retrieve explainable ownerships

concept_map.explainables().ownerships();

Retrieves all of this ConceptMap’s explainable attribute ownerships.

Returns

Dictionary of (String, String) to ConceptMap.Explainable

Explainable

Retrieve conjunction

explainable.conjunction()

Retrieves the subquery of the original query that is actually being explained.

Returns

String

Retrieve ID

explainable.explainable_id()

Retrieves the unique ID that identifies this Explainable.

Returns

int

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.variable_mapping()

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

Version Compatibility

Client Python TypeDB TypeDB Cluster Python
2.16.1 2.16.1 2.16.1 >= 3.6
2.12.0 to 2.14.3 2.12.0 to 2.15.0 2.13.0 to 2.15.0 >= 3.6
2.9.0 to 2.11.1 2.9.0 to 2.11.1 2.9.0 to 2.11.2 >= 3.6
2.8.0 2.8.0 N/A >= 3.6
2.6.0 to 2.6.3 2.6.0 to 2.7.1 N/A >= 3.6
2.4.0 to 2.5.0 2.1.2 to 2.5.0 2.5.0 >= 3.6
2.2.0 2.1.2 to 2.5.0 2.1.2 to 2.3.0 >= 3.6
2.1.1 2.1.2 2.1.2 >= 3.6
2.1.0 2.1.0 2.1.0 >= 3.6
2.0.1 2.0.2 2.0.2 >= 3.6
2.0.0 2.0.0 to 2.0.1 2.0.0 to 2.0.1 >= 3.6
1.8.0 1.8.0 to 1.8.4 N/A >= 3.5, < 3.8