# Queries and views in depth

Code on this page comes in TypeScript, Rust, and Python. The same page with one language only: [Python](https://docs.laserdata.com/md/python/laser-sdk/advanced/views.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/advanced/views.md), [Rust](https://docs.laserdata.com/md/rust/laser-sdk/advanced/views.md).

This is the full reference for [Queries and views](/laser-sdk/views). Start there for the short version.

A view is a queryable table that the managed backend keeps up to date from messages in the log. A projection says which fields to extract. A binding says which topic feeds the projection and which index the rows land in. Queries read the index. Views need Laser Stack or LaserData Cloud. On standalone Apache Iggy the query capability is off and every call on this page returns an unsupported error.

## How a view is built

1. Register a projection. It names the fields to extract from each payload.
2. Apply a binding. It connects a `(stream, topic)` source to the projection and names the operational index.
3. Publish to the topic as usual. The managed backend extracts the fields from each new record and writes a row to the index.
4. Query the index.

Registration and binding submit control commands through the authenticated managed endpoint. The managed backend applies them asynchronously, so the calls return before the index exists. Register the projection before you apply a binding that names it, or the binding is rejected. A query fails until the index exists, then returns an empty page.

A client with a default stream scopes projection IDs, index names, and the index a query names to that stream, as `stream:<stream>/<name>`. Listings return your stream's projections without the prefix. Schema registration and lookup use the stream's own registry. See [Stream-scoped resource names](/laser-sdk/connect#stream-scoped-resource-names).

In Rust, views need the `projections` and `query` features. The `managed` feature includes both.

## Materialize a topic

`topic.materialize().apply()` registers a whole-record projection and binds the topic to its index. The index defaults to the topic name. Set `index` to choose another name. Set `typed` to use an extraction projection instead. Use `operation_id` in Rust and Python, or `operationId` in TypeScript, to repeat setup with the same identity after an uncertain response. A topic feeds one index. Applying a setup with another index to a topic that is already materialized moves the topic there: the earlier index stops receiving rows and keeps the ones it has, and the new index fills from the retained log.

The returned materialization handle exposes status and a bounded wait for readiness. Status includes source incarnation, source and applied offsets, rejected records, accepted gaps, and the first observed offsets. Caught up means that the index reached a captured source target. It does not prove complete historical coverage. Unknown first offsets, missing source identity, gaps, skipped records, omitted bodies, and records that expired before the binding read them prevent a complete-history result.

Status answers nothing when the projection does not exist or its topic is no longer bound to the index. Each binding status names `failure`, the class of the last failed table creation (`configuration`, `schema`, `poison` and `fatal` need a change to the binding or its backend, `transient`, `capacity` and `read_only` recover on their own), and `stall`, why nothing moves when no record holds the binding (`source_missing`, `source_unreadable`, `destination_unreadable`, `backpressure`). A binding applied for an earlier incarnation of its stream holds every partition with `retired_incarnation` until it is applied again. A binding whose index you may not read is left out, and a status read is refused as unauthorized when you may read none of the projection's indexes, so a wait ends with that error instead of running out its timeout.

The wait returns `ready`, `blocked` when a record or a history gap holds a partition, `failed` when table creation failed in a way that needs a change, `not_found` when the projection or its binding is gone, or `timed_out` with the last status. If the topic is recreated during a caught-up wait, the wait measures the new topic. The wait reads quickly at first and backs off to one read per second. A held record is released by applying the binding again with the dead-letter invalid-record policy. A history gap is released by an operator.

`topic.materialization(projection_id)` returns the same handle in a process that did not run the setup, read under the topic's stream. Without an explicit projection ID or typed projection, the projection ID is the index name, which defaults to the topic name.

**TypeScript**

```ts
const view = laser.stream("telemetry").topic("readings").materialization("readings_v1")
const readiness = await view.wait("realized", 10_000)
if (readiness.kind === "failed") console.error(readiness.status[0]?.failure)
```

**Rust**

```rust
let view = laser.stream("telemetry").topic("readings").materialization("readings_v1")?;
match view.wait(MaterializationReadiness::Realized, Duration::from_secs(10)).await? {
    MaterializationWait::Failed { status } => eprintln!("{:?}", status[0].failure),
    readiness => println!("{readiness:?}"),
}
```

**Python**

```python
view = laser.stream("telemetry").topic("readings").materialization("readings_v1")
readiness = await view.wait("realized", 10_000)
if readiness["kind"] == "failed":
    print(readiness["status"][0]["failure"])
```

### Keyed current state

A projection with keyed history keeps the latest value for each key. Configure `keyed` on its builder with a header key or a payload JSON pointer. Whole-record projections require a header key. The delete header is optional. When the projection names one, a record that carries that header removes the key's current row, whatever the header's value. Without one, the view never deletes a key: a record carrying a header named `deleted` or `delete` replaces the row like any other update. The backend retains the key position so that replaying an older record cannot restore a deleted value. For a typed keyed projection, a record that yields no extracted field and does not delete its key is an invalid record: it follows the binding's invalid-record policy and never removes its key.

**TypeScript**

```ts
import { ProjectionBuilder } from "@laserdata/laser-sdk"

const key = { kind: "header", name: "order_id" } as const
const latest = new ProjectionBuilder("orders_latest").record().keyed(key).build()
const current = new ProjectionBuilder("orders_current").record().keyed(key, "deleted").build()
await laser.topic("orders").materialize().index("orders_latest").typed(latest).apply()
```

**Rust**

```rust
use laser_sdk::prelude::full::*;
use laser_sdk::query::ProjectionKey;

let key = ProjectionKey::Header { name: "order_id".to_owned() };
let latest = Projection::builder("orders_latest").record().keyed(key.clone(), None).build();
let current = Projection::builder("orders_current").record().keyed(key, Some("deleted")).build();
laser.topic("orders").materialize().index("orders_latest").typed(latest).apply().await?;
```

**Python**

```python
import laser_sdk as ls

key = {"kind": "header", "name": "order_id"}
latest = ls.ProjectionBuilder("orders_latest").record().keyed(key).build()
current = ls.ProjectionBuilder("orders_current").record().keyed(key, delete_header="deleted").build()
await laser.topic("orders").materialize().index("orders_latest").typed(latest).apply()
```

`orders_latest` keeps the newest record of each order and never removes one. `orders_current` removes an order when a record carries the `deleted` header.

A key must stay in one source partition within a topic incarnation. A later incarnation can use that key again. Keyed bindings contain one default projection and use Keep, KeepUntilSourceDeleted, or time-to-live retention. The materialize helper selects Keep when keyed history has no explicit retention. Keyed status never claims complete append history. Changing an existing projection or index between append and keyed history, or the delete header of a keyed projection, is refused as a conflict.

## Register a projection

All three SDKs build a projection with the same builder: `Projection::builder(id)` in Rust, `new ProjectionBuilder(id)` in TypeScript, and `ls.ProjectionBuilder(id)` in Python. TypeScript uses camelCase method names. `build()` returns the projection, which is a dict in Python. Pass it to `projections().register(projection)`.

* `field(name)` indexes a top-level JSON field under the same name.
* `fields([...])` indexes several top-level fields.
* `field_at(name, pointer)` indexes the value at an RFC 6901 JSON pointer under `name`. `field_at("cpu_pct", "/cpu/value")` indexes `cpu.value` as `cpu_pct`.
* `field_typed(name, type)` and `field_at_typed(name, pointer, type)` give the field a type. Rust uses `FieldType::Int`, `Float`, `Bool`, or `Text`. Python and TypeScript use `"int"`, `"float"`, `"bool"`, or `"text"`. Query results return the field as a long, double, boolean, or string, a stored value that does not fit as null, and a typed-column backend stores it in a typed column. A field without a type is a `variant` in query results: each value keeps the type it was stored with.
* `vector_field(pointer)` extracts an embedding vector for nearest-neighbor search. Without it, the vector is read from `/embedding`.
* `content_type(..)` selects the decoder, such as JSON or Avro. The builder default is `Any`, a best-effort decode.
* `inline_payload()` keeps a copy of the original payload with each row, so typed reads decode the row without reading the log. This is the builder default. `index_only()` keeps only the declared fields.
* `version(n)` sets the schema version. The default is 1. The recommended ID form is `name.vN`, for example `readings_v1.v1`.
* `name(..)` sets the display name. It is separate from the ID, so you can rename a projection without changing the ID that producers send.
* `extraction(schema)` replaces the whole extraction plan. `IndexSchemaBuilder` builds one with `field`, `field_at`, `vector_field`, and `inline_payload`.

A hand-written object or dict with the same fields also works. It states the payload choice with `inline_payload` (`inlinePayload`) on the extraction and `inline_payload_default` (`inlinePayloadDefault`) on the projection. A dict that omits them stores no payload, unlike the builder.

A producer can also ask for one record's payload to be kept with its row with `inline_payload()` on the publish request (TypeScript: `inlinePayload()`).

Limits:

* A projection ID is 1 to 255 bytes and a display name at most 255 bytes, both without control characters. The name is optional.
* Do not start a projection ID with `index:`. The platform reserves that prefix. Without a default stream, an ID that starts with it fails with `projection id must not start with "index:"`.
* A field name, a JSON pointer, and the vector field pointer are 1 to 255 bytes each, without control characters.
* A record can carry at most 32 `.index(..)` values. The SDK refuses more when you send.
* The managed backend decodes payloads up to 8 MiB. A larger record keeps only the values its `.index(..)` headers set. The projection's fields are not extracted from it, and the row does not copy the payload. A row copies a payload only up to the body limit of the backend that stores it, and above that limit the row keeps its fields without the copy.
* A record with no indexed fields produces no row.

The log keeps the original bytes according to the topic's retention. Rows have their own retention, set on the binding, so a row can outlive the message that produced it. Only declared fields are queryable. Other fields stay in the inline payload, when it is kept, or in the log.

`projections().register(..)` rejects a graph projection with an invalid error. Register those with `register_graph` as shown in [Graph](/laser-sdk/advanced/graph).

### Read and change the registry

* `projections().get(id)` returns one projection with its bindings, or nothing when the ID is unknown.
* `projections().list()` browses the registry one page at a time, in ID order. Rust and TypeScript narrow it with `for_topic`, `for_topics`, `name_contains`, `id_prefix`, and `search` (camelCase in TypeScript), pick the page with `page(n)` and `results(n)`, and finish with `fetch()`. Python passes `topic=`, `topics=`, `name_contains=`, `id_prefix=`, `search=`, `page=`, and `results=` to `list(..)`. A page holds 10 projections by default and at most 100. The reply carries `items`, `page`, `total_pages`, and `total_results` (`totalPages` and `totalResults` in TypeScript), counting only the projections you may read. No filter lists every projection.
* `projections().drop(id)` stops materialization for that projection. Rows already written stay.

Writes are applied asynchronously. Poll `get(id)` to see when a registration has been applied.

## Bind a topic

A binding selects one `(stream, topic)` source and the projections allowed to read it. The builder is `ProjectionBinding::builder()` in Rust, `new ProjectionBindingBuilder()` in TypeScript, and `ls.ProjectionBindingBuilder()` in Python. Pass the result to `bindings().apply(binding)`.

* `source(stream, topic)` selects the topic. A binding has exactly one source. `selector(source)` takes a prebuilt source instead.
* `allow(projection_id)` adds a permitted projection. Call it once per projection.
* `default_projection(id)` handles records that name no projection. Without a default, those records are skipped.
* `index(name)` names the operational index. Without it, the index takes the source topic name.
* `backend(binding)` pins the index to an exact backend resource ID and generation. Without it, the index uses the replica-local backend.
* `retention(policy)` sets how long rows live, independent of topic retention. Without it, the binding uses the deployment default, which mirrors the log unless an operator changed it.
* `notify()` turns on [change records](/laser-sdk/advanced/change-feed) for this binding. Notifications are off by default.
* `invalid_records(policy)` (TypeScript: `invalidRecords(policy)`) selects `block` or `dead_letter`. The default blocks the partition on a rejected record.
* `oversize(policy)` selects `block` or `reference`. A reference keeps the source location without copying an oversized body.

A producer tags a record for one projection with `projection_ref(id)` on the publish request (TypeScript: `projectionRef`). It sets the `agdx.ref` header. A record tagged for a projection outside the allowed set is skipped or dead-lettered, according to the deployment's policy. The header keeps your local projection ID, and the managed backend resolves it against the bindings of the record's own stream, so a record never selects another stream's projection.

The build step differs by language when no source is set:

| Call | Rust | TypeScript | Python |
| --- | --- | --- | --- |
| `build()` | Panics | Throws `InvalidError` | Raises `InvalidError` |
| `try_build()` / `tryBuild()` | Returns `Err(InvalidError)` | Returns `undefined` | Raises `InvalidError` |

A hand-written binding uses the fields `source`, `allowed_projections`, `default_projection`, `backend`, `index`, `notify`, `retention`, `invalid_records`, and `oversize` (camelCase in TypeScript).

### Rejected records

Some records can never reach their index. The record may carry more indexed fields than a record may have, or the destination may refuse its values, for example because they break a constraint. Such a record stops its partition. Nothing after it is written, so the index never silently loses a record. The managed backend reports the record to the operator with its offset, the index or graph it failed to reach, and the reason.

The managed backend blames a record only when it has proof. For a destination refusal, the destination must accept other records of the same batch, refuse this one twice, and still pass its readiness check. When every record fails, the destination is the problem, and the partition waits for it instead.

A skip releases the record. Every skip is an ordered record on the control log, so every replica skips the same record and folds the rest the same way. The skip covers that one record, its one index or graph, and the current incarnation of the topic. The record's other effects, such as graph writes and session links, still apply. The skipped record goes to the dead-letter topic with the reason.

With `invalid_records` set to `dead_letter`, the managed backend appends the skip automatically. With `block`, the partition waits for an operator skip or a policy change. An authorized operator can skip under either policy. A record with an `agdx.sid` writer schema that fails validation is a rejected record.

The folds that build memory, the session index, key-value, fork, and graph data can hold on one record the same way. When the store refuses the write of one record, for example for a constraint, the fold stops at that record and the [`fold_stalled` alert](/observability#monitoring-alerts) names its offset. An operator skip of that record on its source partition releases the fold, and every replica skips it the same way. The memory fold drops the record. The session index keeps it in its session as an `invalid` event with reason `skipped_record` and folds nothing else of it. A key-value, fork, or graph write is not applied, and its outcome becomes an error with the `Backend` result code that names the skip. The record goes to the dead-letter topic with the reason. A store that is down, busy, full, or refuses its credentials never names a record, so no skip is offered while the store is only unavailable, and the fold resumes once the store answers.

### Retention policies

| Policy | Rust | Python | TypeScript |
| --- | --- | --- | --- |
| Mirror the log, the default | `RetentionPolicy::MirrorLog` | `{"kind": "mirror_log"}` | `{ kind: "mirrorLog" }` |
| Keep forever | `RetentionPolicy::Keep` | `{"kind": "keep"}` | `{ kind: "keep" }` |
| Keep until the source topic is deleted | `RetentionPolicy::KeepUntilSourceDeleted` | `{"kind": "keep_until_source_deleted"}` | `{ kind: "keepUntilSourceDeleted" }` |
| Time to live after materialization | `RetentionPolicy::TimeToLive { ttl_micros }` | `{"kind": "time_to_live", "ttl_micros": n}` | `{ kind: "timeToLive", ttlMicros: n }` |
| Newest rows only | `RetentionPolicy::MaxRows { rows }` | `{"kind": "max_rows", "rows": n}` | `{ kind: "maxRows", rows: n }` |

In TypeScript, `n` is a `bigint`. Mirror the log removes rows when Iggy removes the messages that produced them. Mirror the log and keep until the source topic is deleted both drop the rows when the source topic is deleted. Keep, time to live, and newest rows only keep their rows after the topic is gone. A policy kind that a newer server sends and your SDK does not know decodes as `Unknown`. Do not apply a binding you read back with an unknown policy, because its original kind is lost.

The index and the topic have separate names. The `readings` topic can feed the `readings_v1` index, so you can version the view without renaming the topic that producers use.

`bindings().remove(source, projection_ref)` stops materialization for that source. Rows already written stay. Pass a projection ID to stop routing into that one projection only. Rust takes `Option<String>` for the second argument. TypeScript and Python make it optional.

### Register and bind, in code

**TypeScript**

```ts
import { ContentType, ProjectionBindingBuilder, ProjectionBuilder } from "@laserdata/laser-sdk"

const projection = new ProjectionBuilder("readings_v1.v1")
  .name("readings_v1")
  .version(1)
  .contentType(ContentType.Json)
  .indexOnly()
  .fields(["host", "cpu", "status"])
  .build()
await laser.projections().register(projection)

const binding = new ProjectionBindingBuilder()
  .source("telemetry", "readings")
  .allow("readings_v1.v1")
  .defaultProjection("readings_v1.v1")
  .index("readings_v1")
  .retention({ kind: "timeToLive", ttlMicros: 7n * 24n * 3_600_000_000n })
  .notify()
  .build()
await laser.bindings().apply(binding)
```

**Rust**

```rust
use laser_sdk::prelude::full::*;

let projection = Projection::builder("readings_v1.v1")
    .name("readings_v1")
    .version(1)
    .content_type(ContentType::Json)
    .index_only()
    .fields(["host", "cpu", "status"])
    .build();
laser.projections().register(projection).await?;

let binding = ProjectionBinding::builder()
    .source("telemetry", "readings")
    .allow("readings_v1.v1")
    .default_projection("readings_v1.v1")
    .index("readings_v1")
    .retention(RetentionPolicy::TimeToLive {
        ttl_micros: 7 * 24 * 3_600_000_000,
    })
    .notify()
    .build();
laser.bindings().apply(binding).await?;
```

**Python**

```python
import laser_sdk as ls

projection = (
    ls.ProjectionBuilder("readings_v1.v1")
    .name("readings_v1")
    .version(1)
    .content_type("json")
    .index_only()
    .fields(["host", "cpu", "status"])
    .build()
)
await laser.projections().register(projection)

binding = (
    ls.ProjectionBindingBuilder()
    .source("telemetry", "readings")
    .allow("readings_v1.v1")
    .default_projection("readings_v1.v1")
    .index("readings_v1")
    .retention({"kind": "time_to_live", "ttl_micros": 7 * 24 * 3_600_000_000})
    .notify()
    .build()
)
await laser.bindings().apply(binding)
```

After the binding is applied, every new message on `telemetry/readings` updates the view.

## Two ways to index a field

With a registered projection, the producer sends a normal payload and the managed backend extracts the fields through the projection's pointers. The producer needs no projection details.

The producer can also set an indexed value directly. `.index(key, value)` on a publish request adds an `agdx.idx.<key>` header with a string value. Use it for raw payloads, for writer schemas the managed backend cannot decode, or for a constant on every record in a batch. A header wins over an extracted value with the same field name. A record can carry at most 32 of these headers.

## Writer schemas

`laser.schemas()` is the writer schema registry for Avro, Protobuf, and JSON Schema payloads. Registration is synchronous: the managed backend checks that the definition compiles, allocates the lowest ID free in the registry, and returns it. Each stream has its own registry and a client without a default stream uses the deployment-wide one, so IDs start at 1 in every registry and two streams can hold the same ID. IDs are permanent, and concurrent callers never get the same one. A registry holds at most 1,024 schemas, dropped ones included, and a registration past that is refused with a resource limit error while every other stream keeps its own budget. A definition that does not compile, a JSON Schema of another draft than 2020-12, and a definition over 1 MiB or nested deeper than 64 levels return an invalid error and allocate nothing. The SDKs refuse the draft and size rules before sending.

* Rust and TypeScript call `register(source)`, optionally chain `.name(..)` and `.version(..)`, and finish with `.send()`. Python passes `name=` and `version=` to `register(..)`. Name and version are stored labels only. A name is 1 to 255 bytes with no control characters.
* `get(id)` returns the schema at that ID, active or dropped, or nothing when the ID is free.
* `list()` browses the registry one page at a time, in ID order, active and dropped schemas alike. Rust and TypeScript narrow it with `name_contains` (`nameContains` in TypeScript), pick the page with `page(n)` and `results(n)`, and finish with `fetch()`. Python passes `name_contains=`, `page=`, and `results=` to `list(..)`. A page holds 10 schemas by default and at most 100, and the reply carries `items`, `page`, `total_pages`, and `total_results` (`totalPages` and `totalResults` in TypeScript).
* `drop(id)` marks the schema dropped. Records stamped with that ID keep decoding, and the ID can never be reused for a different definition. Dropping an unknown ID does nothing.

Producers stamp the ID with `.schema_id(id)` on the publish request (TypeScript: `schemaId`). The stamp is enforced: the managed backend decodes or validates the body under that schema, refuses an Avro or Protobuf schema whose family differs from the record's `agdx.ct`, and applies the binding's invalid-record policy to a record that breaks it. An Avro or Protobuf body is a bare datum or message, with no single-object or registry framing. A record's ID resolves in the registry of the stream it was published to, then in the deployment-wide registry, so another stream's schema never decodes it.

`CompiledSchema` decodes a body client-side into the same value the managed backend indexes and consumer filters read: schema field names, numeric Protobuf enums, exact 64-bit integers, bytes as arrays of byte values, proto3 defaults present, and Avro logical types as their physical values, so a decimal reads as its unscaled bytes and a timestamp as its long. In TypeScript the 64-bit integer types decode to `bigint` and narrower integers to `number`.

## Wait for the view

Materialization is asynchronous. A message you just published can be missing from the next query.

* Wait for a query to succeed after you apply a binding. The examples do this before they publish, so new records reach a running projector.
* Use the [change feed](/laser-sdk/advanced/change-feed) to learn when an index advanced, then query.
* Use a read-your-writes query when one query must see your own earlier writes. See [Consistency](#consistency).

## Query an index

`laser.query(index)` opens a query against an operational index. Chain conditions, then run it with a terminal such as `fetch()`. TypeScript uses camelCase names, such as `whereEq`, `filterGte`, and `countDistinct`.

### Match and filter

* `where_eq(field, value)` matches an indexed field exactly. It is the cheap path that index keys answer directly.
* `filter_eq`, `filter_ne`, `filter_gt`, `filter_gte`, `filter_lt`, `filter_lte`, `filter_in`, `filter_contains`, and `filter_prefix` compare any indexed field. Chained filters combine with AND.
* `filter(expr)` adds a composed condition. Build it with `Filter::pred`, `Filter::all`, `Filter::any`, and `Filter::negate` in Rust, `ls.Filter.pred`, `all`, `any`, and `negate` in Python, and `filterPred`, `filterAll`, `filterAny`, and `filterNegate` in TypeScript.
* `message_type(value)` matches the reserved `message_type` field.
* `time_range(start, end)` matches the reserved `ts` field, in epoch microseconds. The range includes both ends, and `start` must be before `end`.

Value types follow each language. Rust takes anything that converts into a `TypedValue`, such as `&str`, `i32`, `i64`, or `f64`. Python takes plain Python values. TypeScript `whereEq`, the `filter*` comparisons and raw SQL parameters take a native `string`, `number`, `bigint`, `boolean`, `null` or `Uint8Array`, or a tagged `TypedValue` such as `{ kind: "int", value: 80 }`. A safe integer or a bigint is a long and another finite number a double, as in Python, and a non-finite number or a bigint outside the signed 64-bit range fails with an invalid error. `filterContains` and `filterPrefix` take a string.

### Sort and page

* `order_asc(field)` and `order_desc(field)` sort. Several calls sort by several fields in order.
* `limit(n)` sets the page size. The default is 50 and the maximum is 1,000. Zero or a value above 1,000 fails with an invalid error before anything is sent.
* `offset(n)` skips the first `n` matching rows, up to 1,000,000. A larger offset fails with an invalid error before anything is sent.
* `with_total()` asks for an exact total count. It costs a full scan on a wide filter. Without it, the total is absent and `has_more` is still exact.

Each result has a `page` with `offset`, `limit`, `total`, and `has_more` (`hasMore` in TypeScript). `has_more` says whether rows follow the page, and the next page repeats the query with the offset moved past the rows already read. Aggregate and vector queries always return one page.

### Aggregate

* `count`, `sum`, `avg`, `min`, `max`, and `count_distinct` work on every backend. `stddev` and `percentile(field, fraction)` need a columnar backend.
* Each aggregate writes to a result field named after itself, such as `count` or `avg`. TypeScript aggregate methods take an optional alias as their last argument.
* `agg_as` adds an aggregate with a chosen alias, so you can return several of the same kind. Rust: `agg_as(func, field, fraction, alias)`. Python: `agg_as(func, alias, field=, fraction=)`. TypeScript: `aggAs(func, alias, { field, fraction })`.
* `group_by([...])` groups the aggregate. `window(field, every)` buckets it into tumbling windows `every` wide (a `Duration` in Rust, milliseconds in TypeScript and Python) over a timestamp field, and each result row carries the bucket start in `window_start`.
* `having(expr)` filters aggregate output. Its fields name an aggregate alias or a group key, not raw row fields. It needs an aggregate.
* An aggregate query cannot also select fields or ask for payloads.

**TypeScript**

```ts
import { queryResultValueI64, queryResultValueText } from "@laserdata/laser-sdk"

const byStatus = await laser.query("readings_v1").count().groupBy(["status"]).fetch()
for (const row of byStatus.rows) {
  const status = queryResultValueText(byStatus, row, "status")
  const count = queryResultValueI64(byStatus, row, "count")
  console.log(`${status ?? "?"}: ${String(count ?? 0n)}`)
}
```

**Rust**

```rust
let by_status = laser
    .query("readings_v1")
    .count()
    .group_by(["status"])
    .fetch()
    .await?;
for row in &by_status.rows {
    let status = by_status.value_text(row, "status").unwrap_or_default();
    let count = by_status.value_i64(row, "count").unwrap_or(0);
    println!("{status}: {count}");
}
```

**Python**

```python
by_status = await laser.query("readings_v1").count().group_by(["status"]).fetch()
for row in by_status.rows:
    status = by_status.value_text(row, "status")
    count = by_status.value_i64(row, "count") or 0
    print(f"{status}: {count}")
```

### Search

* `nearest(embedding, top_k)` runs a nearest-neighbor search on the `embedding` field. Rust and TypeScript use `nearest_in(field, embedding, top_k)` (`nearestIn`) for another field. Python passes `field=` to `nearest`. The `top_k` nearest rows are the whole answer, so a vector search takes no sort, no offset and no total.
* `text(query)` runs a lexical search over every text-hinted indexed field. `text_in(field, query)` narrows it to one field. Relevance lands in each row's `score`. Rows come in relevance order and page by offset like any other query, so a lexical search takes no sort and no total. Lexical search needs the `keyword` capability, and the SDK refuses it before sending when the deployment does not advertise it.
* A query runs one shape: a search, an aggregate or a distinct read. The SDK refuses a query that combines two of them.

### Select fields and payloads

* `select_fields([...])` returns only some fields.
* `distinct()` returns distinct rows over the selected fields. It needs `select_fields`.
* `with_payload()` returns the stored payload bytes on each row.

### Raw SQL

`raw_sql` runs one read-only SQL statement on the index's backend. It works on SQL backends only, is not portable, and cannot be combined with any structured condition, sort, aggregate, selection, or payload request.

| Language | Call | Dialect |
| --- | --- | --- |
| Rust | `raw_sql(dialect, sql)`, or `raw_sql_with(dialect, sql, params)` with positional parameters | Required, a `SqlDialect` |
| TypeScript | `rawSql(dialect, sql, params?)` | Required |
| Python | `raw_sql(dialect, sql, params=None)` | Required |

Operational backends serve SQLite for Turso, Postgres for Postgres, and MySQL for Doris and VeloDB. Read the backend capabilities before choosing a dialect. A dialect that the backend does not serve returns an unsupported error.

Every table in the statement must name an index that the caller can read in the same stream and backend. This includes tables in joins, subqueries, and common table expressions. A common table expression may reuse the name of an index the caller cannot read, and then reads only what its own body reads. Writes, session variables, system tables, schema-qualified names, comments, casts to catalog object types such as `regclass`, and unapproved functions are refused. The plane provisions restricted query identities for Postgres and Doris, and Postgres resolves functions in the system catalog only, so a function defined in the data schema cannot replace a built-in one. Turso runs queries in read-only mode with an engine deadline.

The query identity is checked again on every backend readiness probe and after a credential change. When it holds more than read access to materialized indexes, or the server refuses it, raw SQL is refused with an unsupported error, the backend capabilities stop listing raw SQL, and the backend readiness reports `query_identity_rejected` with the reason. Materialization and structured queries keep working, and raw SQL returns once the identity passes the check again. An optional `query_dsn` override is checked the same way, and the plane never falls back to its own privileged connection.

Every statement stops at the query deadline. Postgres and Turso cancel it in the engine. Doris also kills the statement on the server, because its own timeout counts whole seconds.

The statement reads the queried index by the same name the query uses. A stream-scoped name such as `stream:orders/orders.v1` holds `:` and `/`, so quote it: `FROM "stream:orders/orders.v1"`, or with backticks on MySQL.

### Consistency

Queries are eventually consistent by default. `read_your_writes()` waits until the projector reaches the end of the source log as it was when the query started. If the projector does not catch up in time, the query fails with a stale error instead of returning older data. `consistency(level)` takes eventual or read-your-writes.

Read-your-writes needs backend support. The SDK checks `capabilities.query.consistency` and returns an unsupported error before sending when the level is not served. Check for a stale error with `error.is_stale()` in Rust, `isStale(error)` in TypeScript, and the `stale` attribute in Python.

Every result names how far the store that served it had applied the log: `context.frontier` lists each source partition of the index with the last applied offset and, when the serving node knows it, the creation time of the topic incarnation the rows come from. Two results from different nodes can sit at different points of the same log, so compare their frontiers rather than the time you sent the queries. Offsets of different topic incarnations do not compare.

### Scope a query

* `conversation(id)` returns only the rows one conversation produced. The deployment indexes every message's conversation header, so this works on any projection without producer changes. Rust takes a `ConversationId`. TypeScript and Python take a string.
* `fork(id)` reads a fork's copy-on-write view instead of the trunk. See [Key-value state](/laser-sdk/advanced/state).

### Deadlines

Each call, and each page of a walk, gets its own deadline, 25 seconds after it starts by default. The server never extends it. A deadline can be at most 25 seconds away, and a later one fails before the query is sent. The server replies `DeadlineExceeded` when the deadline passes. The client waits 2 seconds more for that reply and then fails with a timeout, which does not prove the query stopped. Set a relative deadline with `deadline(duration)` in Rust and `deadline(deadline_ms)` in milliseconds in Python and TypeScript. `deadline_at_micros(..)` (TypeScript: `deadlineAtMicros`) sets an absolute time in epoch microseconds in all three SDKs.

## Read results

A result has `fields`, `rows`, `page`, and `context`. Each row's values follow the order of `fields`. The fields come from the query and the projection, never from the rows a page happens to hold, so every page of one query has the same fields and types. Without `select_fields`, a result has every field the projection declares, in name order, then the row's stream, topic, partition, offset, and source incarnation. With `select_fields`, it has exactly the selected fields in the order given, then the same position fields, and a query without text or vector search reads only those fields from the backend. An aggregate has its group keys, `window_start` when windowed, and its aliases: counts are longs, averages, deviations and percentiles doubles, and sums, minimums and maximums follow the field's type. Raw SQL columns are `variant`. Read values by field name with the accessors:

| Language | Accessors |
| --- | --- |
| Rust and Python | `result.value(row, name)`, `value_text`, `value_u64`, `value_i64`, and `field_index(name)` |
| TypeScript | `queryResultValue(result, row, name)`, `queryResultValueText`, `queryResultValueU64`, `queryResultValueI64`, and `queryResultFieldIndex(result, name)` |

Use typed accessors for logic and the text accessor for display. `value_u64` and `value_i64` return nothing when the value is missing, out of range, or not an integer. TypeScript `typedValueDiagnosticText(value)` and Python `ls.typed_value_diagnostic_text(value)` render any typed value as text. See [Managed data](/laser-sdk/advanced/managed-data#typed-query-results) for the type rules.

### Typed reads

Typed reads decode the stored payload of each row, so they need a view that keeps payloads. A row without a payload fails.

* `fetch_typed` returns one page of decoded values. Rust decodes JSON into your type with `fetch_typed::<T>()` and takes another decoder with `fetch_typed_with::<C, T>()`. Python decodes JSON into Python values, and `fetch_typed_with(codec)` takes any object with `decode(data)`. TypeScript takes a codec, as in `fetchTyped(new Json<Reading>())`.
* `fetch_one` returns at most one decoded value. Rust and Python also have `fetch_one_with`. TypeScript `fetchOne(codec)` takes the codec directly.
* `fetch_all()` reads every matching row into memory and returns a row set with the rows and `frontier_moved` (TypeScript: `fetchAll()`, `frontierMoved`). `fetch_all_typed()` (TypeScript: `fetchAllTyped(codec)`) decodes them. Use these only when the result fits in memory.

## Walk many rows

`rows()` walks matching rows across pages. It needs an explicit ceiling, `max_rows(n)` (TypeScript: `maxRows(n)`), and fails with an invalid error without one. It stops at the ceiling or the last page, whichever comes first. Rust returns a walker that you advance with `next().await`. TypeScript returns an async iterable. Python returns an asynchronous iterator. `rows_typed()` does the same with decoded payloads (TypeScript: `rowsTyped(codec)`).

Each walked row is a `QueryRow` bound to its fields, read by name with `value`, `value_text`, `value_u64`, `value_i64`, and `field_index` (TypeScript: `valueText`, `valueU64`, `valueI64`, `fieldIndex`). Python rows also read as `row["status"]` or `row[0]`, like `sqlite3.Row`.

Pages of a walk are separate reads of a live view. Each page carries the store's frontier from before it was read, and the walk compares it with the first page's. When they differ, rows written between pages can repeat or be missing, and `frontier_moved` (TypeScript: `frontierMoved`) on the walk or the row set turns true. The walk still finishes.

**TypeScript**

```ts
const hosts = new Set<string>()
const walk = laser.query("readings_v1").whereEq("status", "degraded").maxRows(5_000).rows()
for await (const row of walk) hosts.add(row.valueText("host") ?? "?")
if (walk.frontierMoved) console.log("the view changed while it was walked")
```

**Rust**

```rust
let mut rows = laser
    .query("readings_v1")
    .where_eq("status", "degraded")
    .max_rows(5_000)
    .rows()?;
let mut hosts = std::collections::BTreeSet::new();
while let Some(row) = rows.next().await? {
    hosts.insert(row.value_text("host").unwrap_or_default());
}
if rows.frontier_moved() {
    println!("the view changed while it was walked");
}
```

**Python**

```python
rows = laser.query("readings_v1").where_eq("status", "degraded").max_rows(5_000).rows()
hosts = set()
async for row in rows:
    hosts.add(row.value_text("host"))
if rows.frontier_moved:
    print("the view changed while it was walked")
```

A zero ceiling returns no rows and sends no request in all three SDKs. TypeScript rejects a negative or unsafe integer ceiling. The walk fetches pages of `limit` rows, 50 by default.

## Execution identity

Every query carries an execution ID. Rust reads it with `execution_id()`, TypeScript with `executionId()`, and Python from the `execution_id` property.

The lower-level call on the client is `execute_query(query)` (TypeScript: `executeQuery`). It checks that the reply carries the execution ID you asked for, and a reply for another execution fails with a protocol error. When the server advertises a different query protocol version, the SDK fails with a typed version error before sending.

### Build a query value

To build a whole query instead of chaining on `laser.query(..)`, use `Query::builder()` in Rust, `new QueryBuilder()` in TypeScript, or `ls.QueryBuilder()` in Python, then pass the result to `execute_query` (TypeScript: `executeQuery`). The execution ID, target, and absolute deadline in epoch microseconds are required, and `build()` fails with an invalid error when one is missing. The builder has one setter per query field. In all three SDKs, `into_query()` (TypeScript: `intoQuery()`) turns a chained request into the same value, and `query_target(target)` (TypeScript: `queryTarget`) starts a chained request from an explicit target.

## Operational views

A binding keeps an operational index on the deployment's backend, and `laser.query(index)` reads it. What a backend can serve depends on what it advertises. See [Managed data](/laser-sdk/advanced/managed-data).

Columnar data enters the log as Arrow IPC. Publish one complete stream per message with `arrow_ipc(bytes, metadata)` on a publish request (TypeScript: `arrowIpc`). The SDK checks the metadata and that the payload length matches it before sending. The managed backend enforces the rest of the acceptance policy.

## Errors

| Situation | What you get |
| --- | --- |
| The deployment does not serve queries | Unsupported error, before sending |
| An unadvertised consistency level or lexical search | Unsupported error naming the feature, before sending |
| `limit` of zero or above 1,000, an offset above 1,000,000, an empty time range, or `having` without an aggregate | Invalid error, before sending |
| `rows()` or `rows_typed()` without `max_rows` | Invalid error |
| Read-your-writes that cannot catch up in time | Stale query error |
| A typed read of a row without a payload | Config error |
| The index does not exist yet | An error until the managed backend creates it |
| Raw SQL that reads an index no binding names | Index not found, as a structured query |
| `register` with a graph projection | Invalid error |

## Key operations

| Verb | What it does |
| --- | --- |
| `Projection::builder(id)` | Start a projection (TypeScript and Python: `ProjectionBuilder(id)`) |
| `.field` / `.fields` / `.field_at` | Index top-level fields or a JSON pointer |
| `.field_typed` / `.field_at_typed` | Index a field with the type its query results carry |
| `.vector_field(pointer)` | Extract an embedding vector |
| `.inline_payload()` / `.index_only()` | Keep the payload with each row, or only the indexed fields |
| `.keyed(key, delete_header)` | Keep the current row of each key, removed by a record carrying the optional delete header |
| `projections().register` / `get` / `list` / `drop` | Manage the projection registry |
| `ProjectionBinding::builder()` | Start a binding (TypeScript and Python: `ProjectionBindingBuilder()`) |
| `.source` / `.allow` / `.default_projection` | Which topic, which projections, and the projection for untagged records |
| `.index` / `.backend` / `.retention` / `.notify` | Index name, backend, row lifetime, and change records |
| `bindings().apply` / `remove` | Apply or remove a binding |
| `schemas().register` / `get` / `list` / `drop` | Manage writer schemas |
| `publish().index(key, value)` | Set an indexed value at publish time |
| `publish().projection_ref(id)` | Tag a record for one allowed projection |
| `query(index)` / `query_target` | Open a query |
| `where_eq` and the `filter_*` family | Match and filter |
| `order_asc` / `order_desc` / `limit` / `offset` | Sort and page |
| `count`, `sum`, `avg`, `group_by`, `window`, `having` | Aggregate |
| `nearest` / `text` | Vector and lexical search |
| `read_your_writes` / `consistency` | Choose read consistency |
| `fetch` / `fetch_typed` / `fetch_one` / `fetch_all` | Run the query |
| `max_rows(n).rows()` / `rows_typed()` | Walk rows across pages under a ceiling, each row read by field name |
| `execute_query` | Lower-level query call |
| `raw_sql` | One read-only SQL statement on a SQL backend |

- [Queries and views](/laser-sdk/views): The short guide
- [Changes in depth](/laser-sdk/advanced/change-feed): Know when a view advanced
- [Managed data](/laser-sdk/advanced/managed-data): Readiness and typed results
- [Laser Stack](/laser-sdk/laser-stack): Run views and queries locally

Source: https://docs.laserdata.com/laser-sdk/advanced/views
