SurrealDB Docs Logo

Enter a search query

select().live()

Initiate live queries for a live stream of notifications.

Method Syntax
db.select(resource).live()

Arguments

ArgumentDescription
resource

The table name or a record ID to select.

Example usage: Listen for live updates

The following example requires adding the futures crate with cargo add futures in order to work with the results of the async stream. Once run, the program will continue to wait and listen for events for the person table to happen.

use futures::StreamExt; use serde::Deserialize; use surrealdb::engine::remote::ws::Ws; use surrealdb::opt::auth::Root; use surrealdb::{Notification, Surreal}; use surrealdb::RecordId; #[derive(Debug, Deserialize)] struct Person { id: RecordId, } // Handle the result of the live query notification fn handle(result: Result<Notification<Person>, surrealdb::Error>) { println!("Received notification: {:?}", result); } #[tokio::main] async fn main() -> surrealdb::Result<()> { let db = Surreal::new::<Ws>("127.0.0.1:8000").await?; db.signin(Root { username: "root", password: "root", }) .await?; db.use_ns("ns").use_db("db").await?; // Select the "person" table and listen for live updates. let mut stream = db.select("person").live().await?; // Process updates as they come in. while let Some(result) = stream.next().await { // Do something with the notification handle(result); } Ok(()) }

Then connect to it using Surrealist or open a new terminal window with the following command.

surreal sql --namespace ns --database db --user root --pass root --pretty

You can then use queries like the following to work with some person records.

CREATE person; UPDATE person SET is_nice_person = true; DELETE person;

The following output will then show up in the terminal window running the Rust example.

Received notification: Ok(Notification { query_id: b55d31dc-e657-4a6b-a32b-f5abed4ef459, action: Create, data: Person { id: Thing { tb: "person", id: String("334mabva9ibitsypabm5") } } }) Received notification: Ok(Notification { query_id: b55d31dc-e657-4a6b-a32b-f5abed4ef459, action: Update, data: Person { id: Thing { tb: "person", id: String("334mabva9ibitsypabm5") } } }) Received notification: Ok(Notification { query_id: b55d31dc-e657-4a6b-a32b-f5abed4ef459, action: Delete, data: Person { id: Thing { tb: "person", id: String("334mabva9ibitsypabm5") } } })

See also

On this page

© SurrealDB GitHub Discord Community Cloud Features Releases Install