# Queries and views

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

A view is a table that stays up to date with a topic. You say which fields to extract, and the managed backend writes a row for every new message. Use views when agents or services need to look up, filter, or count what happened without reading the whole log. Views need [Laser Stack](/laser-sdk/laser-stack) or LaserData Cloud.

## Quick example

Materialize the topic with a typed projection, publish a reading, and wait for a captured source target before querying it. The wait has a deadline and ends early when a record holds a partition (`blocked`), the table cannot be created without a change (`failed`), or the projection or its binding is gone (`not_found`).

**TypeScript**

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

await using laser = await Laser.connectEnv()
const scoped = laser.withDefaultStream("telemetry")
const readings = scoped.topic("readings")
await readings.ensure(1)
const projection = new ProjectionBuilder("readings_v1")
  .fields(["host", "cpu", "status"])
  .build()
const view = await readings.materialize().index("readings_v1").typed(projection).apply()
await readings.publish().json({ host: "node-2", cpu: 91, status: "degraded" }).send()
const readiness = await view.wait("caught_up", 20_000)
if (readiness.kind !== "ready") throw new Error(`Materialization is ${readiness.kind}`)
const result = await scoped.query("readings_v1").whereEq("status", "degraded").fetch()
for (const row of result.rows) console.log(queryResultValueText(result, row, "host"))
```

**Rust**

```rust
use laser_sdk::prelude::full::*;
use laser_sdk::materialize::{MaterializationReadiness, MaterializationWait};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_env().await?.with_default_stream("telemetry");
    let readings = laser.topic("readings");
    readings.ensure(1, None).await?;
    let projection = Projection::builder("readings_v1")
        .fields(["host", "cpu", "status"])
        .build();
    let view = readings.materialize().index("readings_v1").typed(projection).apply().await?;
    readings.publish().json(&serde_json::json!({
        "host": "node-2", "cpu": 91, "status": "degraded"
    }))?.send().await?;
    let readiness = view.wait(MaterializationReadiness::CaughtUp, Duration::from_secs(20)).await?;
    if !matches!(readiness, MaterializationWait::Ready { .. }) {
        eprintln!("Materialization did not become ready: {readiness:?}");
        return Ok(());
    }
    let result = laser.query("readings_v1").where_eq("status", "degraded").fetch().await?;
    for row in &result.rows {
        println!("{:?}", result.value_text(row, "host"));
    }
    Ok(())
}
```

**Python**

```python
import asyncio
import laser_sdk as ls

async def main() -> None:
    async with await ls.Laser.connect_env() as laser:
        scoped = laser.with_default_stream("telemetry")
        readings = scoped.topic("readings")
        await readings.ensure(1)
        projection = ls.ProjectionBuilder("readings_v1").fields(["host", "cpu", "status"]).build()
        view = await readings.materialize().index("readings_v1").typed(projection).apply()
        await readings.publish({"host": "node-2", "cpu": 91, "status": "degraded"}).send()
        readiness = await view.wait("caught_up", 20_000)
        if readiness["kind"] != "ready":
            raise RuntimeError(f"Materialization is {readiness['kind']}")
        result = await scoped.query("readings_v1").where_eq("status", "degraded").fetch()
        for row in result.rows:
            print(result.value_text(row, "host"))

asyncio.run(main())
```

**Go**

```go
package main

