Lesson 6: Building applications
Driver setup
-
The official TypeDB Python driver package can be installed with:
pip install typedb-driver -
The following classes must be imported in order to use the Python driver in any codebase:
from typedb.driver import TypeDB, Credentials, DriverOptions
Managing databases
-
The
TypeDB.drivermethod is used to instantiate a new driver object.driver: TypeDBDriver = TypeDB.driver(ADDRESS, credentials, options) -
The
TypeDBDriver.databases.createmethod is used to create a new database.driver.databases.create(DB)
Transactions
-
The
TypeDBSession.transactionmethod is used to instantiate a new transaction. The transaction type is specified using theREAD,WRITE, orSCHEMAvalue of theTransactionTypeenum.transaction: TypeDBTransaction = driver.transaction(DB, TransactionType.READ) -
Drivers and transaction objects are ideally always be instantiated using a context manager so that their destructors are called automatically, otherwise call `.close() manually on them
with TypeDB.driver(ADDRESS, credentials, options) as driver: with session.transaction(DB, TransactionType.READ) as transaction: # code goes here -
The
TypeDBTransaction.commitmethod is used to commit a transaction.transaction.commit()
Executing queries
-
The
TypeDBTransaction.query()method is used to submit queries.results: Promise[QueryAnswer] = transaction.query(QUERY) -
Typically you submit and resolve the promise catch any errors that are thrown
transaction.query(QUERY).resolve()
Processing results
-
Each result of a query that ends in
fetchreturns Documents. The top-level dictionary has fields corresponding to thefetchclause structure. -
If you know you aren’t catching errors at query time and don’t care about the returned values (such as when doing straight inserts), you can submit without resolving or reading answers to boost performance