# Querying documents
Source: https://sovaria.in/docs/document-queries

Filter collections by any field with AND / OR, query every subcollection with the same name (collection groups), sort, page with cursors, count, sum and average matches, and index what you query.

A query reads one collection (or subcollection, like `users/alice/posts`) and returns the documents whose fields match its filters, in the order you ask for. It runs in your project's Postgres as the caller, so [collection rules](https://sovaria.in/docs/documents-overview) and row policies decide exactly what each user gets back — the same as reading one document.

(Diagram: How a document query runs — Values are always bound parameters; field paths and the collection are quoted by the database driver so Postgres can use your indexes.)

## Filters

| Operator | Matches documents where the field… |
|---|---|
| `==`, `!=` | equals / exists and does not equal the value |
| `<`, `<=`, `>`, `>=` | compares with the value — only values of the **same type** match (`"1999"` is not `> 1900`) |
| `in`, `not-in` | equals one of / exists and equals none of up to 30 values |
| `array-contains` | is an array holding the value (objects must match exactly) |
| `array-contains-any` | is an array holding at least one of up to 30 values |

- Use dotted paths for nested fields: `address.city`. A key with other characters goes in backticks: ``meta.`first-seen` ``.
- The document id is `__key__`: `where("__key__", "in", ["a", "b"])`.
- Ordering by a field leaves out documents that don't have it. Ties are broken by document id.
- Up to 30 filters and 8 order-by fields per query; `limit` up to your plan's documents per query.

## OR and nested filters

Filters are combined with AND. For OR, put a group in `where`: `or(…)` matches documents that match any of its filters, and `and(…)` nests inside it — the same as Firestore's `or()` / `and()`. Groups nest up to 4 levels, and a query can expand to at most **30 OR terms** (an AND of two 6-filter ORs is 36, so it is refused). Over HTTP a group is `{"or": [...]}` or `{"and": [...]}`.

JavaScript:
```js
import { or, and, filter } from '@sovaria/sdk'

// status is open AND (priority >= 3 OR (assignee is me AND due this week))
const tasks = await sov.collection('tasks')
  .where('status', '==', 'open')
  .where(or(filter('priority', '>=', 3), and(filter('assignee', '==', uid), filter('due', '<', weekEnd))))
  .get()

// Firestore code works unchanged
import { query, where, or, getDocs } from '@sovaria/sdk/firestore'
await getDocs(query(collection(db, 'tasks'), or(where('priority', '>=', 3), where('pinned', '==', true))))
```

Python:
```python
from sovaria import or_, and_, field_filter

tasks = await (sov.collection("tasks")
               .where("status", "==", "open")
               .where(or_(field_filter("priority", ">=", 3),
                          and_(field_filter("assignee", "==", uid), field_filter("due", "<", week_end))))
               .get())
```

Dart:
```dart
await sov.collections.collection('tasks').query(where: [
  ['status', '==', 'open'],
  Filter.or([['priority', '>=', 3], Filter.and([['assignee', '==', uid], ['due', '<', weekEnd]])]),
]);
```

HTTP:
```bash
curl -s -X POST $URL/api/v1/data/doc/_query/tasks \
  -d '{"where":[["status","==","open"],
                {"or":[["priority",">=",3],{"and":[["assignee","==","u1"],["due","<","2026-10-30"]]}]}]}' …
```

CLI:
```bash
sov collections query tasks --where '[{"or":[["priority",">=",3],["pinned","==",true]]}]' --limit 50
```

## Collection groups

A collection group reads every collection with the same id at any depth, like Firestore's `collectionGroup`: `comments` covers `comments`, `posts/p1/comments` and `users/u1/posts/p9/comments`. Filters, sorting, cursors, `count` and aggregations work the same; in a group the document identity (`__key__`, the tiebreak and cursors) is the **full document path**, so two `comments/a` under different parents never collide.

