TypeDB Python Driver
Driver Architecture
To learn about the mechanism that TypeDB drivers use to set up communication with databases running on the TypeDB
Server, refer to the Drivers Overview.
API Reference
To learn about the methods available for executing queries and retrieving their answers using Python, refer to
the API Reference.
Install TypeDB Python Driver through Pip
- Install
typedb-driver
using pip
:
pip install typedb-driver
- If multiple Python versions are available, you may wish to use:
pip3 install typedb-driver
- Make sure the TypeDB Server is running.
- In your python program, import from
typedb.driver
(see Example usage or tests/integration
for examples):
from typedb.driver import *
driver = TypeDB.core_driver(address=TypeDB.DEFAULT_ADDRESS)
Example usage
TypeDB Cloud / Enterprise (Cloud driver)
from typedb.driver import *
class TypeDBExample:
def typedb_example():
with TypeDB.cloud_driver(TypeDB.DEFAULT_ADDRESS, Credentials("admin", "password"), DriverOptions()) as driver:
driver.databases.create("typedb")
database = driver.databases.get("typedb")
try:
tx = driver.transaction(database.name, TransactionType.READ)
result_promise = tx.query("define entity i-cannot-be-defined-in-read-transactions;")
print("The result is still promised, so it needs resolving even in case of errors!")
result_promise.resolve()
except TypeDBDriverException as expected_exception:
print(f"Once the query's promise is resolved, the exception is revealed: {expected_exception}")
finally:
tx.close()
with driver.transaction(database.name, TransactionType.SCHEMA) as tx:
define_query = """
define
entity person, owns name, owns age;
attribute name, value string;
attribute age, value integer;
"""
answer = tx.query(define_query).resolve()
if answer.is_ok():
print(f"OK results do not give any extra interesting information, but they mean that the query "
f"is successfully executed!")
tx.commit()
with driver.transaction(database.name, TransactionType.READ) as tx:
answer = tx.query("match entity $x;").resolve()
rows = list(answer.as_concept_rows())
row = rows[0]
header = list(row.column_names())
column_name = header[0]
concept_by_name = row.get(column_name)
concept_by_index = row.get_index(0)
print(f"Getting concepts by variable names ({concept_by_name.get_label()}) and "
f"indexes ({concept_by_index.get_label()}) is equally correct. ")
if concept_by_name.is_entity_type():
print(f"Both represent the defined entity type: '{concept_by_name.as_entity_type().get_label()}' "
f"(in case of a doubt: '{concept_by_index.as_entity_type().get_label()}')")
answer = tx.query("match attribute $a;").resolve()
rows = [row for row in answer.as_concept_rows()]
for row in rows:
column_names_iter = row.column_names()
column_name = next(column_names_iter)
concept_by_name = row.get(column_name)
if concept_by_name.is_attribute_type():
attribute_type = concept_by_name.as_attribute_type()
print(f"Defined attribute type's label: '{attribute_type.get_label()}', "
f"value type: '{attribute_type.try_get_value_type()}'")
print(f"It is also possible to just print the concept itself: '{concept_by_name}'")
with driver.transaction(database.name, TransactionType.WRITE) as tx:
insert_query = "insert $z isa person, has age 10; $x isa person, has age 20, has name \"John\";"
answer = tx.query(insert_query).resolve()
rows = list(answer.as_concept_rows())
row = rows[0]
for column_name in row.column_names():
inserted_concept = row.get(column_name)
print(f"Successfully inserted ${column_name}: {inserted_concept}")
if inserted_concept.is_entity():
print("This time, it's an entity, not a type!")
header = [name for name in row.column_names()]
x = row.get_index(header.index("x"))
print(
"As we expect an entity instance, we can try to get its IID (unique identification): {x.try_get_iid()}. ")
if x.is_entity():
print(f"It can also be retrieved directly and safely after a cast: {x.as_entity().get_iid()}")
tx.commit()
with driver.transaction(database.name, TransactionType.WRITE) as tx:
queries = ["insert $a isa person, has name \"Alice\";", "insert $b isa person, has name \"Bob\";"]
for query in queries:
tx.query(query)
tx.commit()
with driver.transaction(database.name, TransactionType.WRITE) as tx:
queries = ["insert $c isa not-person, has name \"Chris\";", "insert $d isa person, has name \"David\";"]
promises = []
for query in queries:
promises.append(tx.query(query))
try:
tx.commit()
assert False, "TypeDBDriverException is expected"
except TypeDBDriverException as expected_exception:
print(f"Commit result will contain the unresolved query's error: {expected_exception}")
with driver.transaction(database.name, TransactionType.READ) as tx:
var = "x"
answer = tx.query(f"match ${var} isa person;").resolve()
count = 0
for row in answer.as_concept_rows():
x = row.get(var)
x_type = x.as_entity().get_type().as_entity_type()
count += 1
print(f"Found a person {x} of type {x_type}")
print(f"Total persons found: {count}")
fetch_query = """
match
$x isa! person, has $a;
$a isa! $t;
fetch {
"single attribute type": $t,
"single attribute": $a,
"all attributes": { $x.* },
};
"""
answer = tx.query(fetch_query).resolve()
count = 0
for document in answer.as_concept_documents():
count += 1
print(f"Fetched a document: {document}.")
print(f"This document contains an attribute of type: {document['single attribute type']['label']}")
print(f"Total documents fetched: {count}")
print("More examples can be found in the API reference and the documentation.\nWelcome to TypeDB!")
TypeDB CE (Core driver)
from typedb.driver import *
class TypeDBExample:
def typedb_example():
with TypeDB.core_driver(TypeDB.DEFAULT_ADDRESS, Credentials("admin", "password"), DriverOptions()) as driver:
driver.databases.create("typedb")
database = driver.databases.get("typedb")
try:
tx = driver.transaction(database.name, TransactionType.READ)
result_promise = tx.query("define entity i-cannot-be-defined-in-read-transactions;")
print("The result is still promised, so it needs resolving even in case of errors!")
result_promise.resolve()
except TypeDBDriverException as expected_exception:
print(f"Once the query's promise is resolved, the exception is revealed: {expected_exception}")
finally:
tx.close()
with driver.transaction(database.name, TransactionType.SCHEMA) as tx:
define_query = """
define
entity person, owns name, owns age;
attribute name, value string;
attribute age, value integer;
"""
answer = tx.query(define_query).resolve()
if answer.is_ok():
print(f"OK results do not give any extra interesting information, but they mean that the query "
f"is successfully executed!")
tx.commit()
with driver.transaction(database.name, TransactionType.READ) as tx:
answer = tx.query("match entity $x;").resolve()
rows = list(answer.as_concept_rows())
row = rows[0]
header = list(row.column_names())
column_name = header[0]
concept_by_name = row.get(column_name)
concept_by_index = row.get_index(0)
print(f"Getting concepts by variable names ({concept_by_name.get_label()}) and "
f"indexes ({concept_by_index.get_label()}) is equally correct. ")
if concept_by_name.is_entity_type():
print(f"Both represent the defined entity type: '{concept_by_name.as_entity_type().get_label()}' "
f"(in case of a doubt: '{concept_by_index.as_entity_type().get_label()}')")
answer = tx.query("match attribute $a;").resolve()
rows = [row for row in answer.as_concept_rows()]
for row in rows:
column_names_iter = row.column_names()
column_name = next(column_names_iter)
concept_by_name = row.get(column_name)
if concept_by_name.is_attribute_type():
attribute_type = concept_by_name.as_attribute_type()
print(f"Defined attribute type's label: '{attribute_type.get_label()}', "
f"value type: '{attribute_type.try_get_value_type()}'")
print(f"It is also possible to just print the concept itself: '{concept_by_name}'")
with driver.transaction(database.name, TransactionType.WRITE) as tx:
insert_query = "insert $z isa person, has age 10; $x isa person, has age 20, has name \"John\";"
answer = tx.query(insert_query).resolve()
rows = list(answer.as_concept_rows())
row = rows[0]
for column_name in row.column_names():
inserted_concept = row.get(column_name)
print(f"Successfully inserted ${column_name}: {inserted_concept}")
if inserted_concept.is_entity():
print("This time, it's an entity, not a type!")
header = [name for name in row.column_names()]
x = row.get_index(header.index("x"))
print(
"As we expect an entity instance, we can try to get its IID (unique identification): {x.try_get_iid()}. ")
if x.is_entity():
print(f"It can also be retrieved directly and safely after a cast: {x.as_entity().get_iid()}")
tx.commit()
with driver.transaction(database.name, TransactionType.WRITE) as tx:
queries = ["insert $a isa person, has name \"Alice\";", "insert $b isa person, has name \"Bob\";"]
for query in queries:
tx.query(query)
tx.commit()
with driver.transaction(database.name, TransactionType.WRITE) as tx:
queries = ["insert $c isa not-person, has name \"Chris\";", "insert $d isa person, has name \"David\";"]
promises = []
for query in queries:
promises.append(tx.query(query))
try:
tx.commit()
assert False, "TypeDBDriverException is expected"
except TypeDBDriverException as expected_exception:
print(f"Commit result will contain the unresolved query's error: {expected_exception}")
with driver.transaction(database.name, TransactionType.READ) as tx:
var = "x"
answer = tx.query(f"match ${var} isa person;").resolve()
count = 0
for row in answer.as_concept_rows():
x = row.get(var)
x_type = x.as_entity().get_type().as_entity_type()
count += 1
print(f"Found a person {x} of type {x_type}")
print(f"Total persons found: {count}")
fetch_query = """
match
$x isa! person, has $a;
$a isa! $t;
fetch {
"single attribute type": $t,
"single attribute": $a,
"all attributes": { $x.* },
};
"""
answer = tx.query(fetch_query).resolve()
count = 0
for document in answer.as_concept_documents():
count += 1
print(f"Fetched a document: {document}.")
print(f"This document contains an attribute of type: {document['single attribute type']['label']}")
print(f"Total documents fetched: {count}")
print("More examples can be found in the API reference and the documentation.\nWelcome to TypeDB!")