Live Queries

Turn any SDBQL query into a real-time stream. Get instant updates whenever the result set changes.

Overview

Live Queries go beyond simple changefeeds. Instead of just subscribing to raw collection events, you send a full SDBQL query. The server monitors all data accessed by that query and automatically re-runs and pushes the new results whenever any dependency changes.

Automatic Filter Updates
Reactive Sorting & Limits

WebSocket Protocol

Connect to the same changefeed endpoint, but send a `live_query` message type:

ws://host:port/_api/ws/changefeed

Request Payload

live_query.json
{
    "type": "live_query",
    "database": "_system",
    "query": "FOR user IN users FILTER user.age > 21 RETURN user",
    "id": "query_1"
  }

Response Events

The server will immediately execute the query and send a `query_result` message. After that, it will re-send the same message whenever a change occurs in the underlying data.

Query Result FromServer
{
    "type": "query_result",
    "id": "query_1",
    "result": [
      { "name": "Alice", "age": 25 },
      { "name": "Bob", "age": 30 }
    ]
  }

Example Code

Here is how to implement a Live Query React hook pattern in JavaScript:

live-query-example.js
// 1. Establish WebSocket Connection
function startLiveQuery(query, onUpdate) {
    const token = 'YOUR_JWT_TOKEN';
    const ws = new WebSocket(`ws://localhost:6745/_api/ws/changefeed?token=${token}`);

    ws.onopen = () => {
        console.log('Connected');
        // 2. Send the Query
        ws.send(JSON.stringify({
            type: "live_query",
            database: "_system",
            query: query
        }));
    };

    ws.onmessage = (event) => {
        const msg = JSON.parse(event.data);
        
        if (msg.type === "query_result") {
            // 3. Receive full updated result set
            onUpdate(msg.result);
        }
    };
    
    return ws;
}

// Usage
const query = "FOR doc IN logs FILTER doc.level == 'ERROR' SORT doc.timestamp DESC LIMIT 5 RETURN doc";

startLiveQuery(query, (results) => {
    console.clear();
    console.log("Latest 5 Errors:");
    console.table(results);
});

Best Use Cases

Real-time Leaderboards

Use SORT score DESC LIMIT 10 to keep a leaderboard always up to date without polling.

Activity Feeds

Filter by user ID and sort by time to show a user's latest actions instantly.

System Monitoring

Query logs with specific severity levels and get alerted immediately when they appear.