JavaScript:
```js
const flagged = await sov.collectionGroup('comments')
  .where('flagged', '==', true).orderBy('at', 'desc').limit(50).get()
flagged.docs.forEach((d) => console.log(d.path))   // posts/p1/comments/c7, users/u2/comments/c1, …
const next = await sov.collectionGroup('comments').where('flagged', '==', true)
  .orderBy('at', 'desc').limit(50).startAfter(flagged.docs.at(-1)).get()

// Firestore code works unchanged
import { collectionGroup, query, where, getDocs } from '@sovaria/sdk/firestore'
await getDocs(query(collectionGroup(db, 'comments'), where('flagged', '==', true)))
```

Python:
```python
flagged = await (sov.collection_group("comments")
                 .where("flagged", "==", True).order_by("at", "desc").limit(50).get())
total = await sov.collection_group("comments").where("flagged", "==", True).count()
```

Dart:
```dart
final page = await sov.collections.collectionGroup('comments')
    .query(where: [['flagged', '==', true]], orderBy: [['at', 'desc']], limit: 50);
```

Swift:
```swift
let page = try await sov.collections.collectionGroup("comments")
    .query(where: [["flagged", "==", true]], orderBy: [["at", "desc"]], limit: 50)
```

Kotlin:
```kotlin
val page = sov.collections.collectionGroup("comments")
    .query(where = listOf(listOf("flagged", "==", true)), orderBy = listOf(listOf("at", "desc")), limit = 50)
```

HTTP:
```bash
curl -s -X POST $URL/api/v1/data/doc/_query/comments \
  -d '{"collection_group": true, "where": [["flagged","==",true]], "order_by": [["at","desc"]], "limit": 50}' …
# → {"documents":[…], "collection_group":"comments", "collections_skipped":0, "next_cursor":{…}}
```

CLI:
```bash
sov collections query comments --group --where '[["flagged","==",true]]' --order-by '[["at","desc"]]'
sov collections count comments --group
```

**Who sees what.** Your collection rules are checked once per collection *pattern* in the group, with document ids written as `*` — the same patterns you use in rules (`posts/*/comments`). A pattern your rules refuse is checked again per concrete collection (`posts/p1/comments`, up to 50), and whatever is still refused is left out of the results. A pattern your rules allow is also checked per concrete collection, so a rule that denies one sub-collection (`posts/p1/comments`) is honoured; up to 500 concrete collections are checked per query, and any past that are left out rather than read unchecked (the answer then has `scope_truncated: true` and `collections_unchecked`). The answer's `collections_skipped` says how many collections were left out. If nothing in the group is readable the query is refused with `403`. Row policies apply to every document as usual. Rules can tell a group read apart: it is checked with the pattern as the resource and `collection_group` set in the data-access context.

- For speed, the first group query builds a group index on every project (in the background, without blocking writes; it doesn't count toward your plan's indexes). For sorting or ranges over a large group, create a composite index with scope `collection_group` — the `index_hint` says so.
- Live listeners work on groups too: `sov.collectionGroup('comments').onSnapshot(…)` gets every added, modified and removed comment under any parent, keyed by path. Renewing a listener checks your rules per pattern again, so collections a user loses access to drop out.
- Offline, the SDK answers group queries from every cached collection with that id.

## Count, sum and average

Aggregations run in your project's Postgres and return only the numbers, so they cost one query however many documents match. Ask for up to 5 at once. `sum` and `average` use numeric values only (other types are skipped, like Firestore); `average` is `null` when no matching document has a number there. With `limit`, they cover the first `limit` results in `orderBy` order; without, every match. The same rules and row policies apply as for reading the documents, and every field you aggregate counts as read.

