Manage Dgraph transactions
mainDgraph supports two types of transactions:
- Read-Write Transactions: Created via
newTransaction(). These allow both queries and mutations. It is best practice to callTransaction#discard()in afinallyblock to clean up resources. - Read-Only Transactions: Created via
newReadOnlyTransaction(). These can share read timestamps across multiple transactions for lower latency. They can also be set assetBestEffort(true)to relax linearizability requirements.
Note: Calling discard() after a successful commit() is a no-op and is safe.
// Read-write transaction pattern
Transaction txn = dgraphClient.newTransaction();
try {
// ... operations
txn.commit();
} finally {
txn.discard();
}
// Best-effort read-only transaction
Transaction bestEffortTxn = dgraphClient.newReadOnlyTransaction()
.setBestEffort(true);