← All lessons/Querying with SaQL
14
Querying with SaQL

Sort Order & Cursor Pagination

Sort scan results and paginate through large result sets using after_hlc.

Prerequisite: Lesson 11 complete

What you'll learn

  • order: 'asc' (default) vs order: 'desc'
  • desc collects all matching records then reverses — filters apply before reversal
  • after_hlc cursor — exclusive > comparison, no duplicates
  • End-of-page detection: response.length < limit
  • Pagination with filter — filter + after_hlc combined
Challenge

Write 30 records. Paginate in pages of 10 using a loop. Confirm total matches type: count.

Interactive Walkthrough

What you'll learn

Sort scan results, paginate through large result sets efficiently using after_hlc.

Sort ascending (default)

curl -s -X POST http://localhost:7475/v1/agents/events/query \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \
  -d '{"type": "scan", "limit": 5, "order": "asc"}' \
  | python3 -m json.tool

Sort descending (newest first)

curl -s -X POST http://localhost:7475/v1/agents/events/query \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \
  -d '{"type": "scan", "limit": 5, "order": "desc"}' \
  | python3 -m json.tool

Note: order: "desc" collects all matching records then reverses — filters are applied before reversal.

Cursor pagination

The cursor is ts_hlc from the last record on the previous page. The comparison is exclusive (>), so you never get duplicate records.

`bash # Page 1 LAST_HLC=$(curl -s -X POST http://localhost:7475/v1/agents/events/query \ -H "Content-Type: application/json" \ -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \ -d '{"type": "scan", "limit": 10}' \ | python3 -c "import sys,json; r=json.load(sys.stdin)['records']; print(r[-1]['ts_hlc'])")

# Page 2 curl -s -X POST http://localhost:7475/v1/agents/events/query \ -H "Content-Type: application/json" \ -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \ -d "{\"type\": \"scan\", \"limit\": 10, \"after_hlc\": $LAST_HLC}" \ | python3 -m json.tool `

When fewer records than limit are returned, you have reached the end.

Pagination with filter

curl -s -X POST http://localhost:7475/v1/agents/events/query \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer spx_root_YOUR_ROOT_KEY" \
  -d '{
    "type": "scan",
    "limit": 10,
    "after_hlc": 1751900065536000,
    "filter": {"field": "type", "op": "eq", "value": "page_view"}
  }' | python3 -m json.tool

Challenge

Write 30 records. Paginate through all of them in pages of 10 using a loop, accumulating the total count. Confirm the total matches type: "count".

---

← Previous
Lesson 13: Compound Filters (AND / OR / NOT)
Next →
Lesson 15: Aggregate Functions