JavaScript:
```js
import { count, sum, average } from '@sovaria/sdk'

const { n, revenue, avgOrder } = await sov.collection('orders')
  .where('status', '==', 'paid')
  .aggregate({ n: count(), revenue: sum('total'), avgOrder: average('total') })

// Firestore code works unchanged
import { getAggregateFromServer, sum as fsum } from '@sovaria/sdk/firestore'
const snap = await getAggregateFromServer(query(collection(db, 'orders')), { revenue: fsum('total') })
snap.data().revenue
```

Python:
```python
from sovaria import count_aggregate, sum_, average

out = await (sov.collection("orders").where("status", "==", "paid")
             .aggregate(n=count_aggregate(), revenue=sum_("total"), avg_order=average("total")))
```

Dart:
```dart
final out = await sov.collections.collection('orders').aggregate(
  {'n': Aggregate.count(), 'revenue': Aggregate.sum('total')},
  where: [['status', '==', 'paid']],
);
```

Swift:
```swift
let out = try await sov.collections.collection("orders").aggregate(
    ["n": Aggregate.count(), "revenue": Aggregate.sum("total")], where: [["status", "==", "paid"]])
```

Kotlin:
```kotlin
val out = sov.collections.collection("orders").aggregate(
    mapOf("n" to Aggregate.count(), "revenue" to Aggregate.sum("total")), where = listOf(listOf("status", "==", "paid")))
```

HTTP:
```bash
curl -s -X POST $URL/api/v1/data/doc/_aggregate/orders \
  -d '{"where":[["status","==","paid"]],
       "aggregations":[{"op":"count"},{"op":"sum","field":"total","alias":"revenue"},{"op":"avg","field":"total"}]}' …
# → {"aggregations":{"count":120,"revenue":48210.5,"avg_total":401.75}}
```

CLI:
```bash
sov collections aggregate orders --sum total --avg total --where '[["status","==","paid"]]'
```

Offline, the SDK answers aggregations from its cache (marked `from_cache`), like queries. For grouping (`GROUP BY`) and anything beyond count, sum and average, use SQL over the collection — see the next section.

JavaScript:
```js
const orders = sov.collection('orders')
const page = await orders
  .where('status', '==', 'paid')
  .where('total', '>=', 50)
  .orderBy('total', 'desc')
  .limit(20)
  .get()
page.docs.forEach((d) => console.log(d.id, d.data, d.version))

// Next page: pass the last snapshot (or page.nextCursor)
const next = await orders.where('status', '==', 'paid').where('total', '>=', 50)
  .orderBy('total', 'desc').limit(20).startAfter(page.docs.at(-1)).get()

const howMany = await orders.where('status', '==', 'paid').count()
```

Python:
```python
orders = sov.collection("orders")
page = await (orders.where("status", "==", "paid").where("total", ">=", 50)
              .order_by("total", "desc").limit(20).get())
for doc in page.docs:
    print(doc.id, doc.data, doc.version)

nxt = await (orders.where("status", "==", "paid").where("total", ">=", 50)
             .order_by("total", "desc").limit(20).start_after(page.docs[-1]).get())

async for doc in orders.where("status", "==", "paid").pages(page_size=500):
    ...   # every match, one request per page
count = await orders.where("status", "==", "paid").count()
```

HTTP:
```bash
curl -s -X POST $URL/api/v1/data/doc/_query/orders \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"where":[["status","==","paid"],["total",">=",50]],
       "order_by":[["total","desc"]], "limit":20,
       "start_after":{"values":[120, "order_481"]}}'
# → {"documents":[{"id","path","data","version","update_time"}…],
#    "has_more":true, "next_cursor":{"values":[…]}, "index_hint":…}

curl -s -X POST $URL/api/v1/data/doc/_count/orders -d '{"where":[["status","==","paid"]]}' …
```

## Cursors and pages

`startAt` / `startAfter` / `endAt` / `endBefore` take either a document snapshot (or `{"key": "id"}` over HTTP — the server reads that document, as you, for its values) or the values of the order-by fields in order, optionally followed by the document id. `limitToLast(n)` returns the last `n` in the same order. Every answer says `has_more` and gives `next_cursor` for the next page.

