# Querying

> Filter, sort, paginate, resolve relations and localize bucket data with expression and JSON filters.

Queries are sent as query parameters of `GET /bucket/:bucketId/data`. The same filters work in [realtime streams](https://docs.spicaengine.com/buckets/realtime) and in the [devkit](https://docs.spicaengine.com/devkit/bucket).

> **Note**
>
> Remember to URL-encode filter values. With `curl`, use `-G --data-urlencode 'filter=...'` as in the examples below.

## Expression filters

An expression filter is a boolean expression over the document. It works on both MongoDB and PostgreSQL, and uses the same language as [rules](https://docs.spicaengine.com/buckets/rules).

```bash
curl -G https://api.example.com/api/bucket/<bucketId>/data \
  -H "Authorization: APIKEY <key>" \
  --data-urlencode 'filter=document.status == "published" && document.views > 10'
```

Refer to properties through `document`, for example `document.title`, `document.author.name` or `document.tags`. Simple comparisons also accept the bare property name (`views > 10`), but functions and relations require the `document.` prefix, so it is a good habit to always use it.

### Operators

| Operator                | Example                                                 |
| ----------------------- | ------------------------------------------------------- |
| `==`, `!=`              | `document.status == "draft"`                            |
| `<`, `<=`, `>`, `>=`    | `document.views >= 100`                                 |
| `&&`, `\|\|`            | `document.status == "published" && document.views > 10` |
| `in`                    | `document.status in ["draft", "review"]`                |
| `+`, `-`, `*`, `/`, `%` | `document.price * document.quantity > 1000`             |

### Functions

| Function                                  | True when                                                                      |
| ----------------------------------------- | ------------------------------------------------------------------------------ |
| `has(document.cover)`                     | The property exists.                                                           |
| `some(document.tags, ["news", "intro"])`  | The array contains at least one of the values.                                 |
| `every(document.tags, ["news", "intro"])` | The array contains all of the values.                                          |
| `equal(document.tags, ["intro", "news"])` | The array has exactly these values.                                            |
| `regex(document.slug, "^hello", "i")`     | The string matches the pattern. The third argument holds regex flags.          |
| `startsWith(document.slug, "hel")`        | The string starts with the text.                                               |
| `contains(document.slug, "spica")`        | The string contains the text.                                                  |
| `length(document.tags) == 2`              | Returns the length of an array or string, for comparisons.                     |
| `unixTime(document.published_at) < now()` | `unixTime` converts a date to seconds, `now()` is the current time in seconds. |

```text
some(document.tags, ["news"]) && unixTime(document.published_at) > now() - 7 * 24 * 60 * 60
```

### Filtering through relations

Expressions can follow relations. Spica joins the related bucket for you:

```text
document.author.name == "Ada Lovelace"
```

### Hashed and encrypted properties

Compare a `hash` or `encrypted` property with the plain value. Spica hashes it before matching:

```text
document.national_id == "12345678901"
```

## JSON filters

On **MongoDB** you can also send a JSON filter with MongoDB query operators:

```bash
curl -G https://api.example.com/api/bucket/<bucketId>/data \
  -H "Authorization: APIKEY <key>" \
  --data-urlencode 'filter={"status": "published", "views": {"$gte": 10}, "tags": {"$in": ["news"]}}'
```

- Dates can be written as ISO strings: `{"published_at": {"$gte": "2026-11-01T00:00:00Z"}}`.
- `_id` and relation values can be written as strings.
- Dot paths go through relations: `{"author.name": "Ada Lovelace"}`.
- Translated properties are matched in the requested language.
- `$near` isn't allowed because results are counted. Use `$geoWithin` for geographic filters.

> **Warning**
>
> PostgreSQL doesn't accept JSON filters and responds with `A json filter is not supported on PostgreSQL. Use a expression filter.` Use expressions if you want your code to work on both engines.

## Sorting

`sort` is a JSON object. Use `1` for ascending and `-1` for descending order:

```text
sort={"published_at": -1, "title": 1}
```

## Pagination

Use `limit` and `skip`, and set `paginate=true` to get the total count with the page:

```bash
curl "https://api.example.com/api/bucket/<bucketId>/data?paginate=true&limit=20&skip=40" \
  -H "Authorization: APIKEY <key>"
```

```json
{"meta": {"total": 87}, "data": [{"_id": "...", "title": "..."}]}
```

> **Tip**
>
> Counting has a cost on large buckets. Only send `paginate=true` when you display the total, and always set a `limit`.

## Relations

Relations are returned as ids by default. Ask Spica to resolve them with `relation`:

| Value                     | Result                                                         |
| ------------------------- | -------------------------------------------------------------- |
| `relation=true`           | Resolve every relation of the bucket.                          |
| `relation=author`         | Resolve one relation. Repeat the parameter to resolve several. |
| `relation=author.company` | Resolve a nested relation through a resolved one.              |

```bash
curl "https://api.example.com/api/bucket/<postsBucketId>/data?relation=author&limit=1" \
  -H "Authorization: APIKEY <key>"
```

```json
[
  {
    "_id": "6b0b1972a5611972c29c25fd",
    "title": "Hello Spica",
    "author": {
      "_id": "6b0b1972a5611972c29c25fb",
      "name": "Ada Lovelace",
      "email": "ada@example.com"
    }
  }
]
```

Resolving relations makes queries slower, so only resolve what the client renders.

## Localization

For properties with `options.translate`, the response contains one language:

1. The language in the `Accept-Language` header, when the bucket preferences list it.
2. Otherwise the default language from the bucket preferences.

```bash
curl "https://api.example.com/api/bucket/<bucketId>/data?limit=1" \
  -H "Authorization: APIKEY <key>" \
  -H "Accept-Language: tr_TR" -i
```

```http
HTTP/1.1 200 OK
Content-Language: tr_TR

[{"_id": "6b0b1972a5611972c29c25fd", "title": "Merhaba Spica", "body": "<p>İlk yazı</p>"}]
```

Send `localize=false` to receive every language, for example to build an editor:

```json
[{"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}}]
```

## Query profiling

Identities and API keys can inspect how queries perform with `GET /bucket/:bucketId/data/profile`, which returns the database's profiler entries for the bucket. The panel shows the same data under **Observability**.