import (
    "context"
    "fmt"
    "os"
    "time"

    "github.com/laserdata/laser-sdk/foreign/go/laser"
    "github.com/laserdata/laser-sdk/foreign/go/wire"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    if err := run(ctx); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run(ctx context.Context) error {
    root, err := laser.ConnectEnv(ctx)
    if err != nil {
        return err
    }
    defer root.Close()
    client := root.WithDefaultStream("telemetry")
    readings := client.Topic("readings")
    if err := readings.Ensure(ctx, 1, nil); err != nil {
        return err
    }
    projection := wire.Projection{ID: "readings_v1", Name: "readings_v1", Version: 1, ContentType: wire.ContentJSON,
        Extraction: wire.IndexSchema{Fields: []wire.IndexField{
            wire.TypedIndexField("host", "/host", wire.FieldText),
            wire.TypedIndexField("cpu", "/cpu", wire.FieldInt),
            wire.TypedIndexField("status", "/status", wire.FieldText),
        }}}
    view, err := readings.Materialize().Index("readings_v1").Typed(projection).Apply(ctx)
    if err != nil {
        return err
    }
    if _, err := readings.Publish().JSON(map[string]any{"host": "node-2", "cpu": 91, "status": "degraded"}).Send(ctx); err != nil {
        return err
    }
    readiness, err := view.Wait(ctx, wire.ReadinessCaughtUp, 20*time.Second)
    if err != nil {
        return err
    }
    if !readiness.Ready() {
        return fmt.Errorf("materialization is %s", readiness.Kind)
    }
    result, err := client.Query("readings_v1").Where("status", wire.StringTyped("degraded")).Fetch(ctx)
    if err != nil {
        return err
    }
    for _, row := range result.Rows {
        for i, field := range result.Fields {
            if field.Name == "host" {
                fmt.Println(row.Values[i].DiagnosticText())
            }
        }
    }
    return nil
}
```

Without `typed`, materialization stores whole records, including arbitrary binary bodies. Use [keyed history](/laser-sdk/advanced/views#keyed-current-state) when the view must keep the latest value per key. A keyed view removes a key only when it names a delete header and a record carries it. The index name `readings_v1` is separate from the topic name.

## Filter and sort

`where_eq` matches an indexed field exactly. The `filter_*` family compares any indexed field, and chained filters combine with AND. Plain values work in every SDK: TypeScript and Python send a whole number as a long and a fraction as a double, and Rust follows the value's Rust type.

**TypeScript**

```ts
const hot = await laser
  .query("readings_v1")
  .filterGte("cpu", 80)
  .orderDesc("cpu")
  .limit(20)
  .fetch()
console.log(`${hot.rows.length} hot hosts, more pages: ${hot.page.hasMore}`)
```

**Rust**

```rust
let hot = laser
    .query("readings_v1")
    .filter_gte("cpu", 80_i64)
    .order_desc("cpu")
    .limit(20)
    .fetch()
    .await?;
println!("{} hot hosts, more pages: {}", hot.rows.len(), hot.page.has_more);
```

**Python**

```python
hot = await laser.query("readings_v1").filter_gte("cpu", 80).order_desc("cpu").limit(20).fetch()
print(f"{len(hot.rows)} hot hosts, more pages: {hot.page.has_more}")
```

**Go**

```go
hot, err := client.Query("readings_v1").Filter("cpu", wire.CmpGte, wire.IntTyped(80)).
    OrderDesc("cpu").Limit(20).Fetch(ctx)
if err != nil {
    return err
}
fmt.Printf("%d hot hosts, more pages: %v\n", len(hot.Rows), hot.Page.HasMore)
```

## Page through rows

A page holds 50 rows by default and at most 1,000. To read more, chain `max_rows(n)` (TypeScript: `maxRows(n)`) and walk the rows with `rows()`, which fetches pages as you go and stops at the ceiling. `rows()` without a ceiling fails with an invalid error. [Walk many rows](/laser-sdk/advanced/views#walk-many-rows) has the code in all three languages.

## Count and group

Call `count()`, `sum(field)`, or `avg(field)` and add `group_by([...])` to get one row per group instead of a list of rows. `window(field, every)` buckets counts by time, `every` a `Duration` in Rust and milliseconds in TypeScript and Python. [Queries and views in depth](/laser-sdk/advanced/views#aggregate) has the full list.

## Know when new data landed

Bind with `notify()` and read the [change feed](/laser-sdk/change-feed) to query only when the view moved. When one query must see your own earlier writes, chain `read_your_writes()` (TypeScript: `readYourWrites()`) on a deployment that supports it.

## Good to know

* Registration and binding apply asynchronously. Register the projection before the binding, and wait for a query to succeed before you publish records you expect to see.
* Rows appear shortly after a publish, not at once. Queries are eventually consistent by default.
* Only declared fields are queryable. The projection builder also keeps a copy of each payload with its row, which typed reads such as `fetch_typed` need. `index_only()` turns that off.
* A client with a default stream scopes index and projection names to that stream. Use the same client setup to bind and to query.
* Row retention is set on the binding and is independent of topic retention. By default rows go when the log drops their messages.
* On standalone Apache Iggy, queries return an unsupported error.

- [Queries and views in depth](/laser-sdk/advanced/views): Every projection, binding, and query option
- [Changes](/laser-sdk/change-feed): Get told when a view advances
- [Filters](/laser-sdk/consumer-filters): Read only the records a filter selects
- [Laser Stack](/laser-sdk/laser-stack): Run views and queries locally
- [Runnable example](https://github.com/laserdata/laser-sdk/tree/main/examples): The query example in Rust, Python, and TypeScript

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