## Join documents with tables in SQL

Documents and tables live in the same project database, so SQL can read a collection next to your tables with `sov_collection('<collection>')`. It returns one row per document — `id`, `data` (the JSON), `version`, `owner_id`, `created_at`, `updated_at` — for the environment you call from. Subcollections work too: `sov_collection('users/u1/orders')`. Neither Firebase nor Supabase can join their document data with relational tables in one query.

SQL:
```sql
-- Orders (a table) with each customer's name (a document)
SELECT o.id, o.total, c.data->>'name' AS customer, c.data->'address'->>'city' AS city
  FROM orders o
  JOIN sov_collection('customers') c ON c.id = o.customer_id
 WHERE o.created_at > now() - interval '7 days';

-- Documents only: aggregate a collection with SQL
SELECT data->>'plan' AS plan, count(*) FROM sov_collection('accounts') GROUP BY 1;
```

JavaScript:
```js
const { rows } = await sov.data.sql(
  `SELECT o.id, c.data->>'name' AS customer
     FROM orders o JOIN sov_collection('customers') c ON c.id = o.customer_id
    WHERE o.total > $1`, [100])
```

- Access is checked the same way as a query through the documents API: the collection needs `doc:read` in your collection rules (or, for app users, the row policies on `sov_documents` decide), and every table needs its SQL rule. A collection name must be a string literal, so it can be checked before the statement runs.
- Row security on documents still applies inside SQL: each user only gets the documents your row policies let them read.
- It is read-only. Write documents with the documents API so versions, transforms, triggers and listeners keep working.
- Postgres inlines the function, so filters on `id` use the documents index; for filters on fields inside `data`, add a document index (below) or an expression index.

## Indexes

Equality and array filters use the document table's JSON index on every project. For sorting and ranges, Sovaria **indexes the first order-by or range field automatically** once a collection has 1,000 documents. Queries that combine several fields run fastest on a **composite index**: the answer's `index_hint` names it, and **Collections › Indexes** (or the API) creates it in the background without blocking writes.

JavaScript:
```js
await sov.data.createDocIndex('orders', ['status', { path: 'total', order: 'desc' }])
const { indexes, limit } = await sov.data.docIndexes('orders')   // state: building | ready | failed
```

Python:
```python
await sov.create_document_index("orders", ["status", {"path": "total", "order": "desc"}])
print(await sov.list_document_indexes("orders"))
```

HTTP:
```bash
curl -s -X POST $URL/api/v1/data/doc/_indexes -d '{"collection":"orders","fields":["status",{"path":"total","order":"desc"}]}' …
# Every "comments" collection (a collection group):
curl -s -X POST $URL/api/v1/data/doc/_indexes -d '{"collection":"comments","scope":"collection_group","fields":[{"path":"at","order":"desc"}]}' …
curl -s $URL/api/v1/data/doc/_indexes …
curl -s -X DELETE $URL/api/v1/data/doc/_indexes/sovidx_… …
```

Creating and dropping indexes is for project team members and the service key. A query slower than your plan's statement timeout returns `504 DEADLINE_EXCEEDED` with the index that would help.

## In the console

- **Collections › Query**: build filters and sorting, run, load more, and export the results as JSON, JSON Lines or CSV.
- **Collections › Indexes**: every automatic and composite index with its state and size, and your plan's cap.
- **Collections › Data**: large collections load 100 documents at a time; import JSON, JSON Lines or CSV (dotted headers become nested fields).

## Plan limits

| Limit | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Documents per query (`nosql.max_scan_rows`) | 1,000 | 5,000 | 10,000 | 25,000 | 50,000 |
| Document indexes per project (`docs.max_indexes`) | 10 | 100 | 300 | 1,000 | 5,000 |
| Query timeout (`sql.statement_timeout_ms`) | 3 s | 8 s | 15 s | 30 s | 60 s |
