Live queries
The Python SDK supports real-time live queries that stream changes from the database directly to your application. When records matching a live query are created, updated, or deleted, the SDK delivers notifications through a generator that you can iterate over.
This page covers how to start live queries, subscribe to change notifications, and stop queries when they are no longer needed.
Note
API References
| Method | Description |
|---|---|
db.live(table, diff?) | Starts a live query on a table and returns a query UUID |
db.subscribe_live(query_uuid) | Subscribes to notifications from a live query |
db.kill(query_uuid) | Stops a running live query |
Starting a live query
The .live() method registers a live query on a table and returns a UUID that identifies the query. You can optionally pass diff=True to receive changes in JSON Patch (RFC 6902) format instead of full record snapshots.
To receive JSON Patch diffs instead of full records, pass diff=True.
Subscribing to changes
After starting a live query, call .subscribe_live() with the returned UUID to obtain a stream of notifications. The async variant returns an AsyncGenerator and the sync variant returns a Generator. Each notification is a dictionary containing action and result keys.
The action field is one of "CREATE", "UPDATE", or "DELETE", and the result field contains the affected record (or the JSON Patch operations when diff=True was used).
Stopping a live query
When you no longer need to receive notifications, call .kill() with the query UUID to stop the live query on the server. This also ends the generator returned by .subscribe_live().
Subscribing to live queries from SurrealQL
You can also initiate a live query using a LIVE SELECT statement through the .query() method. The query returns a UUID that can be passed to .subscribe_live() in the same way as a UUID returned by .live().
This approach is useful when you need the filtering capabilities of SurrealQL, such as selecting specific fields or applying WHERE clauses.
Learn more
Surreal API reference for method signatures and parameters
Connecting to SurrealDB for WebSocket connection setup
SurrealQL LIVE SELECT for the query language syntax