Files
lancedb/docs/web/sql/ddl/materialized-view.mdx
T
Jack Ye 2b1b2a29dd feat!: layer GPU settings and total execution limits (#5146)
BREAKING CHANGE: Resource inputs use the same names at Function
registration, column/MV creation, and refresh. Use total_cpu_millis,
total_memory_bytes, and total_gpu_count for execution-wide worker
budgets, plus gpu_class and positive gpu_count for each worker. Replace
budget dictionary inputs and unprefixed aggregate limits with these
fields. Move existing refresh gpu_count caps to total_gpu_count;
gpu_count now selects devices per worker.

Each setting resolves independently: refresh > column/MV creation >
Function annotation > deployment. Creation settings also apply to
initial MV population and automatic refresh. MVs sum total budgets
across distinct pinned Function versions; per-worker GPU counts use the
largest Function default unless overridden. An unset GPU class resolves
to gpu_class="any" after inheritance; an explicit "any" overrides a
registered concrete class. Use gpu_class="default" to pin the default
pool explicitly.

```python
@function(
    gpu=True, gpu_class="h100", gpu_count=2,
    total_cpu_millis=8000,
    total_memory_bytes=16 * 1024**3,
    total_gpu_count=4,
)
def embed(text: str) -> list[float]: ...

version = db.create_function(embed)
table.add_columns(
    {"embedding": version(text=col("text"))},
    gpu_class="any", gpu_count=1, total_gpu_count=8,
)
table.refresh_column_async(
    "embedding", gpu_class="h100", gpu_count=4, total_gpu_count=8,
)

mv = db.create_materialized_view(
    "embeddings", query="SELECT embed(text) AS embedding FROM documents",
    gpu_class="any", gpu_count=2, total_gpu_count=8,
)
mv.refresh(gpu_count=4, total_gpu_count=8)
```

```mermaid
flowchart TD
    R["Refresh settings"] --> E["Effective settings, resolved per field"]
    D["Column or MV creation settings"] --> E
    F["Function settings"] --> E
    C["Deployment defaults"] --> E
    E --> W["GPU class and device count per worker"]
    E --> T["Total CPU, memory and GPU ceilings"]
```

Pinned Function images retain their identity. Registration GPU counts
are defaults; execution overrides determine worker allocation. Admission
rejects GPU counts below an image's minimum requirement or above the
total budget. Python, Rust, SQL/REST and supported TypeScript operations
use the same resource model.

No local builds or tests, as requested; regression coverage runs in CI.
2026-11-21 15:04:34 -08:00

178 lines
6.6 KiB
Plaintext

---
title: "Materialized View"
sidebarTitle: "Materialized View"
description: "CREATE MATERIALIZED VIEW and SHOW MATERIALIZED VIEWS; refreshing is a REFRESH statement."
icon: table
keywords: ["materialized view", "create materialized view", "show materialized views", "sql"]
availability:
embedded: unavailable
enterprise: available
---
A materialized view stores a query's result as rows, kept current by a refresh.
It is the counterpart to a [view](/sql/ddl/view), which stores only the query.
<Note>
Materialized views are off by default in LanceDB Enterprise and have to be enabled
there. Which statements and query shapes a deployment accepts, whether it needs
the source table to have stable row ids, and how it refreshes a view depend on
its LanceDB Enterprise version and configuration.
</Note>
## CREATE MATERIALIZED VIEW {#create}
<CodeGroup>
```sql SQL icon="database"
CREATE MATERIALIZED VIEW <name> AS SELECT ...
```
</CodeGroup>
{/* Draft for the materialized-view exist_ok release.
`IF NOT EXISTS` preserves an existing materialized view's definition, data and
refresh settings without refreshing it. The Python equivalent is
`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped
asynchronous creation returns a completed job without submitting a refresh job.
Existing names are errors by default.
*/}
Once created, a materialized view can be queried like a table. Use the
statements below to list, refresh and drop it. For SDK methods, see
[Materialized views](/management/materialized-view#create).
{/*
Draft for automatic materialized-view refresh. Enable this section, and
"ALTER MATERIALIZED VIEW" below, when the server feature is released.
Set scheduling options at creation, continuing the join and chained
Functions from [Create a Function](/curation/create-function#chain):
```sql
CREATE MATERIALIZED VIEW frames_captioned
WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5)
AS
SELECT
f.frame_id,
extract_frame(v.video, f.ts) AS jpeg,
caption(extract_frame(v.video, f.ts)) AS caption
FROM videos v
JOIN frames f ON v.id = f.video_id
WHERE f.selected = true
```
`auto_refresh_enabled` and `auto_refresh_interval_seconds` work the same way
here as for a [computed column](/sql/ddl/table#automatic-refresh-options):
the interval is a minimum pacing after the last successful refresh, and
automatic execution needs the same server-side switch enabled. Omitting
`WITH` leaves automatic refresh at the server's default.
*/}
## SHOW MATERIALIZED VIEWS {#show}
```sql
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100;
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
```
Returns two non-null string columns: `namespace_path`, a compact JSON array
of parent namespace components (`[]` for root), and `name`, the unqualified
object name. Omitting `IN` lists all authorized namespaces in the current database;
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
the current database's root. Listings require the relevant database and
namespace `USAGE` privileges.
The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata.
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
unchanged with the same object type and scope. Stop when no token is returned;
a short or empty page can still carry a continuation. See
[catalog listing pagination](/sql/pagination).
## Refreshing one {#refresh}
<CodeGroup>
```sql SQL icon="database"
REFRESH MATERIALIZED VIEW chunks
```
</CodeGroup>
See [REFRESH MATERIALIZED VIEW](/sql/dml/refresh-materialized-view) for the full syntax,
and compatibility notes for older server versions.
{/*
Draft for automatic materialized-view refresh. Enable this section when the
server feature is released; see the note on "CREATE MATERIALIZED VIEW" above.
## ALTER MATERIALIZED VIEW {#alter}
```sql
ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = true;
ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_interval_seconds = 300;
ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = false;
```
The whole view toggles together; there is no per-output granularity the way
a multi-output Function column has one setting per output. SET takes effect
immediately and does not itself run a refresh:
- **Disabling** prevents new automatic refreshes. An inflight one may still
finish, and `REFRESH MATERIALIZED VIEW` keeps working manually.
- **Re-enabling catches up the entire backlog in one pass**, the same as a
computed column's [automatic refresh](/sql/ddl/table#automatic-refresh-options):
the next scheduler tick picks up every source change accumulated since the
view was disabled, immediately, with no further write needed to trigger it.
A materialized view's *initial* population, at `CREATE` or when the server
runs it, happens regardless of `auto_refresh_enabled`; only refreshes after
that are gated by the setting.
*/}
## Dropping one {#drop}
```sql
DROP MATERIALIZED VIEW <name>
```
A dedicated statement; the SDKs emit it rather than
[`DROP TABLE`](/sql/ddl/table#drop), even though a materialized view **is**
a table underneath. For the same reason, dropping one removes stored rows,
unlike dropping a [view](/sql/ddl/view#drop).
<Note>
**Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the
same underlying job as dropping any table, `drop_table` or `drop_object`.
</Note>
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Materialized View" icon="table" href="/management/materialized-view">
Creating one from the SDK.
</Card>
<Card title="Refresh a materialized view" icon="arrows-rotate" href="/feature-engineering/refresh-materialized-view">
How a refresh works, in LanceDB Enterprise.
</Card>
</CardGroup>
### Resource settings
Creation accepts `total_cpu_millis`, `total_memory_bytes`, and `total_gpu_count`
as execution-wide defaults, plus `gpu_class` and positive `gpu_count` for each
worker. Refresh accepts the same names and overrides each supplied field.
Unspecified fields inherit creation settings, then Function settings, then
deployment defaults. A materialized view sums total budgets across distinct
pinned Function versions; per-worker counts use the largest Function default
unless overridden.
```sql
CREATE MATERIALIZED VIEW embeddings
WITH (gpu_class = 'any', gpu_count = 2, total_gpu_count = 8)
AS SELECT embed(text) AS embedding FROM documents;
REFRESH MATERIALIZED VIEW embeddings
WITH (gpu_class = 'h100', gpu_count = 4, total_gpu_count = 8);
```