docs: add an ordinary Blob v2 photo tutorial (#5087)

The quickstart links to a Blob example that assumes both tables already
exist. Replace that gap with a from-empty photo tutorial: generate real
PNG files with the standard library, ingest an ordinary Blob v2 table,
filter metadata, save and compare exact image bytes, then create and
verify a filtered destination through Enterprise SQL or an Embedded
materialized copy.

Keep Early access and distinguish Enterprise 1.12.0 row-ID fetches from
deployment-dependent snapshot-bound reads. Cover source stability, range
reads and Function readers for large media, ambiguous write recovery,
and the absence of a SQL constructor for uploading client-side files.

The executable Embedded workflow passed on Python SDK 0.42.0b17 using
disposable local storage. Generated snippets, MDX compilation,
combined-site `mint validate`, and `mint broken-links --check-anchors
--check-redirects` passed. Enterprise connection/SQL examples were
checked against the public API and existing 1.12 documentation but were
not executed against an Enterprise deployment; this does not establish
SQL copy behavior after source cleanup. No saved editions or publication
state change.

Fixes
[OSS-3102](https://linear.app/lancedb/issue/OSS-3102/walk-users-from-image-files-to-a-filtered-blob-v2-table-copy).
This commit is contained in:
Xuanwo
2026-11-18 17:19:02 +08:00
committed by GitHub
parent a98cffda4b
commit 9f58d8aab6
4 changed files with 356 additions and 46 deletions
@@ -0,0 +1,149 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
def test_photo_tutorial(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
# --8<-- [start:photo_files]
import struct
import zlib
from pathlib import Path
def solid_png(rgb):
def chunk(kind, data):
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
return (
struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
)
header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0)
pixels = (b"\x00" + bytes(rgb) * 8) * 8
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", header)
+ chunk(b"IDAT", zlib.compress(pixels))
+ chunk(b"IEND", b"")
)
inputs = Path("photo-inputs")
inputs.mkdir()
for label, rgb in [("red", (255, 0, 0)), ("blue", (0, 0, 255))]:
(inputs / f"{label}.png").write_bytes(solid_png(rgb))
# --8<-- [end:photo_files]
# --8<-- [start:photo_connect_embedded]
import lancedb
db = lancedb.connect("./photo-db")
# --8<-- [end:photo_connect_embedded]
# --8<-- [start:photo_ingest]
import pyarrow as pa
schema = pa.schema(
[
pa.field("id", pa.int64(), nullable=False),
pa.field("label", pa.string(), nullable=False),
lancedb.blob("image", nullable=False),
],
metadata={"lance.blob.managed": "false"},
)
photos = db.create_table("photos", schema=schema)
photos.add(
[
{"id": 1, "label": "red", "image": (inputs / "red.png").read_bytes()},
{"id": 2, "label": "blue", "image": (inputs / "blue.png").read_bytes()},
]
)
assert photos.count_rows() == 2
# --8<-- [end:photo_ingest]
# --8<-- [start:photo_fetch]
hits = (
photos.search()
.where("label = 'red'")
.select(["id", "label"])
.with_row_id(True)
.limit(10)
.to_list()
)
assert [row["id"] for row in hits] == [1]
payloads = photos.fetch_blobs("image", [row["_rowid"] for row in hits]).to_pylist()
assert payloads == [(inputs / "red.png").read_bytes()]
saved = Path("selected-red.png")
saved.write_bytes(payloads[0])
assert saved.read_bytes() == (inputs / "red.png").read_bytes()
# --8<-- [end:photo_fetch]
# --8<-- [start:photo_bytes]
rows = (
photos.search()
.where("label = 'red'")
.select(["id", "image"])
.limit(10)
.to_list(blob_mode="bytes")
)
assert rows == [{"id": 1, "image": (inputs / "red.png").read_bytes()}]
# --8<-- [end:photo_bytes]
# --8<-- [start:photo_ranges]
with photos.fetch_blob_files("image", [hits[0]["_rowid"]])[0] as reader:
assert reader.read_range(0, 8) == b"\x89PNG\r\n\x1a\n"
# --8<-- [end:photo_ranges]
# --8<-- [start:photo_copy_embedded]
selected = (
photos.search()
.where("label = 'red'")
.select(["id", "label", "image"])
.limit(10)
.to_arrow(blob_mode="bytes")
)
db.create_table("photo_subset", data=selected, schema=schema)
# --8<-- [end:photo_copy_embedded]
# --8<-- [start:photo_verify]
photo_subset = db.open_table("photo_subset")
assert photo_subset.count_rows() == 1
copied = (
photo_subset.search()
.select(["id", "label"])
.with_row_id(True)
.limit(10)
.to_list()
)
assert [(row["id"], row["label"]) for row in copied] == [(1, "red")]
copied_bytes = photo_subset.fetch_blobs(
"image", [row["_rowid"] for row in copied]
).to_pylist()
assert copied_bytes == [(inputs / "red.png").read_bytes()]
# --8<-- [end:photo_verify]
def enterprise_connection():
# --8<-- [start:photo_connect_enterprise]
import os
import lancedb
db = lancedb.connect(
os.environ["LANCEDB_URI"],
api_key=os.environ["LANCEDB_API_KEY"],
region=os.environ["LANCEDB_REGION"],
host_override=os.environ["LANCEDB_HOST_OVERRIDE"],
sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"],
)
# --8<-- [end:photo_connect_enterprise]
return db
def copy_with_enterprise_sql(db):
# --8<-- [start:photo_copy_sql]
db.execute_query(
"CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)"
).read_all()
db.execute_query(
"INSERT INTO photo_subset (id, label, image) "
"SELECT id, label, image FROM photos WHERE label = 'red'"
).read_all()
# --8<-- [end:photo_copy_sql]
+181 -45
View File
@@ -141,6 +141,19 @@ import {
PyQueryToPandasKwargs as QueryToPandasKwargs,
} from '/snippets/blob_pylance.mdx';
import {
PyPhotoFiles,
PyPhotoConnectEmbedded,
PyPhotoConnectEnterprise,
PyPhotoIngest,
PyPhotoFetch,
PyPhotoBytes,
PyPhotoRanges,
PyPhotoCopyEmbedded,
PyPhotoCopySql,
PyPhotoVerify,
} from '/snippets/photo_tutorial.mdx';
A table stores data in rows and columns and keeps a history of committed
versions. Queries read table data, writes update it, and indexes accelerate
searches over its columns.{/* Draft until branching reaches early access: restore "Branches let you make changes separately from the
@@ -393,60 +406,183 @@ Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled
are outside the GA support scope.
*/}
Suppose your Enterprise database has a `photos` table with an integer `id` and a
Blob v2 column named `image`. Set `LANCEDB_URI`, `LANCEDB_API_KEY`, and
`LANCEDB_HOST_OVERRIDE` to your database URI, API key, and HTTPS endpoint.
See [Connect to LanceDB Enterprise](/basics/catalog#enterprise).
#### From image files to a filtered table {#photo-tutorial}
An SDK query normally returns a descriptor with the blob's location and size.
Pass `blob_mode="bytes"` to get the actual image in the same query. Each result
contains Python `bytes`, or `None` for a null image.
Start in an empty working directory and an empty database. This Python tutorial
creates `photos` with `id`, `label`, and Blob v2 `image` columns, saves one
matching image, and copies that row into a fresh `photo_subset` table. It uses
ordinary tables, with Realtime Engine disabled. Avoid other writers while
running the examples.
```python
import os
import lancedb
Install a Python SDK that provides `lancedb.blob`. For preview builds, use the
[installation instructions](/quickstart#python-pre-release-builds). The examples
need `lancedb` and `pyarrow`; generating the images uses only Python's standard
library.
db = lancedb.connect(
os.environ["LANCEDB_URI"],
api_key=os.environ["LANCEDB_API_KEY"],
host_override=os.environ["LANCEDB_HOST_OVERRIDE"],
)
rows = (
db.open_table("photos").search()
.where("id < 100")
.select(["id", "image"])
.limit(10)
.to_list(blob_mode="bytes")
)
for row in rows:
image = row["image"]
print(row["id"], len(image) if image is not None else None)
```
##### 1. Create two image files {#photo-files}
Use this mode with a Python SDK and Enterprise deployment that support
snapshot-bound blob reads. The bytes come from the same table version as the
filtered rows. Keep that version available until the read finishes. On
Enterprise 1.12.0, or when you already have row IDs, use `fetch_blobs()`.
Keep the source unchanged between selecting the IDs and fetching their bytes.
Inside a LanceDB Function, a parameter annotated with `lancedb.BlobReader`
lets the function seek and read the input on demand.
[Fetch blobs by row ID](#multimodal-read-blobs) · [Troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes)
Generate tiny red and blue PNG images with known pixel contents. Open these
files in an image viewer. To use your own photos later, replace the file paths
and the expected bytes in the checks.
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoFiles}
</CodeBlock>
</CodeGroup>
##### 2. Choose a connection {#photo-connection}
For LanceDB Embedded, create a local database:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoConnectEmbedded}
</CodeBlock>
</CodeGroup>
For LanceDB Enterprise, use an empty development database where you can create
ordinary tables. Get the API and Flight SQL endpoints from your administrator;
set these environment variables using the
[Enterprise connection instructions](/basics/catalog#enterprise) and
[SQL connection settings](/basics/sql#sql-is-remote). Choose this connection
instead of the Embedded connection to run the SQL copy later:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoConnectEnterprise}
</CodeBlock>
</CodeGroup>
##### 3. Define the schema and insert the images {#photo-ingest}
The explicit schema makes `image` a Blob v2 field. The table metadata opts into
ordinary Blob storage. Table creation fails if `photos` already exists; use a
new database for another run.
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoIngest}
</CodeBlock>
</CodeGroup>
<Warning>
If table creation or ingestion loses its response, check whether `photos`
exists and inspect its IDs and image bytes before repeating the write. An
ambiguous result can mean the write committed. Repeating `add` can duplicate
rows. See [write recovery](/ingestion/insert#performance) and
[large upload recovery](/ingestion/insert#bulk-ingests-into-a-remote-table).
</Warning>
##### 4. Filter metadata, save an image, and check its contents {#photo-read}
First select at most ten matching rows without loading their images. Fetch only
those rows' bytes, save the red image, and compare the complete saved file with
the original. This row-ID path works with Enterprise 1.12.0:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoFetch}
</CodeBlock>
</CodeGroup>
`id` is the application's photo ID; `_rowid` is the table's row identifier used
by `fetch_blobs`. Keep the source unchanged between the metadata query and the
fetch. Row IDs alone do not bind the fetch to the query's snapshot. Stable row
IDs across compaction do not protect against an overwrite or a same-name table
replacement.
With a Python SDK and Enterprise deployment that support **snapshot-bound blob
reads**, request the bytes in the query instead:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoBytes}
</CodeBlock>
</CodeGroup>
The bytes then come from the same table version as the filtered rows. Keep that
version available until the read finishes. Enterprise 1.12.0 users should use
the row-ID example above; support for snapshot-bound reads depends on both the
SDK and the serving deployment. See
[troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes).
LanceDB Embedded also supports this query mode; use a reader checked out to a
fixed version if concurrent writers can overwrite the source.
##### Choose a read method for larger media {#photo-read-method}
| Task | Method |
| --- | --- |
| Save a small, bounded set of complete images | `fetch_blobs`, or query with `blob_mode="bytes"` on a supporting deployment |
| Read a header or part of a large video | `fetch_blob_files`, then `read_range` or `read_ranges` |
| Seek through a video in server-side processing | A LanceDB Function parameter annotated with `lancedb.BlobReader` |
| Copy rows inside Enterprise | SQL `INSERT INTO ... SELECT`, without downloading images to the client |
A row limit bounds the number of images, not their total size. Avoid fetching
whole videos just to inspect their headers. Here is a range read against the
same red PNG; it verifies the eight-byte PNG signature:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoRanges}
</CodeBlock>
</CodeGroup>
For multiple slices, see [range reads](#multimodal-read-blobs). For a seekable
video reader inside a Function, see
[read a blob incrementally](/curation/create-function#incremental).
#### Copy a subset of blob rows {#multimodal-copy-subset}
To copy images within the same Enterprise database, run the filter on the
server. This example appends matching rows to an existing `photo_subset`
table with the same `id` and blob `image` columns.
Continue with the same `photos`, selecting the same red image. Choose one copy
path below, then run the shared verification. Neither path overwrites an
existing `photo_subset`.
```sql
INSERT INTO photo_subset (id, image)
SELECT id, image FROM photos WHERE id < 100;
```
##### Enterprise SQL {#photo-copy-sql}
In Enterprise 1.12.0, selecting a Blob v2 column directly in SQL returns the
payload as `large_binary`. Use `blob_descriptor(image)` when you want storage
metadata. For a copy, select `image` itself.
[SQL blob descriptors](/sql/dql/blob-descriptor)
On the Enterprise connection, create a fresh destination with a Blob column,
then copy matching rows on the server. `execute_query` submits one statement
per call; consume each result before continuing:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoCopySql}
</CodeBlock>
</CodeGroup>
Enterprise 1.12.0 supports this SQL copy. Selecting a Blob v2 column directly
in SQL returns the payload as `large_binary`. Select `image` itself for the
copy; use [`blob_descriptor(image)`](/sql/dql/blob-descriptor) to inspect storage
metadata instead.
`lancedb.blob("image")` is a Python schema helper, not a SQL value constructor.
SQL has no `blob(local_path)` constructor to upload a client-side image file.
Ingest file bytes with the SDK as above, then use SQL to copy stored rows.
If the copy response is lost, inspect `photo_subset` before repeating the
`INSERT`; the same [write recovery rules](/ingestion/insert#performance) apply.
##### LanceDB Embedded {#photo-copy-embedded}
SQL requires Enterprise. With the Embedded connection, materialize this small
selection and give the destination the explicit Blob schema:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoCopyEmbedded}
</CodeBlock>
</CodeGroup>
##### Verify the destination {#photo-copy-verify}
Reopen `photo_subset`, check its row count and application ID, and compare its
image bytes with the original local file. The destination has its own row IDs,
so query them again instead of reusing the source's `_rowid` values:
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyPhotoVerify}
</CodeBlock>
</CodeGroup>
#### Blob storage layouts {#blob-storage-layouts}
+5 -1
View File
@@ -367,7 +367,11 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c
</CodeBlock>
</CodeGroup>
See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan.
For image files and larger payloads, follow the
[Blob photo tutorial](/management/table#photo-tutorial) to create an ordinary
Blob table, filter its metadata, save and check an image, and copy matching rows.
It includes an Embedded path and an Enterprise SQL path. Blob columns are in
Early access.
## 8\. Train on your data {#8-train}
+21
View File
@@ -0,0 +1,21 @@
{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */}
export const PyPhotoBytes = "rows = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"image\"])\n .limit(10)\n .to_list(blob_mode=\"bytes\")\n)\nassert rows == [{\"id\": 1, \"image\": (inputs / \"red.png\").read_bytes()}]\n";
export const PyPhotoConnectEmbedded = "import lancedb\n\ndb = lancedb.connect(\"./photo-db\")\n";
export const PyPhotoConnectEnterprise = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n os.environ[\"LANCEDB_URI\"],\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ[\"LANCEDB_REGION\"],\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n sql_host_override=os.environ[\"LANCEDB_SQL_HOST_OVERRIDE\"],\n)\n";
export const PyPhotoCopyEmbedded = "selected = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\", \"image\"])\n .limit(10)\n .to_arrow(blob_mode=\"bytes\")\n)\ndb.create_table(\"photo_subset\", data=selected, schema=schema)\n";
export const PyPhotoCopySql = "db.execute_query(\n \"CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)\"\n).read_all()\ndb.execute_query(\n \"INSERT INTO photo_subset (id, label, image) \"\n \"SELECT id, label, image FROM photos WHERE label = 'red'\"\n).read_all()\n";
export const PyPhotoFetch = "hits = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [row[\"id\"] for row in hits] == [1]\npayloads = photos.fetch_blobs(\"image\", [row[\"_rowid\"] for row in hits]).to_pylist()\nassert payloads == [(inputs / \"red.png\").read_bytes()]\nsaved = Path(\"selected-red.png\")\nsaved.write_bytes(payloads[0])\nassert saved.read_bytes() == (inputs / \"red.png\").read_bytes()\n";
export const PyPhotoFiles = "import struct\nimport zlib\nfrom pathlib import Path\n\ndef solid_png(rgb):\n def chunk(kind, data):\n checksum = zlib.crc32(kind + data) & 0xFFFFFFFF\n return (\n struct.pack(\">I\", len(data)) + kind + data + struct.pack(\">I\", checksum)\n )\n\n header = struct.pack(\">IIBBBBB\", 8, 8, 8, 2, 0, 0, 0)\n pixels = (b\"\\x00\" + bytes(rgb) * 8) * 8\n return (\n b\"\\x89PNG\\r\\n\\x1a\\n\"\n + chunk(b\"IHDR\", header)\n + chunk(b\"IDAT\", zlib.compress(pixels))\n + chunk(b\"IEND\", b\"\")\n )\n\ninputs = Path(\"photo-inputs\")\ninputs.mkdir()\nfor label, rgb in [(\"red\", (255, 0, 0)), (\"blue\", (0, 0, 255))]:\n (inputs / f\"{label}.png\").write_bytes(solid_png(rgb))\n";
export const PyPhotoIngest = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64(), nullable=False),\n pa.field(\"label\", pa.string(), nullable=False),\n lancedb.blob(\"image\", nullable=False),\n ],\n metadata={\"lance.blob.managed\": \"false\"},\n)\nphotos = db.create_table(\"photos\", schema=schema)\nphotos.add(\n [\n {\"id\": 1, \"label\": \"red\", \"image\": (inputs / \"red.png\").read_bytes()},\n {\"id\": 2, \"label\": \"blue\", \"image\": (inputs / \"blue.png\").read_bytes()},\n ]\n)\nassert photos.count_rows() == 2\n";
export const PyPhotoRanges = "with photos.fetch_blob_files(\"image\", [hits[0][\"_rowid\"]])[0] as reader:\n assert reader.read_range(0, 8) == b\"\\x89PNG\\r\\n\\x1a\\n\"\n";
export const PyPhotoVerify = "photo_subset = db.open_table(\"photo_subset\")\nassert photo_subset.count_rows() == 1\ncopied = (\n photo_subset.search()\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [(row[\"id\"], row[\"label\"]) for row in copied] == [(1, \"red\")]\ncopied_bytes = photo_subset.fetch_blobs(\n \"image\", [row[\"_rowid\"] for row in copied]\n).to_pylist()\nassert copied_bytes == [(inputs / \"red.png\").read_bytes()]\n";