Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings

# Conflicts:
#	python/python/tests/test_table.py
This commit is contained in:
Will Jones
2026-11-10 02:14:38 +00:00
474 changed files with 44681 additions and 10005 deletions
+6 -1
View File
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "0.41.0-beta.17"
current_version = "0.42.0-beta.9"
parse = """(?x)
(?P<major>0|[1-9]\\d*)\\.
(?P<minor>0|[1-9]\\d*)\\.
@@ -70,6 +70,11 @@ filename = "rust/lancedb/Cargo.toml"
replace = "\nversion = \"{new_version}\""
search = "\nversion = \"{current_version}\""
[[tool.bumpversion.files]]
filename = "rust/lancedb/cli/Cargo.toml"
replace = "\nversion = \"{new_version}\""
search = "\nversion = \"{current_version}\""
[[tool.bumpversion.files]]
filename = "nodejs/Cargo.toml"
replace = "\nversion = \"{new_version}\""
+2 -1
View File
@@ -52,7 +52,8 @@ runs:
Linux/X64) platform="linux-x86_64"; sha256="$LINUX_X86_64_SHA256" ;;
Linux/ARM64) platform="linux-aarch_64"; sha256="$LINUX_AARCH_64_SHA256" ;;
macOS/*) platform="osx-universal_binary"; sha256="$OSX_SHA256" ;;
Windows/X64) platform="win64"; sha256="$WIN64_SHA256" ;;
# Windows 11 Arm runners can execute the upstream x64 protoc binary.
Windows/X64|Windows/ARM64) platform="win64"; sha256="$WIN64_SHA256" ;;
*) echo "Unsupported runner: $RUNNER_OS_NAME/$RUNNER_ARCH_NAME" >&2; exit 1 ;;
esac
zip="$RUNNER_TEMP/protoc.zip"
+3 -2
View File
@@ -4,10 +4,11 @@
come from the `LanceDB.zip` asset of `lancedb/docs` release
`vale-lancedb-v0.1.0`, whose archive SHA-256 is
`0730a43e919774121068811d5687c61dfc7a0421cff78e1393f5e565b622cb0f`.
`ProductNames` no longer swaps in "LanceDB OSS".
`ProductNames` no longer swaps in "LanceDB OSS" and now recommends
"LanceDB Enterprise" for the retired "LanceDB Distributed" name.
The product-terminology rules were added here: `EmbeddedName`,
`RemoteExecution`, `OSSProduct`, `DistributedEnterprise`, `InternalNames`
`RemoteExecution`, `OSSProduct`, `InternalNames`
(warnings) and `LegacyCloud` (suggestion). They enforce the names in the
docs repository's `STYLE.md#names`. Run every rule's tests from
`.github/vale` with `vale test --coverage styles`.
@@ -1,19 +0,0 @@
extends: existence
message: "'%s' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both."
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
level: warning
ignorecase: false
tokens:
- 'Distributed(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Enterprise'
- 'Enterprise(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Distributed'
tests:
- name: flags Distributed and Enterprise side by side
input: Choose Distributed or Enterprise. LanceDB Enterprise and LanceDB Distributed differ, and so does Distributed/Enterprise.
want: |
1:8:LanceDB.DistributedEnterprise:'Distributed or Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both.
1:43:LanceDB.DistributedEnterprise:'Enterprise and LanceDB Distributed' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both.
1:98:LanceDB.DistributedEnterprise:'Distributed/Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both.
- name: leaves the defining sentence and the Embedded pair alone
input: |
LanceDB Enterprise runs LanceDB Distributed. Compare Embedded and Distributed execution. Distributed search and enterprise teams are fine.
want: ''
+3 -3
View File
@@ -1,5 +1,5 @@
extends: existence
message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'."
message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'."
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
level: suggestion
ignorecase: false
@@ -13,8 +13,8 @@ tests:
- name: suggests checking each LanceDB Cloud mention
input: Connect to LanceDB Cloud with an API key. Cloud/Enterprise users get the cache.
want: |
1:12:LanceDB.LegacyCloud:'LanceDB Cloud' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'.
1:43:LanceDB.LegacyCloud:'Cloud/Enterprise' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'.
1:12:LanceDB.LegacyCloud:'LanceDB Cloud' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'.
1:43:LanceDB.LegacyCloud:'Cloud/Enterprise' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'.
- name: leaves other clouds and code alone
input: |
Deploy into your own cloud account on Google Cloud. Pass `LanceDB Cloud` as a literal.
+15 -6
View File
@@ -9,7 +9,8 @@ swap:
'(?:Lancedb|LanceDb|lanceDB|LANCEDB|Lance DB)': LanceDB
'LanceDB (?:cloud|CLOUD)': LanceDB Cloud
'LanceDB (?:enterprise|ENTERPRISE)': LanceDB Enterprise
'(?:HuggingFace|Huggingface|Hugging face)': Hugging Face
'LanceDB\s+Distributed': LanceDB Enterprise
'(?:Hugging Face|Hugging face|Huggingface)': HuggingFace
Langchain: LangChain
Typescript: TypeScript
VoyageAI: Voyage AI
@@ -21,13 +22,21 @@ tests:
1:32:LanceDB.ProductNames:Use 'LanceDB Cloud' instead of 'LanceDB cloud'.
1:49:LanceDB.ProductNames:Use 'LanceDB Enterprise' instead of 'LanceDB enterprise'.
- name: corrects names seen misspelled in the current pages
input: Load a HuggingFace model, build a Langchain retriever in Typescript and call VoyageAI.
input: Load a Hugging Face model, build a Langchain retriever in Typescript and call VoyageAI.
want: |
1:8:LanceDB.ProductNames:Use 'Hugging Face' instead of 'HuggingFace'.
1:35:LanceDB.ProductNames:Use 'LangChain' instead of 'Langchain'.
1:58:LanceDB.ProductNames:Use 'TypeScript' instead of 'Typescript'.
1:78:LanceDB.ProductNames:Use 'Voyage AI' instead of 'VoyageAI'.
1:8:LanceDB.ProductNames:Use 'HuggingFace' instead of 'Hugging Face'.
1:37:LanceDB.ProductNames:Use 'LangChain' instead of 'Langchain'.
1:60:LanceDB.ProductNames:Use 'TypeScript' instead of 'Typescript'.
1:80:LanceDB.ProductNames:Use 'Voyage AI' instead of 'VoyageAI'.
- name: leaves package names, identifiers and code alone
input: |
The lancedb package exposes `HuggingFaceEmbeddings` and LanceDBConnection; see `Typescript` in code.
want: ''
- name: uses Enterprise for the product and its execution model
input: Connect to LanceDB Distributed.
want: |
1:12:LanceDB.ProductNames:Use 'LanceDB Enterprise' instead of 'LanceDB Distributed'.
- name: keeps technical descriptions and API identifiers
input: |
LanceDB Enterprise supports distributed search. Compare Embedded and Enterprise. Distributed training uses workers. `LanceDB Distributed` and `RemoteTable` are literal code.
want: ''
@@ -1,5 +1,5 @@
extends: existence
message: "Avoid '%s'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product."
message: "Avoid '%s'. Write 'LanceDB Enterprise' and describe where the operation runs directly."
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
level: warning
ignorecase: false
@@ -11,18 +11,18 @@ tests:
- name: flags remote as the execution model
input: In remote mode, a remote table is opened through a remote connection.
want: |
1:4:LanceDB.RemoteExecution:Avoid 'remote mode'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
1:19:LanceDB.RemoteExecution:Avoid 'remote table'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
1:52:LanceDB.RemoteExecution:Avoid 'remote connection'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
1:4:LanceDB.RemoteExecution:Avoid 'remote mode'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
1:19:LanceDB.RemoteExecution:Avoid 'remote table'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
1:52:LanceDB.RemoteExecution:Avoid 'remote connection'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
- name: flags plurals and a heading
input: |
## Remote tables
Remote databases hold remote tables.
want: |
1:4:LanceDB.RemoteExecution:Avoid 'Remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
3:1:LanceDB.RemoteExecution:Avoid 'Remote databases'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
3:23:LanceDB.RemoteExecution:Avoid 'remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product.
1:4:LanceDB.RemoteExecution:Avoid 'Remote tables'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
3:1:LanceDB.RemoteExecution:Avoid 'Remote databases'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
3:23:LanceDB.RemoteExecution:Avoid 'remote tables'. Write 'LanceDB Enterprise' and describe where the operation runs directly.
- name: leaves other remotes and code alone
input: |
Push to the git remote, read remote storage and fetch a remote URL. `open_table` returns a `RemoteTable`; see `remote table` in the API.
+10
View File
@@ -9,6 +9,11 @@ on:
- python/pyproject.toml
- ci/check_cargo_lock.py
- ci/check_sdist.py
- ci/extract_sdk_doc_links.py
- ci/build_cli_linux.sh
- ci/package_cli.py
- .bumpversion.toml
- rust/lancedb/cli/Cargo.toml
- ci/set_lance_version.py
- ci/tests/**
- .github/workflows/ci-scripts.yml
@@ -18,6 +23,11 @@ on:
- python/pyproject.toml
- ci/check_cargo_lock.py
- ci/check_sdist.py
- ci/extract_sdk_doc_links.py
- ci/build_cli_linux.sh
- ci/package_cli.py
- .bumpversion.toml
- rust/lancedb/cli/Cargo.toml
- ci/set_lance_version.py
- ci/tests/**
- .github/workflows/ci-scripts.yml
+167
View File
@@ -0,0 +1,167 @@
name: CLI release packages
on:
workflow_call:
workflow_dispatch:
pull_request:
paths:
- 'rust/lancedb/**'
- 'Cargo.toml'
- 'Cargo.lock'
- 'rust-toolchain.toml'
- '.cargo/config.toml'
- '.bumpversion.toml'
- 'LICENSE'
- 'RUST_THIRD_PARTY_LICENSES.html'
- 'ci/build_cli_linux.sh'
- 'ci/package_cli.py'
- 'ci/tests/test_package_cli.py'
- '.github/actions/setup-protoc/**'
- '.github/workflows/cli-release.yml'
- '.github/workflows/gh-release.yml'
permissions:
contents: read
concurrency:
group: cli-packages-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
version:
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.version.outputs.version }}
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- name: Validate release version before building
id: version
run: |
version=$(python ci/package_cli.py version)
echo "version=$version" >> "$GITHUB_OUTPUT"
build:
needs: version
timeout-minutes: 180
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: ubuntu-2404-8x-x64
image: quay.io/pypa/manylinux_2_28_x86_64
protoc: linux-x86_64
- target: aarch64-unknown-linux-gnu
runner: ubuntu-2404-8x-arm64
image: quay.io/pypa/manylinux_2_28_aarch64
protoc: linux-aarch_64
- target: aarch64-apple-darwin
runner: warp-macos-14-arm64-6x
runs-on: ${{ matrix.runner }}
env:
CLI_TARGET: ${{ matrix.target }}
CLI_VERSION: ${{ needs.version.outputs.version }}
MACOSX_DEPLOYMENT_TARGET: '14.0'
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
with:
# Leave .cargo/config.toml's CPU/feature flags in effect.
rustflags: ''
cache: false
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
with:
key: cli-release-${{ matrix.target }}
save-if: ${{ github.event_name == 'pull_request' || github.ref == 'refs/heads/main' }}
- uses: ./.github/actions/setup-protoc
id: protoc
with:
install: ${{ runner.os == 'macOS' }}
- name: Add swap for Arm fat LTO
if: matrix.target == 'aarch64-unknown-linux-gnu'
run: |
swap_file="$RUNNER_TEMP/lancedb-cli-swap"
sudo fallocate --length 16G "$swap_file"
sudo chmod 600 "$swap_file"
sudo mkswap "$swap_file"
sudo swapon "$swap_file"
- name: Build Linux CLI against glibc 2.28
if: runner.os == 'Linux'
env:
MANYLINUX_IMAGE: ${{ matrix.image }}
PROTOC_PLATFORM: ${{ matrix.protoc }}
PROTOC_VERSION: ${{ steps.protoc.outputs.version }}
PROTOC_SHA256: ${{ matrix.protoc == 'linux-x86_64' && steps.protoc.outputs.linux-x86_64-sha256 || steps.protoc.outputs.linux-aarch_64-sha256 }}
run: |
docker run --rm \
--volume "$PWD:/workspace" --workdir /workspace \
--volume "$HOME/.cargo:/cargo" --env CARGO_HOME=/cargo \
--volume "$HOME/.rustup:/rustup" --env RUSTUP_HOME=/rustup \
--env CLI_TARGET --env PROTOC_PLATFORM --env PROTOC_VERSION --env PROTOC_SHA256 \
"$MANYLINUX_IMAGE" bash ci/build_cli_linux.sh
- name: Build macOS CLI
if: runner.os == 'macOS'
run: |
cargo build --locked --release -p lancedb-cli --bin lancedb --target "$CLI_TARGET"
strip -S "target/$CLI_TARGET/release/lancedb"
# Stripping can invalidate the linker's ad-hoc signature on Apple Silicon.
codesign --force --sign - "target/$CLI_TARGET/release/lancedb"
- name: Package, inspect runtime dependencies, and smoke-test archive
run: |
python ci/package_cli.py package \
--binary "target/$CLI_TARGET/release/lancedb" --target "$CLI_TARGET" --output dist
- name: Smoke-test Linux archive on a clean glibc 2.28 system
if: runner.os == 'Linux'
run: |
docker run --rm --volume "$PWD/dist:/artifacts:ro" \
--env CLI_TARGET --env CLI_VERSION almalinux:8 bash -euo pipefail -c '
dnf install -y libstdc++
mkdir -p /tmp/check /tmp/cli-home
export HOME=/tmp/cli-home XDG_CONFIG_HOME=/tmp/cli-home/.config
stem="lancedb-v${CLI_VERSION}-${CLI_TARGET}"
tar -xzf "/artifacts/${stem}.tar.gz" -C /tmp/check
cli="/tmp/check/${stem}/lancedb"
"$cli" --help
test "$("$cli" --version)" = "lancedb ${CLI_VERSION}"
"$cli" profile list
'
- uses: actions/upload-artifact@v7
with:
name: cli-archive-${{ matrix.target }}
path: dist/*.tar.gz
if-no-files-found: error
assemble:
needs: [version, build]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- uses: actions/download-artifact@v8
with:
pattern: cli-archive-*
merge-multiple: true
path: dist
- name: Require all three archives and generate checksums
run: |
python ci/package_cli.py checksums --output dist
python ci/package_cli.py verify --output dist
- uses: actions/upload-artifact@v7
with:
name: cli-release
path: dist/*
if-no-files-found: error
+6 -1
View File
@@ -14,7 +14,7 @@ jobs:
test:
strategy:
matrix:
os: [ubuntu-24.04, macos-14]
os: [ubuntu-24.04, macos-15]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
@@ -24,6 +24,11 @@ jobs:
with:
components: clippy
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
with:
# Restoring compiled targets can exhaust the hosted runner disk.
prefix-key: v1-cli-downloads
cache-targets: false
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install Linux prerequisites
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler libssl-dev clang
-179
View File
@@ -1,179 +0,0 @@
name: Codex Fix CI
on:
workflow_dispatch:
inputs:
workflow_run_url:
description: "Failing CI workflow run URL (e.g., https://github.com/lancedb/lancedb/actions/runs/12345678)"
required: true
type: string
branch:
description: "Branch to fix (e.g., main, release/v2.0, or feature-branch)"
required: true
type: string
guidelines:
description: "Additional guidelines for the fix (optional)"
required: false
type: string
permissions:
contents: write
pull-requests: write
actions: read
jobs:
fix-ci:
runs-on: warp-ubuntu-latest-x64-4x
timeout-minutes: 60
env:
CC: clang
CXX: clang++
steps:
- name: Show inputs
run: |
echo "workflow_run_url = ${{ inputs.workflow_run_url }}"
echo "branch = ${{ inputs.branch }}"
echo "guidelines = ${{ inputs.guidelines }}"
- name: Checkout Repo
uses: actions/checkout@v6
with:
ref: ${{ inputs.branch }}
fetch-depth: 0
persist-credentials: true
- name: Set up Node.js
uses: actions/setup-node@v6
with:
# pnpm 11 (used by the nodejs install step below) requires
# Node >= 22.13; use 24 since 22 hits EOL in October.
node-version: 24
- name: Install Codex CLI
run: npm install -g @openai/codex
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: clippy, rustfmt
- uses: Swatinem/rust-cache@v2
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler libssl-dev
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install Python dependencies
run: |
pip install maturin ruff pytest pyarrow pandas polars
- name: Set up Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '11'
cache: maven
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 11.1.1
- name: Install Node.js dependencies for TypeScript bindings
run: |
cd nodejs
pnpm install --frozen-lockfile
- name: Configure git user
run: |
git config user.name "lancedb automation"
git config user.email "robot@lancedb.com"
- name: Run Codex to fix CI failure
env:
WORKFLOW_RUN_URL: ${{ inputs.workflow_run_url }}
BRANCH: ${{ inputs.branch }}
GUIDELINES: ${{ inputs.guidelines }}
GITHUB_TOKEN: ${{ secrets.ROBOT_TOKEN }}
GH_TOKEN: ${{ secrets.ROBOT_TOKEN }}
OPENAI_API_KEY: ${{ secrets.CODEX_TOKEN }}
run: |
set -euo pipefail
cat <<EOF >/tmp/codex-prompt.txt
You are running inside the lancedb repository on a GitHub Actions runner. Your task is to fix a CI failure.
Input parameters:
- Failing workflow run URL: ${WORKFLOW_RUN_URL}
- Branch to fix: ${BRANCH}
- Additional guidelines: ${GUIDELINES:-"None provided"}
Follow these steps exactly:
1. Extract the run ID from the workflow URL. The URL format is https://github.com/lancedb/lancedb/actions/runs/<run_id>.
2. Use "gh run view <run_id> --json jobs,conclusion,name" to get information about the failed run.
3. Identify which jobs failed. For each failed job, use "gh run view <run_id> --job <job_id> --log-failed" to get the failure logs.
4. Analyze the failure logs to understand what went wrong. Common failures include:
- Compilation errors
- Test failures
- Clippy warnings treated as errors
- Formatting issues
- Dependency issues
5. Based on the analysis, fix the issues in the codebase:
- For compilation errors: Fix the code that doesn't compile
- For test failures: Fix the failing tests or the code they test
- For clippy warnings: Apply the suggested fixes
- For formatting issues: Run "cargo fmt --all"
- For other issues: Apply appropriate fixes
6. After making fixes, verify them locally:
- Run "cargo fmt --all" to ensure formatting is correct
- Run "cargo clippy --workspace --tests --all-features -- -D warnings" to check for issues
- Run ONLY the specific failing tests to confirm they pass now:
- For Rust test failures: Run the specific test with "cargo test -p <crate> <test_name>"
- For Python test failures: Build with "cd python && maturin develop" then run "pytest <specific_test_file>::<test_name>"
- For Java test failures: Run "cd java && mvn test -Dtest=<TestClass>#<testMethod>"
- For TypeScript test failures: Run "cd nodejs && pnpm build && pnpm test -- --testNamePattern='<test_name>'"
- Do NOT run the full test suite - only run the tests that were failing
7. If the additional guidelines are provided, follow them as well.
8. Inspect "git status --short" and "git diff" to review your changes.
9. Create a fix branch: "git checkout -b codex/fix-ci-<run_id>".
10. Stage all changes with "git add -A" and commit with message "fix: resolve CI failures from run <run_id>".
11. Push the branch: "git push origin codex/fix-ci-<run_id>". If the remote branch exists, delete it first with "gh api -X DELETE repos/lancedb/lancedb/git/refs/heads/codex/fix-ci-<run_id>" then push. Do NOT use "git push --force" or "git push -f".
12. Create a pull request targeting "${BRANCH}":
- Title: "ci: <short summary describing the fix>" (e.g., "ci: fix clippy warnings in lancedb" or "ci: resolve test flakiness in vector search")
- First, write the PR body to /tmp/pr-body.md using a heredoc (cat <<'PREOF' > /tmp/pr-body.md). The body should include:
- Link to the failing workflow run
- Summary of what failed
- Description of the fixes applied
- Then run "gh pr create --base ${BRANCH} --body-file /tmp/pr-body.md".
13. Display the new PR URL, "git status --short", and a summary of what was fixed.
Constraints:
- Use bash commands for all operations.
- Do not merge the PR.
- Do not modify GitHub workflow files unless they are the cause of the failure.
- If any command fails, diagnose and attempt to fix the issue instead of aborting immediately.
- If you cannot fix the issue automatically, create the PR anyway with a clear explanation of what you tried and what remains to be fixed.
- env "GH_TOKEN" is available, use "gh" tools for GitHub-related operations.
EOF
printenv OPENAI_API_KEY | codex login --with-api-key
codex --config shell_environment_policy.ignore_default_excludes=true exec --dangerously-bypass-approvals-and-sandbox "$(cat /tmp/codex-prompt.txt)"
+6
View File
@@ -50,6 +50,10 @@ jobs:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- name: Extract SDK documentation links
run: |
python3 ci/extract_sdk_doc_links.py --output ./lychee-inputs/sdk-doc-links.md
- name: Check links
id: lychee
continue-on-error: true
@@ -64,10 +68,12 @@ jobs:
args: >-
--scheme https
--scheme http
--include-fragments
--no-progress
--max-retries 3
--timeout 20
'docs/src/**/*.md'
'./lychee-inputs/sdk-doc-links.md'
format: json
output: ./lychee/out.json
jobSummary: false
+34 -2
View File
@@ -1,8 +1,8 @@
name: GitHub Release
# All SDKs share one version, so a single `vX.Y.Z` tag produces a single GitHub
# release covering all of them. The per-package publish workflows (PyPI, NPM,
# Cargo, Maven) trigger off the same tag independently.
# release covering all of them, including CLI binaries. The per-package publish
# workflows (PyPI, NPM, Cargo, Maven) trigger off the same tag independently.
on:
push:
@@ -13,7 +13,11 @@ permissions:
contents: read
jobs:
cli:
uses: ./.github/workflows/cli-release.yml
gh-release:
needs: cli
runs-on: ubuntu-latest
permissions:
contents: write
@@ -22,6 +26,15 @@ jobs:
with:
fetch-depth: 0
lfs: true
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- uses: actions/download-artifact@v8
with:
name: cli-release
path: dist
- name: Verify CLI release assets
run: python ci/package_cli.py verify --output dist
- name: Extract version
id: extract_version
env:
@@ -83,3 +96,22 @@ jobs:
generate_release_notes: false
name: LanceDB v${{ steps.extract_version.outputs.version }}
body: ${{ steps.release_notes.outputs.changelog }}
files: |
dist/lancedb-*.tar.gz
dist/SHA256SUMS
fail_on_unmatched_files: true
overwrite_files: true
report-failure:
runs-on: ubuntu-24.04
needs: [cli, gh-release]
if: always() && failure()
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v6
- uses: ./.github/actions/create-failure-issue
with:
job-results: ${{ toJSON(needs) }}
workflow-name: ${{ github.workflow }}
+11 -2
View File
@@ -39,7 +39,9 @@ jobs:
contents: write
steps:
- name: Output Inputs
run: echo "${{ toJSON(github.event.inputs) }}"
env:
INPUTS_JSON: ${{ toJSON(github.event.inputs) }}
run: echo "$INPUTS_JSON"
- uses: actions/checkout@v6
with:
fetch-depth: 0
@@ -59,10 +61,17 @@ jobs:
- name: Bump version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_TYPE: ${{ inputs.type }}
BUMP_MINOR: ${{ inputs.bump-minor }}
run: |
pip install bump-my-version PyGithub packaging
bash ci/bump_version.sh ${{ inputs.type }} ${{ inputs.bump-minor }}
bash ci/bump_version.sh "$RELEASE_TYPE" "$BUMP_MINOR"
release_tag=$(git describe --tags --exact-match HEAD)
bash ci/update_lockfiles.sh --amend
# Keep the unpublished tag on the commit that includes the synced lockfile.
if [ "$(git rev-parse "${release_tag}^{}")" != "$(git rev-parse HEAD)" ]; then
git tag --force --annotate "$release_tag" --message "$(git log -1 --format=%s)" HEAD
fi
- name: Push new version tag
if: ${{ !inputs.dry_run }}
uses: ad-m/github-push-action@881a6320fdb16eb5318c5054f31c218aec2b324c # v1.3.0
+2 -1
View File
@@ -36,7 +36,8 @@ concurrency:
jobs:
linux:
name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }}
timeout-minutes: 60
# The ARM64 release build can exceed an hour with fat LTO on a cold runner.
timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }}
strategy:
matrix:
config:
+11 -2
View File
@@ -161,7 +161,16 @@ jobs:
- name: Test without pylance or pandas
run: |
pip uninstall -y pylance pandas
pytest -vv python/tests/test_table.py python/tests/test_namespace_no_pylance.py
# These modules still import optional packages during collection or
# exercise them throughout many tests; the full run above covers them.
pytest -m "not slow and not s3_test" -vv --durations=30 python/tests \
--ignore=python/tests/docs \
--ignore=python/tests/test_context.py \
--ignore=python/tests/test_db.py \
--ignore=python/tests/test_embeddings.py \
--ignore=python/tests/test_embeddings_slow.py \
--ignore=python/tests/test_namespace_integration.py \
--ignore=python/tests/test_query.py
# Make sure wheels are not included in the Rust cache
- name: Delete wheels
run: rm -rf target/wheels
@@ -171,7 +180,7 @@ jobs:
matrix:
features: ["default", "experimental-functions"]
timeout-minutes: 30
runs-on: macos-14
runs-on: macos-15
defaults:
run:
shell: bash
+38 -10
View File
@@ -14,6 +14,12 @@ on:
- docs/web-tests/blob-v2/rs/**
- nodejs/Cargo.toml
- python/Cargo.toml
- python/src/**
- python/python/lancedb/exceptions.py
- python/python/lancedb/remote/errors.py
- ci/build_no_lock.py
- ci/tests/test_build_no_lock.py
- .github/actions/setup-protoc/**
- .github/workflows/rust.yml
permissions:
@@ -134,7 +140,8 @@ jobs:
command: check advisories bans licenses sources
build-no-lock:
runs-on: ubuntu-24.04
# Keep the existing Linux runner; its available disk varies by image.
runs-on: ubuntu-2404-4x-x64
timeout-minutes: 30
env:
# Need up-to-date compilers for kernels
@@ -161,9 +168,22 @@ jobs:
run: |
sudo apt update
sudo apt install -y protobuf-compiler libssl-dev
- name: Test build output cleanup
run: python3 -m unittest discover -s ci/tests -p test_build_no_lock.py -v
- name: Build all
run: |
cargo build --profile ci --benches --all-features --tests
df -h .
# Every target is linked, but this job never executes the test binaries.
python3 ci/build_no_lock.py
- name: Report build disk usage
if: always()
run: |
df -h .
for build_path in target "$HOME/.cargo/registry" "$HOME/.cargo/git"; do
if [ -d "$build_path" ]; then
du -h -d 2 "$build_path"
fi
done
linux:
timeout-minutes: 60
@@ -179,6 +199,8 @@ jobs:
# Need up-to-date compilers for kernels
CC: clang-18
CXX: clang++-18
# Preserve the repository CPU flags and use setup-mold's system linker.
RUSTFLAGS: "-C target-cpu=haswell -C target-feature=+avx2,+fma,+f16c -C linker-features=-lld"
steps:
- uses: actions/checkout@v6
with:
@@ -218,16 +240,20 @@ jobs:
sudo mkswap "$swapfile"
sudo swapon "$swapfile"
- name: Build
run: cargo build --profile ci --all-features --tests --locked --examples
run: cargo build --profile ci -p lancedb --all-features --tests --locked --examples
- name: Run feature tests
run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests
- name: Run examples
run: cargo run --profile ci --all-features --example simple --locked
run: cargo run --profile ci -p lancedb --all-features --example simple --locked
- name: Run blob v2 docs example
# Python and TypeScript blob docs tests install preview packages.
# Those builds are not guaranteed to remain available for more than
# 6 months, so they stay a manual run. This example uses the workspace crate.
run: cargo run --profile ci --all-features -p lancedb-blob-v2-docs --example multimodal --locked
run: |
# The completed all-features checks leave large lancedb artifacts in target.
# Reclaim that package before building the example with a different feature set.
cargo clean --profile ci -p lancedb
cargo run --profile ci --all-features -p lancedb-blob-v2-docs --example multimodal --locked
remote:
timeout-minutes: 30
@@ -243,6 +269,8 @@ jobs:
env:
CC: clang-18
CXX: clang++-18
# Rust's default rust-lld bypasses setup-mold's /usr/bin/ld replacement.
RUSTFLAGS: "-C target-cpu=haswell -C target-feature=+avx2,+fma,+f16c -C linker-features=-lld"
GH_TOKEN: ${{ github.token }}
SOPHON_READ_TOKEN: ${{ secrets.SOPHON_READ_TOKEN }}
steps:
@@ -270,7 +298,7 @@ jobs:
timeout-minutes: 60
strategy:
matrix:
mac-runner: ["macos-14", "macos-15"]
mac-runner: ["macos-15", "macos-26"]
runs-on: "${{ matrix.mac-runner }}"
defaults:
run:
@@ -324,8 +352,8 @@ jobs:
# unreadable outside their own branch anyway, since GitHub scopes
# caches to the creating ref.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install Protoc v21.12
run: choco install --no-progress protoc
- name: Install protoc
uses: ./.github/actions/setup-protoc
- name: Build
run: |
$env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT
@@ -361,8 +389,8 @@ jobs:
# unreadable outside their own branch anyway, since GitHub scopes
# caches to the creating ref.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install Protoc v21.12
run: choco install --no-progress protoc
- name: Install protoc
uses: ./.github/actions/setup-protoc
- name: Build
run: |
$env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT
+8 -11
View File
@@ -72,7 +72,7 @@ are wrappers around the Rust library.
* `node`: **Deprecated** Typescript package source code
* `java`: Java package source code
* `docs/src`: SDK reference, built with mkdocs
* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Distributed
* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Enterprise
* `docs/web-tests`: the tests the documentation's code examples are extracted from
## Documentation
@@ -84,13 +84,13 @@ it is ready for readers.
### Choose the right place
- `docs/web/` holds website guides for LanceDB Embedded and the APIs used by both
Embedded and Distributed.
Embedded and Enterprise.
- `docs/src/` holds the SDK reference. See [docs/README.md](docs/README.md) for
its build and API-generation instructions.
- `docs/web-tests/` and `rust/lancedb/tests/` hold tests used to generate the
website's code examples.
Document SDK APIs here, and explain which operations work in Embedded and Distributed.
Document SDK APIs here, and explain which operations work in Embedded and Enterprise.
Put Enterprise-specific deployment and operating instructions in the Enterprise
documentation.
@@ -150,18 +150,15 @@ example.
### Say where a feature works
Use `availability` in a page's frontmatter to describe the support covered by
that page. Each product (`oss` for LanceDB Embedded, `enterprise` for LanceDB
Enterprise) is either `available` or `unavailable`; use the summary
and body for setup requirements, SDK differences and unsupported operations.
For example, a page about signing in to Enterprise could declare:
that page. Each product (`embedded` for LanceDB Embedded, `enterprise` for
LanceDB Enterprise) is `available` or `unavailable`. Use the body for setup
requirements, SDK differences and unsupported operations. For example, a page
about signing in to Enterprise could declare:
```yaml
availability:
oss: unavailable
embedded: unavailable
enterprise: available
summary: >-
These sign-in instructions apply to LanceDB Enterprise. LanceDB
Embedded has no server to sign in to.
```
Check these claims with the feature owner. Don't use `varies`, treat an API
Generated
+577 -417
View File
File diff suppressed because it is too large Load Diff
+17 -17
View File
@@ -19,21 +19,21 @@ categories = ["database-implementations"]
rust-version = "1.95.0"
[workspace.dependencies]
lance = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-linalg = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" }
lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lancedb = { path = "rust/lancedb", default-features = false }
ahash = "0.8"
anyhow = "1"
@@ -49,8 +49,7 @@ arrow-select = "59.2.0"
arrow-cast = "59.2.0"
arrow-flight = { version = "59.2.0", features = ["flight-sql-experimental"] }
async-trait = "0"
# Smithy JSON 0.63 requires the pre-1.7 Document representation; allow the MSRV pin.
aws-smithy-types = ">=1.3.6, <1.7"
aws-smithy-types = "1.9.1"
base64 = "0.22"
bytes = "1"
datafusion = { version = "55.0.0", default-features = false }
@@ -82,6 +81,7 @@ url = "2"
num-traits = "0.2"
oauth2 = { version = "5.0", default-features = false }
regex = "1.10"
reqwest = { version = "0.13.0", default-features = false }
semver = "1.0.25"
serde = "1"
serde_json = { version = "1", features = ["preserve_order"] }
+1 -1
View File
@@ -51,7 +51,7 @@ LanceDB is a central location where developers can build, train and analyze thei
### **Ecosystem**:
- **Columnar Storage**: Built on the Lance columnar format for efficient storage and analytics.
- **Seamless Integration**: Python, Node.js, Rust, and REST APIs for easy integration. Native Python and Javascript/Typescript support.
- **Rich Ecosystem**: Integrations with [**LangChain** 🦜️🔗](https://python.langchain.com/docs/integrations/vectorstores/lancedb/), [**LlamaIndex** 🦙](https://gpt-index.readthedocs.io/en/latest/examples/vector_stores/LanceDBIndexDemo.html), Apache-Arrow, Pandas, Polars, DuckDB and more on the way.
- **Rich Ecosystem**: Integrations with [**LangChain** 🦜️🔗](https://docs.lancedb.com/integrations/ai/langchain), [**LlamaIndex** 🦙](https://docs.lancedb.com/integrations/ai/llamaIndex), Apache-Arrow, Pandas, Polars, DuckDB and more on the way.
## **How to Install**:
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Run inside a native-architecture manylinux_2_28 container. Cargo and rustup
# are mounted from the runner; keep the image's compiler/toolchain PATH intact.
set -euo pipefail
export PATH="/cargo/bin:$PATH"
# The manylinux images provide GCC, but do not guarantee Clang or LLD. Native
# dependencies use Clang, and the Arm linker wrapper below also requires LLD.
dnf install -y clang lld
export CC=clang CXX=clang++
"$CC" --version
"$CXX" --version
ld.lld --version
# Fail before Cargo downloads or compiles dependencies if either compiler or
# the linker cannot produce a runnable binary in this container.
printf 'int main(void) { return 0; }\n' > /tmp/cli-toolchain-probe.c
"$CC" -fuse-ld=lld /tmp/cli-toolchain-probe.c -o /tmp/cli-toolchain-probe
/tmp/cli-toolchain-probe
"$CXX" -fuse-ld=lld -x c++ /tmp/cli-toolchain-probe.c -o /tmp/cli-toolchain-probe
/tmp/cli-toolchain-probe
git config --global --add safe.directory /workspace
curl -fsSL "https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-${PROTOC_PLATFORM}.zip" -o /tmp/protoc.zip
echo "${PROTOC_SHA256} /tmp/protoc.zip" | sha256sum -c -
unzip -q /tmp/protoc.zip -d /tmp/protoc
export PATH="/tmp/protoc/bin:$PATH"
# GNU ld on Arm has a much higher memory peak for Lance's final link. Use a
# linker wrapper without replacing the repository's CPU and feature rustflags.
if [[ "$CLI_TARGET" == aarch64-unknown-linux-gnu ]]; then
cat > /tmp/cli-linker <<'LINKER'
#!/bin/sh
exec clang -fuse-ld=lld "$@"
LINKER
chmod 755 /tmp/cli-linker
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=/tmp/cli-linker
fi
cargo build --locked --release -p lancedb-cli --bin lancedb --target "$CLI_TARGET"
strip "target/$CLI_TARGET/release/lancedb"
+111
View File
@@ -0,0 +1,111 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Link all CI test/bench targets after the workflow removes Cargo.lock.
This job never runs the test binaries. Discard their completed
executables while retaining normal binaries, libraries and build-script outputs.
"""
import json
import shutil
import subprocess
import sys
from pathlib import Path
def discard_test_executable(message: dict, target_dir: Path) -> bool:
if message.get("reason") != "compiler-artifact":
return False
target = message["target"]
kinds = target["kind"]
# profile.test describes this build; target.test is only a manifest capability.
# Ordinary binaries may still be needed through CARGO_BIN_EXE by later targets.
if "custom-build" in kinds or not (
message["profile"]["test"] or "test" in kinds or "bench" in kinds
):
return False
executable = message.get("executable")
if executable is None:
return False
path = Path(executable)
if not path.resolve().is_relative_to(target_dir.resolve()):
raise ValueError(f"executable {path} is outside target directory {target_dir}")
if not path.is_file():
return False
size = path.stat().st_size
path.unlink()
print(
json.dumps(
{
"removed_test_executable": str(path),
"target": target["name"],
"logical_bytes": size,
"filesystem_free_bytes": shutil.disk_usage(path.parent).free,
}
),
flush=True,
)
return True
def main() -> int:
metadata = subprocess.run(
["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"],
stdout=subprocess.PIPE,
text=True,
)
if metadata.returncode:
return metadata.returncode
target_dir = Path(json.loads(metadata.stdout)["target_directory"])
command = [
"cargo",
"build",
"--profile",
"ci",
"--benches",
"--all-features",
"--tests",
# Bound simultaneous compiler/linker temporary outputs as well as retained files.
"--jobs",
"1",
"--message-format=json,json-diagnostic-rendered-ansi",
]
cleanup_failed = False
with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process:
assert process.stdout is not None
for line in process.stdout:
try:
message = json.loads(line)
except json.JSONDecodeError:
print(line, end="", flush=True)
continue
if not isinstance(message, dict):
print(line, end="", flush=True)
continue
if message.get("reason") == "compiler-message":
diagnostic = message["message"]
sys.stderr.write(
diagnostic.get("rendered") or json.dumps(diagnostic) + "\n"
)
sys.stderr.flush()
elif message.get("reason") == "compiler-artifact":
try:
discard_test_executable(message, target_dir)
except (OSError, ValueError) as error:
print(
f"Cannot discard completed test executable: {error}",
file=sys.stderr,
)
cleanup_failed = True
elif message.get("reason") not in {
"build-script-executed",
"build-finished",
}:
print(line, end="", flush=True)
result = process.wait()
return result if result else int(cleanup_failed)
if __name__ == "__main__":
sys.exit(main())
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Extract documentation links defined in rust/lancedb/src/docs.rs for link checking."""
from __future__ import annotations
import argparse
from pathlib import Path
import re
import sys
REPO_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DOCS_RS = REPO_ROOT / "rust" / "lancedb" / "src" / "docs.rs"
def _parse_match_arm_map(match_arms: str) -> dict[str, str | None]:
mapping: dict[str, str | None] = {}
uncommented = "\n".join(
line for line in match_arms.splitlines() if not line.strip().startswith("//")
)
for raw_arm in uncommented.split(","):
arm = " ".join(raw_arm.split())
if not arm or "=>" not in arm:
continue
lhs, rhs = [part.strip() for part in arm.split("=>", 1)]
variants = [
part.strip().removeprefix("Self::")
for part in lhs.split("|")
if part.strip()
]
if rhs == "None":
value: str | None = None
else:
str_match = re.search(r'"([^"]+)"', rhs)
if not str_match:
raise ValueError(f"unsupported match arm value: {rhs}")
value = str_match.group(1)
for variant in variants:
mapping[variant] = value
return mapping
def extract_doc_links(docs_rs_path: Path = DEFAULT_DOCS_RS) -> list[str]:
source = docs_rs_path.read_text(encoding="utf-8")
base_match = re.search(
r'pub\s+const\s+DOCS_BASE_URL:\s*&str\s*=\s*"([^"]+)";', source
)
if not base_match:
raise ValueError("DOCS_BASE_URL not found in docs.rs")
base_url = base_match.group(1)
all_match = re.search(
r"pub\s+const\s+ALL:\s*&'static\s*\[Self\]\s*=\s*&\[(.*?)\];",
source,
re.DOTALL,
)
if not all_match:
raise ValueError("DocLink::ALL not found in docs.rs")
variants = re.findall(r"Self::([A-Za-z0-9_]+)", all_match.group(1))
if not variants:
raise ValueError("no variants found in DocLink::ALL")
path_fn = re.search(
r"pub\s+const\s+fn\s+path\(self\)\s*->\s*&'static\s+str\s*\{\s*match\s+self\s*\{(.*?)\}\s*\}",
source,
re.DOTALL,
)
anchor_fn = re.search(
r"pub\s+const\s+fn\s+anchor\(self\)\s*->\s*Option<&'static\s+str>\s*\{\s*match\s+self\s*\{(.*?)\}\s*\}",
source,
re.DOTALL,
)
if not path_fn or not anchor_fn:
raise ValueError("DocLink::path or DocLink::anchor not found in docs.rs")
paths = _parse_match_arm_map(path_fn.group(1))
anchors = _parse_match_arm_map(anchor_fn.group(1))
urls: list[str] = []
for variant in variants:
path = paths.get(variant)
if not path:
raise ValueError(f"missing path mapping for DocLink::{variant}")
anchor = anchors.get(variant)
url = f"{base_url}{path}#{anchor}" if anchor else f"{base_url}{path}"
if url not in urls:
urls.append(url)
return urls
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--docs-rs",
type=Path,
default=DEFAULT_DOCS_RS,
help="Path to rust/lancedb/src/docs.rs",
)
parser.add_argument(
"--output",
type=Path,
required=True,
help="Markdown file to write extracted links to",
)
args = parser.parse_args(argv)
urls = extract_doc_links(args.docs_rs)
args.output.parent.mkdir(parents=True, exist_ok=True)
lines = ["# SDK documentation links", ""] + [f"- <{url}>" for url in urls] + [""]
args.output.write_text("\n".join(lines), encoding="utf-8")
return 0
if __name__ == "__main__":
sys.exit(main())
+230
View File
@@ -0,0 +1,230 @@
"""Package and validate standalone CLI release assets (Python 3.12+).
Run `version` before building, `package` on each native runner, then `checksums`
after gathering the archives. Run `verify` again immediately before publication.
"""
import argparse
import hashlib
import os
import re
import subprocess
import tarfile
import tempfile
import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TARGETS = (
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"aarch64-apple-darwin",
)
NOTICES = ("LICENSE", "RUST_THIRD_PARTY_LICENSES.html")
def release_version(root: Path, ref: str) -> str:
config = tomllib.loads((root / ".bumpversion.toml").read_text())["tool"][
"bumpversion"
]
version = config["current_version"]
if not re.fullmatch(r"\d+\.\d+\.\d+(?:-beta\.\d+)?", version):
raise ValueError(f"Unsupported release version: {version}")
for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"):
package = tomllib.loads((root / manifest).read_text())["package"]
if package["version"] != version:
raise ValueError(f"{manifest} version does not match {version}")
if ref.startswith("refs/tags/") and ref != f"refs/tags/v{version}":
raise ValueError(f"Tag {ref} does not match v{version}")
return version
def archive_stem(version: str, target: str) -> str:
return f"lancedb-v{version}-{target}"
def command(*args: str) -> str:
return subprocess.check_output(args, text=True)
def check_linux_metadata(header: str, dynamic: str, symbols: str, target: str):
machine = (
"AArch64" if target.startswith("aarch64") else "Advanced Micro Devices X86-64"
)
if not re.search(rf"Machine:\s+{re.escape(machine)}\s*$", header, re.MULTILINE):
raise ValueError(f"ELF architecture does not match {target}")
allowed = {
"libc.so.6",
"libdl.so.2",
"libm.so.6",
"libpthread.so.0",
"librt.so.1",
"libgcc_s.so.1",
"libstdc++.so.6",
"ld-linux-x86-64.so.2",
"ld-linux-aarch64.so.1",
}
needed = set(re.findall(r"\(NEEDED\).*\[([^\]]+)\]", dynamic))
if not needed or needed - allowed:
raise ValueError(f"Unexpected runtime libraries: {sorted(needed - allowed)}")
if re.search(r"\((?:RPATH|RUNPATH)\)", dynamic):
raise ValueError("CLI must not depend on a build-container runtime path")
# AlmaLinux 8 provides glibc 2.28, GCC 8's libstdc++, and libgcc.
limits = {
"GLIBC": (2, 28),
"GLIBCXX": (3, 4, 25),
"CXXABI": (1, 3, 11),
"GCC": (7, 0, 0),
}
for namespace, limit in limits.items():
for value in re.findall(rf"\b{namespace}_([\d.]+)\b", symbols):
if tuple(map(int, value.split("."))) > limit:
raise ValueError(
f"Runtime symbol {namespace}_{value} exceeds Linux baseline"
)
if "GLIBC_PRIVATE" in symbols:
raise ValueError("CLI must not require private glibc symbols")
def check_macos_metadata(arches: str, libraries: str, build: str):
if arches.strip() != "arm64":
raise ValueError("CLI must contain exactly the arm64 architecture")
for library in re.findall(r"^\s+(\S+) \(", libraries, re.MULTILINE):
if not library.startswith(("/usr/lib/", "/System/Library/")):
raise ValueError(f"Non-system macOS runtime library: {library}")
minimum = re.findall(r"^\s*minos ([\d.]+)\s*$", build, re.MULTILINE)
if len(minimum) != 1 or tuple(map(int, minimum[0].split("."))) != (14, 0):
raise ValueError("CLI must target macOS 14.0")
def check_runtime(binary: Path, target: str):
path = str(binary.resolve())
if target.endswith("linux-gnu"):
check_linux_metadata(
command("readelf", "-h", path),
command("readelf", "-d", path),
command("readelf", "--version-info", path),
target,
)
else:
command("codesign", "--verify", "--strict", path)
check_macos_metadata(
command("lipo", "-archs", path),
command("otool", "-L", path),
command("vtool", "-show-build", path),
)
def verify_archive(archive: Path, version: str, target: str):
stem = archive_stem(version, target)
expected = {f"{stem}/{name}" for name in ("lancedb", *NOTICES)}
with tarfile.open(archive, "r:gz") as tar:
members = tar.getmembers()
if len(members) != len(expected) or {m.name for m in members} != expected:
raise ValueError(f"Unexpected archive contents: {archive.name}")
for member in members:
mode = 0o755 if member.name.endswith("/lancedb") else 0o644
if not member.isfile() or member.mode != mode or member.size == 0:
raise ValueError(f"Invalid archive member: {member.name}")
def smoke_test(archive: Path, version: str, target: str):
verify_archive(archive, version, target)
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
with tarfile.open(archive, "r:gz") as tar:
tar.extractall(directory, filter="data")
binary = directory / archive_stem(version, target) / "lancedb"
home = directory / "home"
home.mkdir()
env = {k: v for k, v in os.environ.items() if not k.startswith("LANCEDB_")}
env.update(HOME=str(home), XDG_CONFIG_HOME=str(home / ".config"))
for args in (("--help",), ("--version",), ("profile", "list")):
output = subprocess.run(
[str(binary), *args],
cwd=home,
env=env,
check=True,
capture_output=True,
text=True,
timeout=30,
)
if args == ("--version",) and output.stdout.strip() != f"lancedb {version}":
raise ValueError(
f"Packaged CLI reports the wrong version: {output.stdout!r}"
)
if args == ("--help",) and "Usage:" not in output.stdout:
raise ValueError("Packaged CLI did not print help")
if (
args == ("profile", "list")
and "Configured profiles:" not in output.stdout
):
raise ValueError("Packaged CLI did not list profiles")
def package(root: Path, binary: Path, target: str, output: Path, version: str) -> Path:
check_runtime(binary, target)
output.mkdir(parents=True, exist_ok=True)
stem = archive_stem(version, target)
archive = output / f"{stem}.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
for name, source in [
("lancedb", binary),
*((name, root / name) for name in NOTICES),
]:
member = tar.gettarinfo(str(source), arcname=f"{stem}/{name}")
member.mode = 0o755 if name == "lancedb" else 0o644
member.uid = member.gid = 0
member.uname = member.gname = ""
with source.open("rb") as file:
tar.addfile(member, file)
smoke_test(archive, version, target)
return archive
def checksum_lines(output: Path, version: str) -> str:
expected = {f"{archive_stem(version, target)}.tar.gz": target for target in TARGETS}
found = {path.name for path in output.glob("*.tar.gz")}
if found != expected.keys():
raise ValueError(
f"Expected exactly these CLI archives: {sorted(expected)}; found {sorted(found)}"
)
lines = []
for name, target in sorted(expected.items()):
archive = output / name
verify_archive(archive, version, target)
with archive.open("rb") as file:
digest = hashlib.file_digest(file, "sha256").hexdigest()
lines.append(f"{digest} {name}\n")
return "".join(lines)
def verify_checksums(output: Path, version: str):
if (output / "SHA256SUMS").read_text() != checksum_lines(output, version):
raise ValueError("SHA256SUMS does not match the CLI release archives")
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("version")
build = commands.add_parser("package")
build.add_argument("--binary", type=Path, required=True)
build.add_argument("--target", choices=TARGETS, required=True)
build.add_argument("--output", type=Path, required=True)
for name in ("checksums", "verify"):
commands.add_parser(name).add_argument("--output", type=Path, required=True)
args = parser.parse_args()
version = release_version(ROOT, os.environ.get("GITHUB_REF", ""))
if args.command == "version":
print(version)
elif args.command == "package":
print(package(ROOT, args.binary, args.target, args.output, version))
elif args.command == "checksums":
(args.output / "SHA256SUMS").write_text(checksum_lines(args.output, version))
else:
verify_checksums(args.output, version)
if __name__ == "__main__":
main()
+3
View File
@@ -155,6 +155,9 @@ def update_cargo_toml(line_updater):
lines = core_manifest.read_text().splitlines(keepends=True)
for index, line in enumerate(lines):
if line.startswith("lance-arrow ="):
dependency = tomllib.loads(line)["lance-arrow"]
if isinstance(dependency, dict) and dependency.get("workspace"):
continue
updated = tomllib.loads(line_updater(line))["lance-arrow"]
config = {"version": updated} if isinstance(updated, str) else updated
if "path" in config:
+65
View File
@@ -0,0 +1,65 @@
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "build_cli_linux.sh"
class BuildCliLinuxTest(unittest.TestCase):
def test_toolchain_failures_stop_before_downloads_and_cargo(self):
# Start with controlled tools so the host's compilers cannot mask a
# missing container dependency. No command can download or build code.
for failed_tool, exit_code in (
("dnf", 42),
("clang", 127),
("clang++", 127),
("ld.lld", 127),
):
with (
self.subTest(failed_tool=failed_tool),
tempfile.TemporaryDirectory() as tmp,
):
workdir = Path(tmp)
bin_dir = workdir / "bin"
bin_dir.mkdir()
log = workdir / "commands.log"
for name in (
"dnf",
"clang",
"clang++",
"ld.lld",
"git",
"curl",
"cargo",
):
status = exit_code if name == failed_tool else 0
if name in ("git", "curl", "cargo"):
status = 99
command = bin_dir / name
command.write_text(
f'#!/bin/sh\necho "{name}" >> "$CLI_TEST_LOG"\nexit {status}\n'
)
command.chmod(0o755)
env = dict(os.environ, PATH=str(bin_dir), CLI_TEST_LOG=str(log))
result = subprocess.run(
["/bin/bash", str(SCRIPT)],
check=False,
cwd=workdir,
env=env,
capture_output=True,
text=True,
timeout=10,
)
self.assertEqual(result.returncode, exit_code, result.stderr)
commands = log.read_text().splitlines()
self.assertEqual(commands[0], "dnf")
self.assertEqual(commands[-1], failed_tool)
self.assertNotIn("git", commands)
self.assertNotIn("curl", commands)
self.assertNotIn("cargo", commands)
if __name__ == "__main__":
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "build_no_lock.py"
SPEC = importlib.util.spec_from_file_location("build_no_lock", SCRIPT)
BUILD = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(BUILD)
class BuildNoLockTest(unittest.TestCase):
def fixture(self, directory):
root = Path(directory)
(root / "src").mkdir()
(root / "tests").mkdir()
(root / "benches").mkdir()
(root / "Cargo.toml").write_text(
'[package]\nname = "artifact_fixture"\nversion = "0.0.0"\nedition = "2024"\n'
"[workspace]\n[features]\nprobe = []\n"
'[[bin]]\nname = "fixture_cli"\npath = "src/main.rs"\n'
'[[bench]]\nname = "fixture_bench"\nharness = false\n'
'[profile.ci]\ninherits = "dev"\ndebug = 0\nincremental = false\n'
)
(root / "build.rs").write_text(
'fn main() { let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap());'
' std::fs::write(out.join("generated.rs"), "pub fn value() -> u32 { 7 }").unwrap(); }'
)
(root / "src/lib.rs").write_text(
'#[cfg(not(feature = "probe"))] compile_error!("all features must be built");\n'
'include!(concat!(env!("OUT_DIR"), "/generated.rs"));\n'
"#[test] fn library_test() { assert_eq!(value(), 7); }\n"
)
(root / "src/main.rs").write_text(
"fn main() { assert_eq!(artifact_fixture::value(), 7); }\n"
)
(root / "tests/retains_binary.rs").write_text(
"#[test] fn ordinary_binary_is_available() {\n"
' assert!(std::process::Command::new(env!("CARGO_BIN_EXE_fixture_cli"))\n'
" .status().unwrap().success()); }\n"
)
(root / "benches/fixture_bench.rs").write_text(
"fn main() { assert_eq!(artifact_fixture::value(), 7); }\n"
)
return root
def run_build(self, root):
env = os.environ | {"CARGO_TARGET_DIR": str(root / "target")}
return subprocess.run(
[sys.executable, str(SCRIPT)],
cwd=root,
env=env,
text=True,
capture_output=True,
)
def test_links_all_targets_and_retains_compiler_inputs(self):
# Stay below the repository so rustup keeps its configured toolchain.
with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp:
root = self.fixture(temp)
result = self.run_build(root)
self.assertEqual(result.returncode, 0, result.stderr)
messages = [
json.loads(line)
for line in result.stdout.splitlines()
if line.startswith("{")
]
removed = [item for item in messages if "removed_test_executable" in item]
self.assertTrue(
{"artifact_fixture", "fixture_cli", "retains_binary", "fixture_bench"}
<= {item["target"] for item in removed}
)
self.assertTrue(
all(
not Path(item["removed_test_executable"]).exists()
for item in removed
)
)
target = root / "target/ci"
self.assertTrue((target / "fixture_cli").is_file())
# Cargo guarantees this binary for test execution, not compile-time reads.
subprocess.run([str(target / "fixture_cli")], check=True)
self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib")))
self.assertTrue(list((target / "build").glob("*/build-script-build")))
self.assertTrue(list((target / "build").glob("*/out/generated.rs")))
def test_link_failure_preserves_cargo_status_and_diagnostic(self):
with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp:
root = self.fixture(temp)
with (root / "src/lib.rs").open("a") as file:
file.write(
'#[cfg(test)] unsafe extern "C" { fn missing_no_lock_probe_symbol(); }\n'
"#[test] fn linker_must_run() { unsafe { missing_no_lock_probe_symbol() } }\n"
)
result = self.run_build(root)
self.assertEqual(result.returncode, 101, result.stderr)
self.assertIn("missing_no_lock_probe_symbol", result.stderr)
self.assertIn("linking with", result.stderr)
def test_never_deletes_an_executable_outside_the_target_directory(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
target = root / "target"
target.mkdir()
outside = root / "other-owner-binary"
outside.write_bytes(b"keep")
message = {
"reason": "compiler-artifact",
"target": {"kind": ["test"], "name": "foreign"},
"profile": {"test": True},
"executable": str(outside),
}
with self.assertRaisesRegex(ValueError, "outside target directory"):
BUILD.discard_test_executable(message, target)
self.assertEqual(outside.read_bytes(), b"keep")
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from ci.extract_sdk_doc_links import extract_doc_links, main
class TestExtractSdkDocLinks(unittest.TestCase):
def test_extracts_all_links_from_repo_docs_rs(self) -> None:
urls = extract_doc_links()
self.assertIn(
"https://docs.lancedb.com/performance#compaction-and-cleanup",
urls,
)
self.assertIn(
"https://docs.lancedb.com/indexing/reindexing#incremental-reindexing",
urls,
)
self.assertIn(
"https://docs.lancedb.com/search/sql",
urls,
)
self.assertIn(
"https://docs.lancedb.com/basics/embedded-vs-enterprise",
urls,
)
def test_cli_writes_markdown(self) -> None:
with TemporaryDirectory() as tmp:
out = Path(tmp) / "sdk-links.md"
rc = main(["--output", str(out)])
self.assertEqual(rc, 0)
content = out.read_text(encoding="utf-8")
self.assertIn(
"<https://docs.lancedb.com/performance#compaction-and-cleanup>",
content,
)
if __name__ == "__main__":
unittest.main()
+228
View File
@@ -0,0 +1,228 @@
import io
import os
import tarfile
import tempfile
import tomllib
import unittest
from pathlib import Path
from unittest.mock import patch
from ci import package_cli as cli
VERSION = "1.2.3-beta.4"
class PackageCliTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.output = self.root / "dist"
self.write_versions(VERSION)
for name in cli.NOTICES:
(self.root / name).write_text(f"Test {name}\n")
self.binary = self.root / "lancedb"
self.binary.write_text(
"#!/usr/bin/env python3\n"
"import os, sys\n"
"assert not any(k.startswith('LANCEDB_') for k in os.environ)\n"
"assert os.environ['HOME'] != os.environ.get('ORIGINAL_HOME')\n"
"assert not os.listdir(os.environ['HOME'])\n"
f"print({{('--version',): 'lancedb {VERSION}', "
"('--help',): 'Usage: lancedb', "
"('profile', 'list'): 'Configured profiles:'}[tuple(sys.argv[1:])])\n"
)
# Packaging must restore executable permissions even if the input lacks them.
self.binary.chmod(0o644)
def write_versions(self, version):
(self.root / ".bumpversion.toml").write_text(
f'[tool.bumpversion]\ncurrent_version = "{version}"\n'
)
for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"):
path = self.root / manifest
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(f'[package]\nversion = "{version}"\n')
def make_package(self, target=cli.TARGETS[0]):
with patch.object(cli, "check_runtime"):
return cli.package(self.root, self.binary, target, self.output, VERSION)
def test_stable_and_beta_versions_and_tags(self):
for version in ("1.2.3", VERSION):
self.write_versions(version)
for ref in (
f"refs/tags/v{version}",
"refs/heads/main",
"refs/pull/1/merge",
):
with self.subTest(version=version, ref=ref):
self.assertEqual(cli.release_version(self.root, ref), version)
def test_mismatched_tag_and_manifests_fail(self):
with self.assertRaisesRegex(ValueError, "Tag"):
cli.release_version(self.root, "refs/tags/v1.2.3")
for manifest in ("rust/lancedb/Cargo.toml", "rust/lancedb/cli/Cargo.toml"):
self.write_versions(VERSION)
(self.root / manifest).write_text('[package]\nversion = "0.1.0"\n')
with (
self.subTest(manifest=manifest),
self.assertRaisesRegex(ValueError, "version does not match"),
):
cli.release_version(self.root, "refs/heads/main")
def test_cli_participates_in_repository_version_bumps(self):
config = tomllib.loads((cli.ROOT / ".bumpversion.toml").read_text())["tool"][
"bumpversion"
]
entry = next(
f
for f in config["files"]
if f.get("filename") == "rust/lancedb/cli/Cargo.toml"
)
manifest = (cli.ROOT / entry["filename"]).read_text()
version = cli.release_version(cli.ROOT, "")
self.assertIn(entry["search"].format(current_version=version), manifest)
lock = tomllib.loads((cli.ROOT / "Cargo.lock").read_text())
package = next(p for p in lock["package"] if p["name"] == "lancedb-cli")
self.assertEqual(package["version"], version)
def test_archive_layout_permissions_and_isolated_smoke_test(self):
with patch.dict(
os.environ,
{"LANCEDB_API_KEY": "unused", "ORIGINAL_HOME": os.environ["HOME"]},
):
archive = self.make_package()
self.assertEqual(archive.name, f"lancedb-v{VERSION}-{cli.TARGETS[0]}.tar.gz")
cli.verify_archive(archive, VERSION, cli.TARGETS[0])
with tarfile.open(archive) as tar:
for member in tar.getmembers():
self.assertEqual(member.uid, 0)
self.assertEqual(member.gid, 0)
def test_wrong_binary_version_fails_smoke_test(self):
self.binary.write_text(
self.binary.read_text().replace(f"lancedb {VERSION}", "lancedb 0.1.0")
)
with self.assertRaisesRegex(ValueError, "wrong version"):
self.make_package()
def test_bad_archive_members_are_rejected(self):
archive = self.make_package()
stem = cli.archive_stem(VERSION, cli.TARGETS[0])
for bad in (
"missing",
"extra",
"duplicate",
"symlink",
"permissions",
"empty",
"traversal",
):
with self.subTest(bad=bad):
with tarfile.open(archive, "w:gz") as tar:
for name in ("lancedb", *cli.NOTICES):
if bad == "missing" and name == "LICENSE":
continue
member = tarfile.TarInfo(f"{stem}/{name}")
member.mode = 0o755 if name == "lancedb" else 0o644
member.size = 1
if name == "lancedb":
if bad == "symlink":
member.type = tarfile.SYMTYPE
member.linkname = "/usr/bin/true"
member.size = 0
elif bad == "permissions":
member.mode = 0o644
elif bad == "empty":
member.size = 0
elif bad == "traversal":
member.name = "../lancedb"
tar.addfile(member, io.BytesIO(b"x"))
if bad in ("extra", "duplicate"):
member = tarfile.TarInfo(
f"{stem}/{'LICENSE' if bad == 'duplicate' else 'extra'}"
)
tar.addfile(member)
with self.assertRaises(ValueError):
cli.verify_archive(archive, VERSION, cli.TARGETS[0])
def test_checksums_require_exact_target_set_and_detect_tampering(self):
self.make_package()
with self.assertRaisesRegex(ValueError, "exactly"):
cli.checksum_lines(self.output, VERSION)
for target in cli.TARGETS[1:]:
self.make_package(target)
manifest = self.output / "SHA256SUMS"
lines = cli.checksum_lines(self.output, VERSION)
manifest.write_text(lines)
self.assertEqual(len(lines.splitlines()), 3)
cli.verify_checksums(self.output, VERSION)
# Still a valid archive, but a different payload from the published digest.
self.binary.write_text(self.binary.read_text() + "# changed\n")
self.make_package()
with self.assertRaisesRegex(ValueError, "SHA256SUMS"):
cli.verify_checksums(self.output, VERSION)
(self.output / "unexpected.tar.gz").write_bytes(b"extra")
with self.assertRaisesRegex(ValueError, "exactly"):
cli.checksum_lines(self.output, VERSION)
class RuntimeMetadataTest(unittest.TestCase):
def test_linux_baseline_and_architectures(self):
for target, machine in (
(cli.TARGETS[0], "Advanced Micro Devices X86-64"),
(cli.TARGETS[1], "AArch64"),
):
cli.check_linux_metadata(
f" Machine: {machine}\n",
" (NEEDED) Shared library: [libc.so.6]\n (NEEDED) Shared library: [libgcc_s.so.1]",
"GLIBC_2.28 GLIBCXX_3.4.25 CXXABI_1.3.11 GCC_7.0.0",
target,
)
def test_linux_rejects_wrong_arch_new_symbols_and_non_system_libraries(self):
header = " Machine: Advanced Micro Devices X86-64\n"
dynamic = " (NEEDED) Shared library: [libc.so.6]"
cases = [(" Machine: AArch64\n", dynamic, "GLIBC_2.28")]
for symbol in (
"GLIBC_2.29",
"GLIBCXX_3.4.26",
"CXXABI_1.3.12",
"GCC_12.0.0",
"GLIBC_PRIVATE",
):
cases.append((header, dynamic, symbol))
for extra in (
" (NEEDED) Shared library: [libssl.so.3]",
" (RUNPATH) Library runpath: [/opt/build/lib]",
):
cases.append((header, dynamic + extra, "GLIBC_2.28"))
for args in cases:
with self.subTest(args=args), self.assertRaises(ValueError):
cli.check_linux_metadata(*args, cli.TARGETS[0])
def test_macos_baseline_and_system_libraries(self):
cli.check_macos_metadata(
"arm64\n",
"cli:\n\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0)",
" minos 14.0\n",
)
def test_macos_rejects_wrong_arch_version_and_homebrew_dependencies(self):
for args in (
("x86_64", "", " minos 14.0\n"),
("arm64", "", " minos 15.0\n"),
("arm64", "", ""),
(
"arm64",
"\t/opt/homebrew/lib/libssl.dylib (compatibility version 3.0.0)",
" minos 14.0\n",
),
):
with self.subTest(args=args), self.assertRaises(ValueError):
cli.check_macos_metadata(*args)
if __name__ == "__main__":
unittest.main()
+19
View File
@@ -146,6 +146,25 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], "
f"{command!r} not found in {commands!r}",
)
with (workdir / "Cargo.toml").open("a") as manifest:
manifest.write('lance-arrow = "1.0.0"\n')
for inherited in (
"lance-arrow = { workspace = true }",
"lance-arrow.workspace = true",
):
inherited_manifest = f"[dependencies]\n{inherited}\n"
core_manifest.write_text(inherited_manifest)
result = subprocess.run(
[sys.executable, str(SCRIPT), version],
cwd=workdir,
env=env,
capture_output=True,
text=True,
timeout=10,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(core_manifest.read_text(), inherited_manifest)
def _write_fake_executables(self, fake_bin: Path) -> None:
cargo = fake_bin / "cargo"
cargo.write_text(
+8
View File
@@ -131,6 +131,14 @@ ignore = [
{ id = "RUSTSEC-2026-0391", reason = "zstd 0.13 via arrow-ipc 58; affected with_context API is unused" },
{ id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" },
{ id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" },
# pin-utils: unmaintained; reviewed 2026-11-05. Transitive via
# aws-smithy-http/runtime/types, including aws-config -> lance-io.
# No safe upgrade exists; clearing requires AWS Smithy to migrate to
# core::pin::pin!, pin-project, or pin-project-lite. Revisit on AWS updates.
# https://rustsec.org/advisories/RUSTSEC-2026-0441
# https://github.com/rustsec/advisory-db/issues/3314
{ id = "RUSTSEC-2026-0441", reason = "pin-utils unmaintained via AWS Smithy; no safe upgrade, awaiting upstream migration" },
]
@@ -0,0 +1,78 @@
# OCI Generative AI Embeddings
[Oracle Cloud Infrastructure (OCI) Generative AI](https://docs.oracle.com/en-us/iaas/Content/generative-ai/home.htm) hosts Cohere embedding models behind an OCI-native, IAM-authenticated API.
Using the `oci-genai` embedding function requires the OCI Python SDK, which can be installed using `pip install oci`. No API key is stored in LanceDB: requests are signed by the SDK with one of the standard OCI authentication methods, so a compartment OCID and an identity that is allowed to `use generative-ai-family` in that compartment are all that is needed.
Supported models are:
- `cohere.embed-v4.0` (1536 dims by default; `output_dimensions` can request 256, 512, 1024 or 1536)
- `cohere.embed-english-v3.0`, `cohere.embed-multilingual-v3.0` (1024 dims)
- `cohere.embed-english-light-v3.0`, `cohere.embed-multilingual-light-v3.0` (384 dims)
- Any dedicated AI cluster endpoint OCID (`ocid1.generativeaiendpoint...`) hosting an embedding model
Cohere embedding models are asymmetric: rows of the source column are embedded with `input_type="SEARCH_DOCUMENT"` and search queries with `input_type="SEARCH_QUERY"`. Inputs are sent in batches of at most 96 texts (the service limit), and the vector size is discovered with a single probe request unless `output_dimensions` is set.
Supported parameters (to be passed in `create` method) are:
| Parameter | Type | Default Value | Description |
|---|---|--------|---------|
| `name` | `str` | `"cohere.embed-v4.0"` | Model ID of an on-demand embedding model, or a dedicated AI cluster endpoint OCID. |
| `compartment_id` | `str` | `None` | OCID of the compartment the requests are authorized in and billed to. Required by the service; falls back to the `OCI_COMPARTMENT_ID` environment variable. |
| `region` | `str` | `"us-chicago-1"` | Region used to derive the inference endpoint `https://inference.generativeai.<region>.oci.oraclecloud.com`. |
| `service_endpoint` | `str` | `None` | Full inference endpoint. Overrides `region`; use it for realms with a different endpoint template. |
| `auth_type` | `str` | `"API_KEY"` | `API_KEY`, `SECURITY_TOKEN`, `INSTANCE_PRINCIPAL` or `RESOURCE_PRINCIPAL` (see below). |
| `auth_profile` | `str` | `"DEFAULT"` | Profile name in the OCI config file (`API_KEY` and `SECURITY_TOKEN` only). |
| `auth_file_location` | `str` | `"~/.oci/config"` | Path of the OCI config file (`API_KEY` and `SECURITY_TOKEN` only). |
| `truncate` | `str` | `"END"` | What to do with inputs longer than the model context: `NONE` (fail), `START` or `END` (drop tokens from that side). |
| `source_input_type` | `str` | `"SEARCH_DOCUMENT"` | `input_type` used when embedding the source column. |
| `query_input_type` | `str` | `"SEARCH_QUERY"` | `input_type` used when embedding queries. |
| `output_dimensions` | `int` | `None` | Embedding size for models that support it (`cohere.embed-v4.0`: 256, 512, 1024, 1536). |
When a table is opened in a new process, an explicit `service_endpoint` or a non-default `region` restored from table metadata requires approval with `get_registry().allow_endpoint(...)`. The default `us-chicago-1` endpoint does not need approval.
Authentication options:
| `auth_type` | Identity used |
|---|---|
| `API_KEY` | User API key from profile `auth_profile` in `auth_file_location` (the setup produced by `oci setup config`). |
| `SECURITY_TOKEN` | Short-lived session token from the same profile, as written by `oci session authenticate`. |
| `INSTANCE_PRINCIPAL` | The Compute instance the code runs on; needs a dynamic group policy. |
| `RESOURCE_PRINCIPAL` | The OCI resource the code runs in (OKE workload identity, Functions, Data Science, ...). |
Usage Example:
```python
import lancedb
from lancedb.pydantic import LanceModel, Vector
from lancedb.embeddings import get_registry
oci_genai = get_registry().get("oci-genai").create(
name="cohere.embed-v4.0",
compartment_id="ocid1.compartment.oc1..<your-compartment>",
auth_type="API_KEY",
auth_profile="DEFAULT",
region="us-chicago-1",
)
class TextModel(LanceModel):
text: str = oci_genai.SourceField()
vector: Vector(oci_genai.ndims()) = oci_genai.VectorField()
data = [{"text": "hello world"},
{"text": "goodbye world"}]
db = lancedb.connect("~/.lancedb")
tbl = db.create_table("test", schema=TextModel, mode="overwrite")
tbl.add(data)
rs = tbl.search("hello").limit(1).to_pandas()
```
The compartment OCID can also be supplied at runtime instead of being stored in the table metadata, either through the `OCI_COMPARTMENT_ID` environment variable or with a registry variable:
```python
registry = get_registry()
registry.set_var("oci_compartment", "ocid1.compartment.oc1..<your-compartment>")
oci_genai = registry.get("oci-genai").create(compartment_id="$var:oci_compartment")
```
+2 -2
View File
@@ -3,7 +3,7 @@
The LanceDB Java SDK provides a convenient way to interact with LanceDB Enterprise deployments using the Lance REST Namespace API.
!!! note
The Java SDK currently only works with LanceDB Distributed, connecting to LanceDB Enterprise or LanceDB Cloud (legacy).
The Java SDK currently only connects to LanceDB Enterprise or LanceDB Cloud (legacy).
LanceDB Embedded support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress.
## Installation
@@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
<dependency>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-core</artifactId>
<version>0.41.0-beta.17</version>
<version>0.42.0-beta.9</version>
</dependency>
```
+11 -11
View File
@@ -182,7 +182,7 @@ Define a materialized view named `name` over the table `source`.
LanceDB Embedded creation and refresh require a source build with the
`experimental-functions` Cargo feature, disabled in published packages.
LanceDB Distributed operations do not require this feature.
LanceDB Enterprise operations do not require this feature.
The view is populated before creation returns. Set `withNoData` to create
only its definition and empty backing table. The view is a normal table:
@@ -558,10 +558,11 @@ on the returned job to know when cleanup has finished.
abstract dropView(name, namespacePath?): Promise<void>
```
Drop the view named `name` and wait for its definition to be deleted.
Drop the view named `name` and wait for catalog removal.
The tables it reads are untouched: a view holds no rows of its own. Use
[dropViewAsync](Connection.md#dropviewasync) to retain the cleanup job instead of waiting on it.
[dropViewAsync](Connection.md#dropviewasync) to retain its SQL query job. Completion confirms
catalog removal; physical cleanup continues in the background.
#### Parameters
@@ -581,11 +582,9 @@ The tables it reads are untouched: a view holds no rows of its own. Use
abstract dropViewAsync(name, namespacePath?): Promise<Job>
```
Start dropping the view named `name` and return the job deleting its
definition, without waiting for completion.
The name is free before this resolves. When nothing was bound to it, the
returned job is already finished and has no id.
Drop a view and return its SQL query job.
The job has type `query` and its ID is the SQL query UUID. Waiting confirms
catalog removal; physical cleanup continues in the background.
#### Parameters
@@ -827,9 +826,10 @@ abstract renameTable(
Rename a table.
Currently only supported in LanceDB Distributed. LanceDB Embedded connections and
namespace-backed connections (via [connectNamespace](../functions/connectNamespace.md)) reject with
a "not supported" error.
Supported in LanceDB Enterprise and by namespace backends that implement
renaming. Directory namespaces support renaming tables resolved through their
manifest, including tables within or across child namespaces. LanceDB Embedded
connections and directory-listing root tables reject with a "not supported" error.
#### Parameters
+1 -1
View File
@@ -252,7 +252,7 @@ static labelList(): Index
Create a label list index.
LabelList index is a scalar index that can be used on `List<T>` columns to
support queries with `array_contains_all` and `array_contains_any`
support queries with `array_has_all` and `array_has_any`
using an underlying bitmap index.
#### Returns
+30 -1
View File
@@ -171,6 +171,24 @@ per fragment. `filter` is a SQL-like expression over the `state`,
***
### progress()
```ts
progress(): Promise<null | JobProgress>
```
Fetch a structured progress snapshot.
Registry jobs include lifecycle and queue metadata even when their job
type does not report counters. The returned object is forward-compatible
with newer servers and job types. In-process operations return null.
#### Returns
`Promise`&lt;`null` \| [`JobProgress`](../interfaces/JobProgress.md)&gt;
***
### refresh()
```ts
@@ -223,11 +241,22 @@ printing it.
### wait()
```ts
wait(): Promise<void>
wait(progressCallback?): Promise<void>
```
Wait until the operation reaches a terminal state.
The optional callback observes the same snapshots fetched by the backend
poller that drives completion; it does not start another poller. Without a
callback, this preserves the original wait behavior. The callback is a
synchronous observer: its return value is ignored and not awaited. If it
throws, the error is logged with `console.warn` and waiting continues; a
callback exception does not reject `wait`.
#### Parameters
* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md)
#### Returns
`Promise`&lt;`void`&gt;
+73 -11
View File
@@ -71,7 +71,7 @@ Add new columns with defined values.
LanceDB Embedded computed-column declaration and refresh require a source
build with the `experimental-functions` Cargo feature. Published packages
disable it; LanceDB Distributed operations remain available.
disable it; LanceDB Enterprise operations remain available.
The `{ computed }` form stores the expression rather than evaluating it
now: the column is committed with no values, and rows get them from
@@ -83,7 +83,7 @@ computed, so a mutated input is reflected by the next refresh. While a
declaration reads a column, that column cannot be renamed, retyped or
dropped.
In LanceDB Distributed the expression is planned by the
In LanceDB Enterprise the expression is planned by the
server, and the refresh runs as a server job -- see
[Table#refreshColumnAsync](Table.md#refreshcolumnasync).
@@ -126,6 +126,9 @@ abstract alterColumns(columnAlterations): Promise<AlterColumnsResult>
Alter the name or nullability of columns.
Local tables reject renaming source or vector columns referenced by
`embedding_functions` schema metadata, preserving the embedding binding.
#### Parameters
* **columnAlterations**: [`ColumnAlteration`](../interfaces/ColumnAlteration.md)[]
@@ -354,6 +357,24 @@ vector and non-vector searches)
We currently don't support custom named indexes.
The index name will always be `${column}_idx`.
On LanceDB Embedded tables the index is built before the returned promise
resolves. On LanceDB Enterprise tables it resolves once the build is
scheduled. Until the build finishes, a vector index may be missing from
[Table.listIndices](Table.md#listindices), a scalar or FTS index may be listed with 0
indexed rows, and queries won't use the index. To wait until the index is
ready, set [IndexOptions.waitTimeoutSeconds](../interfaces/IndexOptions.md#waittimeoutseconds), call
[Table.waitForIndex](Table.md#waitforindex), or use [Table.createIndexAsync](Table.md#createindexasync) and wait
on its job when the server returned a job ID.
`waitTimeoutSeconds` waits for the submitted build when the server returns
a job ID. On older servers that don't return one, it falls back to polling
the index by name. [Table.waitForIndex](Table.md#waitforindex) always waits by name. When
replacing an existing index, those name-based waits may return before the
new build finishes because the old index can still match.
`createIndexAsync` can track a specific build only when the server returned
a job ID; otherwise it returns an already-complete job and callers must
use [Table.waitForIndex](Table.md#waitforindex) for that build.
#### Parameters
* **column**: `string`
@@ -410,6 +431,11 @@ Create an index, returning a handle to the indexing job.
The job may already be complete when returned; callers must not assume
the index exists until [Job.wait](Job.md#wait) resolves.
In LanceDB Enterprise, the returned job tracks this submission only if the
server returns a job ID. If it does not, the job is already complete and
does not wait for the background build; use [Table.waitForIndex](Table.md#waitforindex) and
account for the replacement caveat described in [Table.createIndex](Table.md#createindex).
#### Parameters
* **column**: `string`
@@ -504,6 +530,9 @@ underlying storage. In order to remove the data, you must subsequently
call ``compact_files`` to rewrite the data without the removed columns and
then call ``cleanup_files`` to remove the old files.
Local tables reject dropping source or vector columns referenced by
`embedding_functions` schema metadata, preserving the embedding binding.
#### Parameters
* **columnNames**: `string`[]
@@ -686,7 +715,7 @@ The per-row errors Function refreshes recorded on this table.
A refresh running under a skip policy records each row it skipped with
the input that failed and the error. This lists those records, newest
job first, plus a summary for any fragment whose per-row detail was
capped. LanceDB Distributed only; reading errors needs read
capped. LanceDB Enterprise only; reading errors needs read
access to the table, since a message carries the value that failed.
#### Parameters
@@ -843,6 +872,11 @@ abstract listIndices(): Promise<IndexConfig[]>
List all indices that have been created with [Table.createIndex](Table.md#createindex)
On LanceDB Enterprise tables, an index whose build hasn't finished may be
missing (vector indices) or listed with 0 indexed rows (scalar and FTS
indices), and `numUnindexedRows` may be undefined. Use
[Table.waitForIndex](Table.md#waitforindex) to wait until an index is ready.
#### Returns
`Promise`&lt;[`IndexConfig`](../interfaces/IndexConfig.md)[]&gt;
@@ -909,6 +943,15 @@ Modeled after ``VACUUM`` in PostgreSQL.
you have added or modified 100,000 or more records or run more than 20 data
modification operations.
On a LanceDB Enterprise (remote) table, only compaction is currently
supported. Pruning old versions and index optimization are silently
skipped there instead of being attempted, so this call resolves
successfully, with zeroed pruning statistics, once the compaction job
has been submitted; it does not wait for that job to finish.
`compactionOptions` can tune the four per-job settings documented in
[CompactionOptions](../interfaces/CompactionOptions.md). Older-server errors are propagated without
retrying with the settings removed.
#### Parameters
* **options?**: `Partial`&lt;[`OptimizeOptions`](../interfaces/OptimizeOptions.md)&gt;
@@ -939,7 +982,7 @@ Prewarm one or more columns of data in the table.
Prewarming is generally useful for columns used in filters or projections.
Large columns (e.g. high-dimensional vectors or binary data) may not be
practical to prewarm.
This feature is currently only supported in LanceDB Distributed.
This feature is currently only supported in LanceDB Enterprise.
#### Returns
@@ -1042,7 +1085,7 @@ for await (const batch of table.query()) {
### refreshColumn()
```ts
abstract refreshColumn(column): Promise<RefreshColumnResult>
abstract refreshColumn(column, options?): Promise<RefreshColumnResult>
```
Fill the rows of a computed column that hold no value yet.
@@ -1051,13 +1094,17 @@ Local refresh requires a source build with `experimental-functions`.
Rows appended since the last refresh are filled by the next one, and
rows whose inputs changed since they were computed are recomputed;
everything else is left as it is. LanceDB Embedded only: in LanceDB
Distributed a refresh runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync).
Enterprise a refresh runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync).
#### Parameters
* **column**: `string`
The name of the computed column to fill.
* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md)
Refresh options, all LanceDB
Enterprise only; see [Table#refreshColumnAsync](Table.md#refreshcolumnasync).
#### Returns
`Promise`&lt;[`RefreshColumnResult`](../interfaces/RefreshColumnResult.md)&gt;
@@ -1070,26 +1117,36 @@ number of rows filled and the new version number of the table.
### refreshColumnAsync()
```ts
abstract refreshColumnAsync(column): Promise<Job>
abstract refreshColumnAsync(column, options?): Promise<Job>
```
Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh
job instead of blocking until it completes.
LanceDB Embedded refresh requires a source build with
`experimental-functions`. LanceDB Distributed jobs do not require this
`experimental-functions`. LanceDB Enterprise jobs do not require this
feature.
The job may already be complete when returned; callers must not assume
the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input --
an unknown column, or one that is not computed -- rejects here rather
than failing the job. In LanceDB Embedded the job runs in-process; in
LanceDB Distributed it is the server's backfill job.
LanceDB Enterprise it is the server's backfill job.
#### Parameters
* **column**: `string`
The name of the computed column to fill.
* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md)
Refresh options, mirroring the SQL
`REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows,
`errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds`
and `initTimeoutSeconds` govern failing rows, and `batchSize`,
`gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker`
size the workers. All are LanceDB Enterprise only; a LanceDB Embedded
refresh rejects every option other than `batchSize`, `gpuClass` and
`gpuCount`.
#### Returns
`Promise`&lt;[`Job`](Job.md)&gt;
@@ -1097,7 +1154,12 @@ LanceDB Distributed it is the server's backfill job.
#### Example
```ts
const job = await table.refreshColumnAsync("doubled");
const job = await table.refreshColumnAsync("embedding", {
where: "published_at > '2026-01-01'",
errorPolicy: "skip",
maxFailedFraction: 0.01,
rowTimeoutSeconds: 30,
});
await job.wait();
console.log(await job.status()); // "finished"
```
@@ -1312,7 +1374,7 @@ Tokenize a full-text search query using the tokenizer configured on an FTS index
Specify exactly one of `column` or `indexName`.
Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in
the client process from index metadata. In LanceDB Distributed, this means the
the client process from index metadata. In LanceDB Enterprise, this means the
same tokenizer model files must also exist locally (under
`LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A
mismatch cannot be detected: the returned tokens may differ from what the
+37
View File
@@ -101,6 +101,38 @@ AnalyzeExec verbose=true, metrics=[]
***
### approxMode()
```ts
approxMode(approxMode): VectorQuery
```
Set the speed / accuracy tradeoff to use for approximate search
This currently affects RQ-quantized indexes, such as IVF_RQ, and
prefiltered search on HNSW indexes, where "fast" enables the ACORN
traversal. Other index types ignore this setting.
"fast" favors lower latency and may reduce recall, "normal" (the default)
uses the index's default balance, and "accurate" favors higher recall and
may increase latency.
#### Parameters
* **approxMode**: `"fast"` \| `"normal"` \| `"accurate"`
#### Returns
[`VectorQuery`](VectorQuery.md)
#### Example
```ts
table.vectorSearch([0.1, 0.2]).approxMode("fast").limit(10);
```
***
### bypassVectorIndex()
```ts
@@ -654,6 +686,11 @@ searchEffort(searchEffort): VectorQuery
Set the initial IVF search effort to a finite value in [0, 1].
Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
80% and 90% for L2, cosine and dot through k=100000. The probe budget
adapts to the metric and k. Hamming and larger k remain uncalibrated;
100000 is not an API limit. Remote queries also require server support.
The default, null, uses Auto (internally 0.5). Zero starts at the caller
minimum; one searches all partitions within the caller maximum. Later
probing may continue when too few candidates are found.
+4
View File
@@ -74,6 +74,7 @@
- [ClientConfig](interfaces/ClientConfig.md)
- [ColumnAlteration](interfaces/ColumnAlteration.md)
- [ColumnOrdering](interfaces/ColumnOrdering.md)
- [CompactionOptions](interfaces/CompactionOptions.md)
- [CompactionStats](interfaces/CompactionStats.md)
- [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
- [ConnectionOptions](interfaces/ConnectionOptions.md)
@@ -109,6 +110,7 @@
- [JobEventsOptions](interfaces/JobEventsOptions.md)
- [JobFailureInfo](interfaces/JobFailureInfo.md)
- [JobInfo](interfaces/JobInfo.md)
- [JobProgress](interfaces/JobProgress.md)
- [ListingOptions](interfaces/ListingOptions.md)
- [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md)
- [MemtableStats](interfaces/MemtableStats.md)
@@ -121,6 +123,7 @@
- [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
- [RTEStats](interfaces/RTEStats.md)
- [RTEWriteSpec](interfaces/RTEWriteSpec.md)
- [RefreshColumnOptions](interfaces/RefreshColumnOptions.md)
- [RefreshColumnResult](interfaces/RefreshColumnResult.md)
- [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
- [RemovalStats](interfaces/RemovalStats.md)
@@ -170,6 +173,7 @@
- [FieldLike](type-aliases/FieldLike.md)
- [IntoSql](type-aliases/IntoSql.md)
- [IntoVector](type-aliases/IntoVector.md)
- [JobProgressCallback](type-aliases/JobProgressCallback.md)
- [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md)
- [MultiVector](type-aliases/MultiVector.md)
- [RecordBatchLike](type-aliases/RecordBatchLike.md)
+1 -1
View File
@@ -19,7 +19,7 @@ optional allowExternalBlobOutsideBases: boolean;
Whether blob URIs outside registered external bases may be written.
Defaults to `false`. This option is supported only in LanceDB Embedded;
LanceDB Distributed returns an error when it is enabled. An enabled write
LanceDB Enterprise returns an error when it is enabled. An enabled write
stores the absolute URI reference without registering a base or copying
the external object into the database. The object must remain accessible
when the blob is read later.
@@ -0,0 +1,49 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / CompactionOptions
# Interface: CompactionOptions
Per-invocation compaction settings. Values must be safe integers.
## Properties
### batchSize?
```ts
optional batchSize: number;
```
Positive scanner batch size in rows.
***
### ioBufferSize?
```ts
optional ioBufferSize: number;
```
Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure.
***
### maxSourceRows?
```ts
optional maxSourceRows: number;
```
Positive live-source-row budget across whole tasks; an oversized first task can produce no work.
***
### targetRowsPerFragment?
```ts
optional targetRowsPerFragment: number;
```
Positive target rows per output fragment; also affects candidate selection.
@@ -90,3 +90,13 @@ detail was capped.
```ts
tableVersion: number;
```
***
### traceback?
```ts
optional traceback: string;
```
User-code traceback, possibly truncated by the server.
+9 -9
View File
@@ -31,7 +31,7 @@ optional createdAt: Date;
When the index was created.
`undefined` in LanceDB Distributed or indices created before timestamps were tracked.
`undefined` in LanceDB Enterprise or indices created before timestamps were tracked.
***
@@ -44,7 +44,7 @@ optional indexDetails: any;
Index-type-specific details parsed as a JavaScript object.
Falls back to a raw string if JSON parsing fails. `undefined` in
LanceDB Distributed or when details are unavailable.
LanceDB Enterprise or when details are unavailable.
***
@@ -66,7 +66,7 @@ optional indexUuid: string;
The UUID of the first segment of the index.
`undefined` in LanceDB Distributed, which does not yet surface this.
`undefined` in LanceDB Enterprise, which does not yet surface this.
***
@@ -78,7 +78,7 @@ optional indexVersion: number;
The on-disk index format version.
`undefined` in LanceDB Distributed.
`undefined` in LanceDB Enterprise.
***
@@ -100,7 +100,7 @@ optional numIndexedRows: number;
The number of rows indexed, across all segments.
May be `undefined` in LanceDB Distributed if the server does not report it.
May be `undefined` in LanceDB Enterprise if the server does not report it.
***
@@ -112,7 +112,7 @@ optional numSegments: number;
The number of segments that make up the index.
`undefined` in LanceDB Distributed.
`undefined` in LanceDB Enterprise.
***
@@ -124,7 +124,7 @@ optional numUnindexedRows: number;
The number of rows not yet covered by this index.
May be `undefined` in LanceDB Distributed if the server does not report it.
May be `undefined` in LanceDB Enterprise if the server does not report it.
***
@@ -136,7 +136,7 @@ optional sizeBytes: number;
The total size in bytes of all index files across all segments.
`undefined` in LanceDB Distributed or indices without size tracking.
`undefined` in LanceDB Enterprise or indices without size tracking.
***
@@ -148,4 +148,4 @@ optional typeUrl: string;
The protobuf type URL, a precise type identifier for the index.
`undefined` in LanceDB Distributed.
`undefined` in LanceDB Enterprise.
+4 -1
View File
@@ -77,4 +77,7 @@ optional waitTimeoutSeconds: number;
Timeout in seconds to wait for index creation to complete.
If not specified, the method will return immediately after starting the index creation.
Only applies to LanceDB Enterprise tables, which build the index in the
background.
If not specified, `createIndex` returns once the build is scheduled.
LanceDB Embedded tables always build the index before `createIndex` returns.
+10
View File
@@ -31,3 +31,13 @@ optional phase: string;
```ts
optional retryable: boolean;
```
***
### traceback?
```ts
optional traceback: string;
```
User-code traceback, possibly truncated by the server.
+20
View File
@@ -39,6 +39,26 @@ jobType: string;
***
### paused
```ts
paused: boolean;
```
Whether an operator has parked this job.
***
### progress
```ts
progress: Record<string, unknown>;
```
Structured lifecycle, queue, pause, and job-type-specific progress.
***
### state
```ts
+117
View File
@@ -0,0 +1,117 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / JobProgress
# Interface: JobProgress
A forward-compatible structured progress snapshot for a server-side job.
Fields are optional because older servers and different job types report
different counters. A missing counter is unknown; it is not zero.
## Indexable
\[`field`: `string`\]: `unknown`
## Properties
### estimated\_remaining\_time\_millis?
```ts
optional estimated_remaining_time_millis: number;
```
Best-effort remaining milliseconds, present only for a reliable sample.
***
### execution\_epoch?
```ts
optional execution_epoch: null | number;
```
Execution identity and sample time used for client-side ETA derivation.
***
### paused?
```ts
optional paused: boolean;
```
Whether an operator has parked the job.
***
### phase?
```ts
optional phase: null | string;
```
Coarse server-derived phase, including phases from newer servers.
***
### rows\_computed?
```ts
optional rows_computed: null | number;
```
***
### rows\_failed?
```ts
optional rows_failed: null | number;
```
***
### rows\_planned?
```ts
optional rows_planned: null | number;
```
Planned, computed, skipped, remaining, and failed row counters, when the
server reports them.
***
### rows\_remaining?
```ts
optional rows_remaining: null | number;
```
***
### rows\_skipped?
```ts
optional rows_skipped: null | number;
```
***
### sample\_at\_millis?
```ts
optional sample_at_millis: null | number;
```
***
### state?
```ts
optional state: string;
```
Lifecycle state, including states from newer servers.
+22
View File
@@ -33,6 +33,28 @@ tbl.optimize({cleanupOlderThan: new Date()});
***
### compactionOptions?
```ts
optional compactionOptions: CompactionOptions;
```
Compaction settings for this invocation. Omitted remote values inherit table
tuning, then deployment/built-in defaults.
Remote tables require a server supporting these SQL options; settings do
not change table policy. This is not a runtime or total-memory limit.
#### Example
```ts
await tbl.optimize({ compactionOptions: {
targetRowsPerFragment: 1000, maxSourceRows: 5000,
ioBufferSize: 64 * 1024 * 1024, batchSize: 128,
} });
```
***
### deleteUnverified
```ts
@@ -64,3 +64,6 @@ optional timeoutMs: number;
```
Timeout for query execution in milliseconds
The timeout also covers reading the results, so consuming them slowly can
exceed it.
@@ -0,0 +1,124 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / RefreshColumnOptions
# Interface: RefreshColumnOptions
Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every
option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores
`batchSize`, `gpuClass` and `gpuCount` and rejects the rest.
## Properties
### batchSize?
```ts
optional batchSize: number;
```
Maximum rows per Function call; must be greater than zero.
***
### errorPolicy?
```ts
optional errorPolicy: string;
```
`"fail"` (default) stops on a row error; `"skip"` writes null and
records the error, subject to the failure limits.
***
### gpuClass?
```ts
optional gpuClass: string;
```
GPU class for Function workers.
***
### gpuCount?
```ts
optional gpuCount: number;
```
Positive aggregate GPU budget for Function workers.
***
### initTimeoutSeconds?
```ts
optional initTimeoutSeconds: number;
```
Deadline for Function initialization, in seconds.
***
### maxExecutorProcessesPerWorker?
```ts
optional maxExecutorProcessesPerWorker: number;
```
Cap on executor processes per Function worker.
***
### maxFailedFraction?
```ts
optional maxFailedFraction: number;
```
Under a skip policy, fail the job once more than this share of rows
(0 to 1) has failed.
***
### maxFailedRows?
```ts
optional maxFailedRows: number;
```
Under a skip policy, fail the job once more than this many rows have
failed.
***
### numWorkers?
```ts
optional numWorkers: number;
```
Worker count for an expression column; Function columns reject it.
***
### rowTimeoutSeconds?
```ts
optional rowTimeoutSeconds: number;
```
Deadline for one Function call, in seconds.
***
### where?
```ts
optional where: string;
```
Only refresh the rows matching this SQL filter.
@@ -14,7 +14,7 @@
optional mode: string;
```
How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes.
How the view was brought up to date: "rebuild", or absent for LanceDB Enterprise SQL refreshes.
***
@@ -24,7 +24,7 @@ How the view was brought up to date: "rebuild", or absent for LanceDB Distribute
optional rowsWritten: number;
```
Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes.
Rows written by this refresh, or absent for LanceDB Enterprise SQL refreshes.
***
@@ -34,7 +34,7 @@ Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes.
optional sourceVersion: number;
```
Source version refreshed to, or absent for LanceDB Distributed SQL refreshes.
Source version refreshed to, or absent for LanceDB Enterprise SQL refreshes.
***
+1 -1
View File
@@ -21,4 +21,4 @@ optional signal: AbortSignal;
```
Cancels the read. The call rejects with `signal.reason`, and the native
read stops, including in-flight requests to a LanceDB Distributed table.
read stops, including in-flight requests to a LanceDB Enterprise table.
@@ -0,0 +1,21 @@
[**@lancedb/lancedb**](../README.md) • **Docs**
***
[@lancedb/lancedb](../globals.md) / JobProgressCallback
# Type Alias: JobProgressCallback()
```ts
type JobProgressCallback: (progress) => void;
```
Callback for progress snapshots observed while waiting for a job.
## Parameters
* **progress**: [`JobProgress`](../interfaces/JobProgress.md)
## Returns
`void`
+481 -17
View File
@@ -27,7 +27,7 @@ connect, per-table storage and write options on create, and `index_cache_size`,
Omit these options to use server-managed storage and caching. Connection-level
`storage_options` supported by an Enterprise deployment remain available.
The synchronous LanceDB Distributed `create_table` uses the same positional order as the
The synchronous LanceDB Enterprise `create_table` uses the same positional order as the
LanceDB Embedded API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value,
embedding_functions`. Prefer keyword arguments for optional parameters.
@@ -42,6 +42,12 @@ table names. `db.list_tables().tables` is a list of the first page; `limit`
controls its page size and `page_token` resumes at a saved token. The same
patterns apply to `list_namespaces()`. Other resource listings use `page_limit`.
Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and
`list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to
collect synchronous results, or `[name async for name in db.list_views()]` with
an asynchronous connection. `page_limit` controls each request, and `page_token`
resumes a listing. Drain the iterator's cached results before saving its token.
::: lancedb.listing.Listing
::: lancedb.listing.TableListing
@@ -162,6 +168,11 @@ registered functions, for example,
namespace. These objects identify resources for ACL operations; a secret object
contains the credential's name, not its value.
Storage integration objects identify database-owned storage configuration, for
example `Object.storage_integration(database="default", name="raw")`. Pass
`namespace_path` for nested namespaces. Their keyspace is separate from Secrets,
Functions, and relations; the wire name is `storage_integration:default:public$raw`.
More object types may be added in the future.
### Access control lists
@@ -205,6 +216,27 @@ for privilege in [Privilege.CREATE_SECRET, Privilege.CREATE_FUNCTION]:
Both privileges also accept their string names in synchronous and asynchronous
ACL methods.
Storage integration creation requires `CREATE_STORAGE_INTEGRATION` on its containing
namespace, together with database and namespace `USAGE`:
```python
catalog.authz.add_acl(
object=Object.namespace(database="default"),
subject=Subject.role("developer"),
privilege=Privilege.CREATE_STORAGE_INTEGRATION,
)
catalog.authz.add_acl(
object=Object.storage_integration(database="default", name="raw"),
subject=Subject.role("reader"),
privilege=Privilege.USAGE,
)
```
Creation grants ownership to the creator. Describing an integration requires
`USAGE` on that integration; dropping it requires `OWNERSHIP`. Listing integrations
requires `USAGE` on the selected database and namespace. Describing and dropping
also require parent `USAGE` grants. Manage these grants through `catalog.authz`.
By default, the `list_acls` function lists all the access control entries in
the system. By adding a function parameter, the output is filtered to just ACLs
matching that parameter. For example, this code lists all the ACLs for the
@@ -227,7 +259,7 @@ async for entry in catalog.authz.list_acls(subject=Subject.role("reader")):
## Remote SQL
Submit SQL against a LanceDB Distributed database through the connection.
Submit SQL against a LanceDB Enterprise database through the connection.
The connected database and `default_namespace_path=["public"]` are used for
unqualified tables. Fully qualified references can still query other databases
and namespaces available to the same deployment. `execute_query` returns a
@@ -308,24 +340,47 @@ listing a storage directory.
## Tables (Synchronous)
LanceDB Embedded and LanceDB Distributed tables use the same arguments for index creation, deletion,
LanceDB Embedded and LanceDB Enterprise tables use the same arguments for index creation, deletion,
index statistics, and search. For example, `table.delete(where="id = 1")`,
`table.create_index("cosine", 2)` (the deprecated vector API), and
`table.search([1.0, 1.0], fast_search=True)` work with either backend.
`fast_search=True` excludes rows that have not been indexed.
`create_scalar_index` defaults to `replace=True` on both backends. Both scalar
and full-text index creation accept `wait_timeout`. LanceDB Distributed maintenance methods
accept the LanceDB Embedded options: cleanup and compaction warn that they are no-ops,
while `optimize` reports an unsupported operation. Removed Tantivy options
produce the same explanatory errors on both backends.
and full-text index creation accept `wait_timeout`. LanceDB Enterprise maintenance methods
accept the LanceDB Embedded options: cleanup and compaction warn that they are no-ops.
`optimize` submits a durable compaction job and returns once that submission is
accepted, not once compaction itself finishes. Pruning and index optimization
are not yet supported remotely, so it silently skips them and returns with
zeroed pruning statistics. Remote `compaction_options` support per-job
`target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size`
on compatible servers. Other non-default settings raise `NotImplementedError`
before submission; older-server errors are returned without dropping options.
The source-row budget selects whole tasks and can produce no work if the first
task exceeds it. An I/O buffer size of zero disables byte-based I/O backpressure.
Use a positive size to limit I/O read-ahead; this is not a total-memory limit.
Each field resolves as invocation option → table tuning → deployment/built-in
default. These options apply only to the submitted job and leave table policy
unchanged. Table `enabled` controls automatic scheduling; explicit manual runs
remain allowed.
The old LanceDB Distributed keyword names `predicate` for `delete`, `index_name` for
```python
table.optimize(compaction_options={
"target_rows_per_fragment": 100_000,
"max_source_rows": 1_000_000,
"io_buffer_size": 64 * 1024 * 1024,
"batch_size": 1024,
})
```
Removed Tantivy options produce the same explanatory errors on both backends.
The old LanceDB Enterprise keyword names `predicate` for `delete`, `index_name` for
`drop_index`, `index_uuid` for `index_stats`, and `column` for `create_fts_index`
remain available with deprecation warnings. Use `where`, `name`, `index_name`,
and `field_names`, respectively. For positional calls, use the argument order
documented by `Table` below; specify index options by keyword when migrating
code that used the former LanceDB Distributed-only argument order.
code that used the former LanceDB Enterprise-only argument order.
::: lancedb.table.Table
@@ -345,11 +400,64 @@ code that used the former LanceDB Distributed-only argument order.
## Functions and Jobs
A `@function` definition is also a local callable. Call a decorated function
directly with row inputs, or call a decorated class with its initialization fields
and then call the returned instance; call `close()` if the class defines it. This
path uses the current Python environment and does not create a registered
`FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute
the remote Arrow adapter. A registered `FunctionVersion` call instead binds
`col(...)` inputs and returns a remote `FunctionApplication`.
```python
from lancedb import function
@function
def normalize(text: str) -> str:
return text.strip().lower()
@function
class Scale:
def __init__(self, factor: float):
self.factor = factor
def __call__(self, value: float) -> float:
return value * self.factor
def close(self) -> None:
self.factor = 0.0
assert normalize(" Hello ") == "hello"
scaler = Scale(factor=2.0)
assert scaler(3.0) == 6.0
scaler.close()
```
Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or
with `bytes` to materialize its contents before the Function runs. Reader
inputs infer the Blob V2 type without an explicit input schema. Readers are
scoped to each invocation and support `read`, `readinto`, `seek`, `tell`,
`size`, and cursor-independent `read_range`.
`size`, and cursor-independent `read_range`. For a local test or another
engine, construct `BlobReader(read_range, size)` with a callback over an
in-memory bytes fixture or the engine's byte-range reader; `read_range` does
not advance the cursor.
```python
from lancedb import BlobReader
payload = b"0123456789"
def read_range(offset: int, length: int) -> bytes:
return payload[offset : offset + length]
with BlobReader(read_range, len(payload)) as reader:
assert reader.read_range(6, 4) == b"6789"
assert reader.tell() == 0
```
::: lancedb.BlobReader
@@ -365,9 +473,9 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`,
::: lancedb.functions.PythonEnvironmentSpec
::: lancedb.functions.udf
::: lancedb.functions.function
::: lancedb.functions.UdfDefinition
::: lancedb.functions.FunctionDefinition
::: lancedb.secrets.EnvVarSecret
@@ -375,6 +483,8 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`,
::: lancedb.functions.FunctionRegistrationRequest
::: lancedb.functions.FunctionRetryPolicy
::: lancedb.functions.FunctionArtifactRequest
::: lancedb.functions.FunctionArtifactContent
@@ -385,8 +495,12 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`,
::: lancedb.functions.FunctionVersion
::: lancedb.functions.HuggingFaceModel
::: lancedb.functions.PythonRuntimeSpec
::: lancedb.GpuClass
::: lancedb.functions.FunctionVersionRef
::: lancedb.functions.ApplicationInput
@@ -432,11 +546,11 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`,
In the 0.41 SDK release, LanceDB Embedded materialized-view creation and refresh require a
source build with the `experimental-functions` Cargo feature. Published Python
packages leave it disabled. Opening, reading, listing and dropping existing views
remain available, as do LanceDB Distributed operations. The same feature
remain available, as do LanceDB Enterprise operations. The same feature
requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary
eager `add_columns` transforms remain available.
In LanceDB Distributed, creation accepts `auto_refresh_enabled` and
In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and
`auto_refresh_interval_seconds`:
```python
@@ -461,6 +575,31 @@ automatic scheduling requests.
::: lancedb.view.ViewDescription
## Property Graphs
A property graph is defined over tables of its namespace: which tables hold
nodes and which hold edges, each node table's key and label, and the node keys
each edge table's source and destination columns reference -- the shape of
SQL/PGQ's `CREATE PROPERTY GRAPH`. It stores no rows of its own; a query reads
its tables as nodes and edges through SQL `GRAPH_TABLE`.
Create one with
[create_property_graph][lancedb.db.DBConnection.create_property_graph], and
manage it with
[open_property_graph][lancedb.db.DBConnection.open_property_graph],
[list_property_graphs][lancedb.db.DBConnection.list_property_graphs] and
[drop_property_graph][lancedb.db.DBConnection.drop_property_graph].
::: lancedb.graph.NodeTable
::: lancedb.graph.EdgeTable
::: lancedb.graph.Endpoint
::: lancedb.graph.PropertyGraph
::: lancedb.graph.PropertyGraphDescription
## Expressions
Type-safe expression builder for filters and projections. Use these instead
@@ -617,7 +756,7 @@ For external blob references, construct the descriptor struct described by
[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`.
Inline `data` and external `uri` representations are mutually exclusive.
LanceDB Distributed SQL returns blob bytes by default. Select `blob_descriptor(video)` to
LanceDB Enterprise SQL returns blob bytes by default. Select `blob_descriptor(video)` to
return an openable reference instead, then use
[`open_blob_file`][lancedb.table.Table.open_blob_file] or the lazy iterable
[`open_blob_files`][lancedb.table.Table.open_blob_files]:
@@ -634,7 +773,7 @@ for row in rows.to_pylist():
frame = extract_frame(video, row["timestamp"])
```
This example uses a LanceDB Distributed SQL connection that produces source-bearing
This example uses a LanceDB Enterprise SQL connection that produces source-bearing
descriptors. The descriptor contains `kind`, `position`, `size`, `blob_id`,
`blob_uri`, and a `source` struct with `uri`, `version`, `committed_at_micros`,
`branch`, `column`, `row_reference`, and `row_is_address`. The opener verifies
@@ -666,7 +805,7 @@ async for video in async_videos.open_blob_files(rows["video"]):
```
Payload bytes load on reads. Opening an external blob with unspecified size
can issue a metadata-only HEAD request. LanceDB Distributed reads use authenticated range
can issue a metadata-only HEAD request. LanceDB Enterprise reads use authenticated range
requests that validate the captured URI and commit timestamp.
Blobs inside lists can be written and queried as descriptors. They are omitted
@@ -691,8 +830,111 @@ so the fetch APIs cannot read their bytes yet.
## Exceptions
Remote HTTP responses with structured resource details raise a subclass of
`HttpError`. Older servers that omit those details generally raise plain
`HttpError`, so `except HttpError` remains a compatible catch-all:
```python
from lancedb.remote.errors import (
AlreadyExistsError,
FunctionNotFoundError,
HttpError,
NamespaceNotFoundError,
SecretNotFoundError,
)
try:
db.describe_namespace(["analytics"])
except (SecretNotFoundError, FunctionNotFoundError, NamespaceNotFoundError) as error:
print(error.error_code, error.resource_kind, error.resource_name)
except AlreadyExistsError as error:
print("resource already exists:", error.resource_name)
except HttpError as error:
print("request failed:", error.request_id, error.status_code)
```
Remote branch deletion sends a single request. If the server rejects it with
HTTP 409, it raises `ConflictError` with the server's reason, including when an
older server omits structured resource details. A structured `already_exists`
response keeps its more specific `AlreadyExistsError` type. Both are subclasses
of `HttpError`.
A remote query whose streamed response stops partway raises
`ResponseInterruptedError`, also a subclass of `HttpError`. It carries the number
of batches and rows already returned and, when the server reports it, the table
version the response reflected, so the query can be run again against that
version. It is never retried automatically, because the batches already returned
would be returned again.
SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and
`request_id`. Servers that report a recognized `x-lancedb-error-code` select a
specific input-error subclass. HTTP failures use the corresponding `HttpError`
subclass. Missing metadata stays absent; diagnostic text is never used to guess
the error type. An Internal or Unavailable response remains a server failure,
even if its message or metadata resembles an input error.
For errors that can arrive over either transport, catch the shared input type:
```python
from lancedb.exceptions import ColumnNotFoundError, SchemaMismatchError
from lancedb.remote.errors import HttpError, SqlError
try:
db.execute_query("SELECT missing FROM events").read_all()
except (ColumnNotFoundError, SchemaMismatchError) as error:
print(error.request_id, error.job_id, error.job_request_id)
except (HttpError, SqlError) as error:
print(error.request_id)
```
`ReferenceNotFoundError` identifies a missing branch or table reference. Table
errors are `TableNotFoundError` for HTTP and `SqlTableNotFoundError` for SQL;
both remain compatible with `lance_namespace.errors.TableNotFoundError`.
A background SQL job still raises `JobFailedError`. Its `__cause__` is the typed
`SqlError` when available, and both carry the current `request_id` and original
worker `job_request_id`. The outer job ID can differ from `sql_job_id`. These
fields are `None` when the server does not report them. Older servers produce
generic HTTP/SQL exceptions with their transport status and current request ID.
::: lancedb.remote.errors.HttpError
::: lancedb.remote.errors.ColumnNotFoundError
::: lancedb.remote.errors.ReferenceNotFoundError
::: lancedb.remote.errors.SchemaMismatchError
::: lancedb.remote.errors.SqlError
::: lancedb.remote.errors.SqlColumnNotFoundError
::: lancedb.remote.errors.SqlTableNotFoundError
::: lancedb.remote.errors.SqlReferenceNotFoundError
::: lancedb.remote.errors.SqlSchemaMismatchError
::: lancedb.exceptions.ColumnNotFoundError
::: lancedb.exceptions.ReferenceNotFoundError
::: lancedb.exceptions.SchemaMismatchError
::: lancedb.remote.errors.TableNotFoundError
::: lancedb.remote.errors.SecretNotFoundError
::: lancedb.remote.errors.FunctionNotFoundError
::: lancedb.remote.errors.NamespaceNotFoundError
::: lancedb.remote.errors.AlreadyExistsError
::: lancedb.remote.errors.ConflictError
::: lancedb.remote.errors.ResponseInterruptedError
::: lancedb.exceptions.MissingValueError
::: lancedb.exceptions.MissingColumnError
@@ -721,6 +963,27 @@ so the fetch APIs cannot read their bytes yet.
::: lancedb.streaming.StreamingDataset
When a transform fails for some rows, fill mode replaces each failed row in place:
```python
dataset = StreamingDataset(
table,
num_splits=8,
transform=transform,
on_transform_error="fill",
fill_value={"id": -1, "vector": [0.0, 0.0]},
)
for row in dataset:
train(row)
print(dataset.rows_filled)
```
The placeholder must have the same structure as a successful transform output.
Pass `repair(exc, row_batch) -> row` instead of `fill_value` to construct a
replacement from the failed one-row Arrow batch. Keep the repair deterministic
when using elastic training or checkpoints. Fill mode preserves split lengths
and sample positions.
::: lancedb.streaming.StreamingDataLoader
::: lancedb.permutation.permutation_builder
@@ -808,6 +1071,14 @@ Table hold your actual data as a collection of records / rows.
::: lancedb.materialized_view.AsyncMaterializedView
## Property Graphs (Asynchronous)
`AsyncConnection` returns this handle from
[create_property_graph][lancedb.db.AsyncConnection.create_property_graph] and
[open_property_graph][lancedb.db.AsyncConnection.open_property_graph].
::: lancedb.graph.AsyncPropertyGraph
## Indices (Asynchronous)
Indices can be created on a table to speed up queries. This section
@@ -851,3 +1122,196 @@ rows nearest to a query vector and can be created with the
::: lancedb.query.AsyncTakeQuery
options:
inherited_members: true
## Storage integrations
::: lancedb.storage_integration.StorageIntegrationInfo
::: lancedb.storage_integration.SecretReference
Integrations belong to a database and follow the same namespace-path naming rules
as Secrets, with their own keyspace. Use a regular database under the cluster root for storage configuration needed
before opening an external database. `default` is a convention; no database with
that name is required or created automatically. The system database is read-only.
Client methods execute SQL through the existing SQL transport.
```python
catalog = lancedb.connect_catalog("https://my-server.example", api_key="secret")
db = catalog.connect_database("default")
integration = db.create_storage_integration(
"raw", "s3://customer-bucket/raw/",
aws_role_arn="arn:aws:iam::123456789012:role/lancedb-access",
)
print(integration.configuration_instructions)
integration = db.describe_storage_integration("raw")
for name in db.list_storage_integrations():
print(name)
db.drop_storage_integration("raw")
```
Static credentials use two existing, single-value Secrets instead of a role:
```python
from lancedb.storage_integration import SecretReference
integration = db.create_storage_integration(
"raw", "s3://customer-bucket/raw/",
aws_access_key_id_secret=SecretReference("s3-key-id", database="default"),
aws_secret_access_key_secret=SecretReference("s3-secret-key", database="default"),
)
```
Pass `namespace_path` on the object APIs and Secret references to select a namespace.
A string Secret reference selects the root namespace of the integration's database.
Cross-database references require `USAGE` on the source database, namespace, and
Secret. Role and static-credential modes are mutually exclusive. Credential values
are never included in integration metadata.
`configuration_instructions` is one sentence of display guidance whose wording may
change. Use the structured identity and policy fields for programmatic access.
Registration does not verify AWS access. `AsyncConnection` provides the same methods;
await create, describe, and drop, and use `async for` for listing.
### Azure storage integrations
Create three Secrets containing the Azure tenant ID, client ID and client secret in an ordinary database. Reference their names when registering Azure Blob access:
```python
integration = db.create_storage_integration(
"customer_blobs",
"az://customer-data/raw/",
storage_provider="AZURE",
azure_storage_account="customeraccount",
azure_tenant_id_secret="azure_tenant",
azure_client_id_secret="azure_client",
azure_client_secret_secret="azure_credential",
)
print(integration.configuration_instructions)
```
Use `SecretReference` to qualify another database or namespace. Sync and async connections use the same options. Secret values are never part of integration metadata. Azure supports service principal client credentials; managed identity, account key and SAS authentication are not integration modes.
The equivalent SQL is:
```sql
CREATE STORAGE INTEGRATION customer_blobs
STORAGE_PROVIDER = 'AZURE'
STORAGE_PREFIX = 'az://customer-data/raw/'
STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount'
STORAGE_AZURE_TENANT_ID_SECRET = public.azure_tenant
STORAGE_AZURE_CLIENT_ID_SECRET = public.azure_client
STORAGE_AZURE_CLIENT_SECRET_SECRET = public.azure_credential;
DESCRIBE STORAGE INTEGRATION customer_blobs;
SHOW STORAGE INTEGRATIONS;
DROP STORAGE INTEGRATION customer_blobs;
```
Registration returns setup instructions and leaves `access_verified` false. It stores an account-qualified prefix such as `az://customer-data@customeraccount.blob.core.windows.net/raw/`.
### GCP storage integrations
Create one Secret containing the complete GCP application credentials JSON file
content, then reference its name when registering Google Cloud Storage access:
```python
from pathlib import Path
db.create_secret("gcp_credentials", Path("credentials.json").read_text())
integration = db.create_storage_integration(
"customer_gcs",
"gs://customer-data/raw/",
storage_provider="GCP",
gcp_credentials_json_secret="gcp_credentials",
)
print(integration.configuration_instructions)
```
The equivalent SQL references the existing Secret:
```sql
CREATE STORAGE INTEGRATION customer_gcs
STORAGE_PROVIDER = 'GCP'
STORAGE_PREFIX = 'gs://customer-data/raw/'
GCP_CREDENTIALS_JSON_SECRET = public.gcp_credentials;
DESCRIBE STORAGE INTEGRATION customer_gcs;
SHOW STORAGE INTEGRATIONS;
DROP STORAGE INTEGRATION customer_gcs;
```
`gcp_credentials_json_secret` names a Secret; pass the file content to
`create_secret`, not to `create_storage_integration`. Use `SecretReference` to
qualify another database or namespace. Sync and async connections accept the same
options. The service interprets the stored JSON when accessing storage; registration
does not validate its credentials format or verify access, and leaves
`access_verified` false. Integration metadata contains the Secret reference, never
its JSON content. GCP options cannot be combined with AWS or Azure options.
### Hugging Face storage integrations
Store a Hugging Face token as one Secret, then register the repository prefix
with the existing integration methods. Only the Secret name is part of the
integration configuration:
```python
import os
from lancedb.storage_integration import SecretReference
db.create_secret("hf_token", os.environ["HF_TOKEN"])
info = db.create_storage_integration(
"private_hub",
"hf://datasets/acme/private/raw/",
storage_provider="HUGGINGFACE",
huggingface_token_secret=SecretReference("hf_token"),
)
print(info.configuration_instructions)
info = db.describe_storage_integration("private_hub")
names = list(db.list_storage_integrations())
db.drop_storage_integration("private_hub")
```
The equivalent SQL references the existing Secret:
```sql
CREATE STORAGE INTEGRATION private_hub
STORAGE_PROVIDER = 'HUGGINGFACE'
STORAGE_PREFIX = 'hf://datasets/acme/private/raw/'
HUGGINGFACE_TOKEN_SECRET = public.hf_token;
DESCRIBE STORAGE INTEGRATION private_hub;
SHOW STORAGE INTEGRATIONS;
SELECT * FROM 'hf://datasets/acme/private/raw/*.parquet' LIMIT 10;
DROP STORAGE INTEGRATION private_hub;
```
Omit the token Secret for anonymous access at Hugging Face's default anonymous
rate limits. A tokenless integration does not use a cluster's Hugging Face token:
```python
info = db.create_storage_integration(
"public_hub", "hf://datasets/acme/public/raw/",
storage_provider="HUGGINGFACE",
)
```
```sql
CREATE STORAGE INTEGRATION public_hub
STORAGE_PROVIDER = 'HUGGINGFACE'
STORAGE_PREFIX = 'hf://datasets/acme/public/raw/';
```
When provided, the Secret must contain the token itself, with repository read
permission.
Cross-database and namespace references use the same `SecretReference` rules as
other integrations. Sync and async APIs accept the same options. Registration
returns one sentence of instructions and leaves `access_verified` false; it does
not contact Hugging Face. Metadata contains the Secret reference, never its value.
Hugging Face options cannot be combined with AWS, Azure or GCP options.
Repository prefixes use `hf://datasets/<owner>/<repo>[/<path>]` or
`hf://models/<owner>/<repo>[/<path>]`. An optional `@revision` follows the repository
name; omitting it allows matching reads of any revision. Prefixes must be concrete
paths without wildcards or traversal. This integration does not make Hugging Face
a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a
matching integration automatically, with no integration argument in the query.
+1 -1
View File
@@ -3,6 +3,6 @@
lancedb==0.41.0b10
numpy==2.2.6
pandas==2.3.3
pillow==12.1.1
pillow==13.0.0
pytest==8.4.2
pytest-asyncio==1.2.0
@@ -1,109 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
# --8<-- [start:camelot_schema]
from lancedb.pydantic import LanceModel
from pydantic import ConfigDict
class Stats(LanceModel):
model_config = ConfigDict(strict=True, extra="forbid")
strength: int
courage: int
magic: int
wisdom: int
class Character(LanceModel):
model_config = ConfigDict(strict=True, extra="forbid")
id: int
name: str
role: str
description: str
stats: Stats
image_filename: str
image: bytes
# --8<-- [end:camelot_schema]
# --8<-- [start:camelot_batches]
import json
from collections.abc import Iterator
from pathlib import Path
def validated_batches(
input_path: Path, batch_size: int
) -> Iterator[list[dict]]:
raw_records = json.loads(input_path.read_text())
asset_root = input_path.parent.parent
batch: list[dict] = []
for raw in raw_records:
payload = dict(raw)
image_path = asset_root / payload.pop("img")
payload["image_filename"] = image_path.name
payload["image"] = image_path.read_bytes()
character = Character.model_validate(payload)
batch.append(character.model_dump(mode="python"))
if len(batch) == batch_size:
yield batch
batch = []
if batch:
yield batch
# --8<-- [end:camelot_batches]
# --8<-- [start:camelot_oss_ingestion]
import lancedb
def ingest_oss(
input_path: Path,
uri: str = "data/camelot.lancedb",
table_name: str = "camelot_multimodal",
batch_size: int = 64,
):
db = lancedb.connect(uri)
if table_name in db.list_tables():
raise ValueError(
f"Table {table_name!r} already exists. Choose a fresh table name."
)
table = db.create_table(table_name, schema=Character)
for batch in validated_batches(input_path, batch_size):
table.add(batch)
table.optimize()
return table
if __name__ == "__main__":
ingest_oss(Path("data/camelot.json"))
# --8<-- [end:camelot_oss_ingestion]
def test_camelot_oss_ingestion(tmp_path):
source = Path(
"docs/web/static/assets/tutorials/build-with-ai-agents/camelot/data/camelot.json"
)
table = ingest_oss(
source,
uri=str(tmp_path / "camelot.lancedb"),
table_name="camelot",
)
rows = (
table.search()
.select(["id", "name", "image", "image_filename"])
.limit(8)
.to_list()
)
assert len(rows) == 8
assert all(row["image"] for row in rows)
assert all(row["image_filename"].endswith(".jpg") for row in rows)
+18
View File
@@ -41,6 +41,7 @@ def connect_enterprise_quickstart_config():
api_key=os.environ["LANCEDB_API_KEY"],
region=os.environ.get("LANCEDB_REGION", "us-east-1"),
host_override=os.environ["LANCEDB_HOST_OVERRIDE"], # https://your-endpoint
sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"],
)
# --8<-- [end:connect_enterprise_quickstart]
return db
@@ -60,6 +61,9 @@ def test_connect_enterprise_quickstart(monkeypatch):
monkeypatch.setenv("LANCEDB_API_KEY", "your-api-key")
monkeypatch.delenv("LANCEDB_REGION", raising=False)
monkeypatch.setenv("LANCEDB_HOST_OVERRIDE", "https://your-endpoint")
monkeypatch.setenv(
"LANCEDB_SQL_HOST_OVERRIDE", "grpc+tls://your-sql-endpoint:10026"
)
assert connect_enterprise_quickstart_config() is not None
assert captured == {
@@ -67,6 +71,7 @@ def test_connect_enterprise_quickstart(monkeypatch):
"api_key": "your-api-key",
"region": "us-east-1",
"host_override": "https://your-endpoint",
"sql_host_override": "grpc+tls://your-sql-endpoint:10026",
}
@@ -79,6 +84,16 @@ def test_connect_enterprise_quickstart_requires_an_endpoint(monkeypatch):
connect_enterprise_quickstart_config()
def test_connect_enterprise_quickstart_requires_a_sql_endpoint(monkeypatch):
monkeypatch.setenv("LANCEDB_URI", "db://your-database")
monkeypatch.setenv("LANCEDB_API_KEY", "your-api-key")
monkeypatch.setenv("LANCEDB_HOST_OVERRIDE", "https://your-endpoint")
monkeypatch.delenv("LANCEDB_SQL_HOST_OVERRIDE", raising=False)
with pytest.raises(KeyError, match="LANCEDB_SQL_HOST_OVERRIDE"):
connect_enterprise_quickstart_config()
def connect_object_storage_config():
# --8<-- [start:connect_object_storage]
import lancedb
@@ -169,6 +184,7 @@ def test_namespace_admin_ops(tmp_path, monkeypatch, capsys):
)
assert db.list_namespaces().namespaces == []
async def connect_object_storage_config_async():
# --8<-- [start:connect_object_storage_async]
import lancedb
@@ -199,6 +215,7 @@ def test_connect_enterprise_placeholders(monkeypatch):
api_key="your-api-key",
region="us-east-1",
host_override="https://your-endpoint",
sql_host_override="grpc+tls://your-sql-endpoint:10026",
)
# --8<-- [end:connect_enterprise_placeholders]
assert db is not None
@@ -207,4 +224,5 @@ def test_connect_enterprise_placeholders(monkeypatch):
"api_key": "your-api-key",
"region": "us-east-1",
"host_override": "https://your-endpoint",
"sql_host_override": "grpc+tls://your-sql-endpoint:10026",
}
+1 -1
View File
@@ -3,7 +3,6 @@
def test_sample_dataset():
# --8<-- [start:sample_dataset]
from tempfile import TemporaryDirectory
import lancedb
@@ -11,6 +10,7 @@ def test_sample_dataset():
with TemporaryDirectory(prefix="lancedb-sampling-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:sample_dataset]
table = db.create_table("records", [{"id": i} for i in range(10)])
splits = (
permutation_builder(table).split_random(counts=[3, 7], seed=42).execute()
+6
View File
@@ -25,6 +25,8 @@ def test_create_embedding_function():
@pytest.mark.skip(reason="OpenAI is not available in the test environment")
def test_embeddings_openai():
# --8<-- [start:openai_embeddings]
import lancedb
db = lancedb.connect("/tmp/db")
func = get_registry().get("openai").create(name="text-embedding-ada-002")
@@ -46,6 +48,8 @@ def test_embeddings_openai():
async def test_embeddings_openai_async():
uri = "memory://"
# --8<-- [start:async_openai_embeddings]
import lancedb
db = await lancedb.connect_async(uri)
func = get_registry().get("openai").create(name="text-embedding-ada-002")
@@ -65,6 +69,8 @@ async def test_embeddings_openai_async():
@pytest.mark.skip(reason="OpenAI is not available in the test environment")
def test_embeddings_manual_query():
# --8<-- [start:manual_query_embeddings]
import lancedb
db = lancedb.connect("/tmp/db")
func = get_registry().get("openai").create(name="text-embedding-ada-002")
+38 -13
View File
@@ -6,14 +6,15 @@
Registering a Function and filling its column need a LanceDB Enterprise
deployment, so `test_function_enterprise` runs only when
LANCEDB_DOCS_TEST_DEPLOYMENT=1 asks for one, with the connection variables the
Enterprise examples already use: LANCEDB_URI, LANCEDB_API_KEY and
LANCEDB_HOST_OVERRIDE, plus LANCEDB_REGION if the deployment needs one. The
Enterprise examples already use: LANCEDB_URI, LANCEDB_API_KEY,
LANCEDB_HOST_OVERRIDE and LANCEDB_SQL_HOST_OVERRIDE, plus LANCEDB_REGION if the
deployment needs one. The
walkthrough calls its table `function_demo` and its Function `double`; the test
creates both under names unique to its run, never replaces an existing object,
and drops only what it created.
The other tests run locally and check the client side of the same code: what
`@udf` sends for registration, how a registered version binds a column, where a
`@function` sends for registration, how a registered version binds a column, where a
local connection stops, and when the Enterprise test connects. They do not run
a Function remotely.
"""
@@ -31,18 +32,18 @@ from lancedb import col
from lancedb.functions import FunctionApplication, FunctionVersion
# --8<-- [start:function_define]
from lancedb import udf
from lancedb import function
@udf
@function
def double(value: float) -> float:
return value * 2
# --8<-- [end:function_define]
# The definition the walkthrough registers. The Enterprise test registers a copy
# of it under a name that only its run uses.
# The definitions the walkthrough registers. The Enterprise test registers a
# copy of each under a name that only its run uses.
WALKTHROUGH_DOUBLE = double
@@ -51,7 +52,7 @@ def describe(value: float):
# --8<-- [start:function_class_define]
@udf(pip=["sentence-transformers"])
@function(pip=["sentence-transformers"])
class embed:
def __init__(self, model: str = "all-MiniLM-L6-v2"):
# Runs on the worker, once per instance: only the worker needs the package.
@@ -68,6 +69,8 @@ class embed:
# --8<-- [end:function_class_define]
WALKTHROUGH_EMBED = embed
# A Function version as the service returns it after registration: the SDK's
# shared golden reply, with the name and signature of the definition above.
@@ -91,7 +94,12 @@ def registered_version(definition) -> FunctionVersion:
return FunctionVersion.from_json(json.dumps(reply))
DEPLOYMENT = ("LANCEDB_URI", "LANCEDB_HOST_OVERRIDE", "LANCEDB_API_KEY")
DEPLOYMENT = (
"LANCEDB_URI",
"LANCEDB_HOST_OVERRIDE",
"LANCEDB_SQL_HOST_OVERRIDE",
"LANCEDB_API_KEY",
)
# The connection settings alone never send this test to a deployment.
OPT_IN = "LANCEDB_DOCS_TEST_DEPLOYMENT"
@@ -138,7 +146,7 @@ def test_function_output_nullability():
pa.field("half", pa.float64(), nullable=False),
pa.field("note", pa.string(), nullable=True),
]
struct = udf(input_schema=inputs, output_schema=pa.schema(fields))(describe)
struct = function(input_schema=inputs, output_schema=pa.schema(fields))(describe)
output = struct.registration_request.signature.output
assert output.kind == "named_struct"
assert [(field.name, field.nullable) for field in output.fields] == [
@@ -152,7 +160,7 @@ def test_function_output_nullability():
pa.field("result", pa.struct(fields), nullable=True),
):
with pytest.raises(ValueError, match="non-nullable"):
udf(input_schema=inputs, output_schema=nullable)(describe)
function(input_schema=inputs, output_schema=nullable)(describe)
def test_function_registration_is_remote(tmp_path):
@@ -181,7 +189,10 @@ def test_function_version_binds_a_column(tmp_path):
# The binding is accepted by add_columns, which a local table refuses:
# a Function column needs LanceDB Cloud or Enterprise.
table = lancedb.connect(tmp_path).create_table("t", [{"value": 1.0}])
with pytest.raises(NotImplementedError, match="Cloud and Enterprise"):
with pytest.raises(
NotImplementedError,
match="Function columns are supported only in LanceDB Enterprise",
):
table.add_columns({"doubled": application})
@@ -223,6 +234,7 @@ def test_function_enterprise(monkeypatch):
api_key=os.environ["LANCEDB_API_KEY"],
region=os.environ.get("LANCEDB_REGION", "us-east-1"),
host_override=os.environ["LANCEDB_HOST_OVERRIDE"],
sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"],
)
# --8<-- [end:function_connect]
@@ -230,7 +242,10 @@ def test_function_enterprise(monkeypatch):
# this run creates both under names only it uses, and drops only those.
run = uuid.uuid4().hex[:12]
table_name = f"function_demo_{run}"
double = udf(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__)
double = function(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__)
embed = function(name=f"embed_{run}", pip=["sentence-transformers"])(
WALKTHROUGH_EMBED.__wrapped__
)
create_table = db.create_table
def create_run_table(name, *args, **kwargs):
@@ -241,6 +256,7 @@ def test_function_enterprise(monkeypatch):
table = None
version = None
embedder = None
try:
# --8<-- [start:function_create_table]
import pyarrow as pa
@@ -284,11 +300,18 @@ def test_function_enterprise(monkeypatch):
(2.0, 4.0),
(3.0, 6.0),
]
# --8<-- [start:function_class_register]
embedder = db.create_function_async(embed).wait()
# --8<-- [end:function_class_register]
assert embedder.name == f"embed_{run}"
finally:
if table is not None:
db.drop_table(table_name)
if version is not None:
db.drop_function(version.name, version=version.version)
if embedder is not None:
db.drop_function(embedder.name, version=embedder.version)
class ReachedConnection(Exception):
@@ -298,6 +321,7 @@ class ReachedConnection(Exception):
SETTINGS = {
"LANCEDB_URI": "db://docs-test",
"LANCEDB_HOST_OVERRIDE": "https://deployment.invalid",
"LANCEDB_SQL_HOST_OVERRIDE": "grpc+tls://sql.deployment.invalid:10026",
"LANCEDB_API_KEY": "docs-test-key",
}
@@ -375,5 +399,6 @@ def test_function_enterprise_connects_when_asked(monkeypatch, connect_attempts,
"api_key": "docs-test-key",
"region": region or "us-east-1",
"host_override": "https://deployment.invalid",
"sql_host_override": "grpc+tls://sql.deployment.invalid:10026",
}
]
+50 -10
View File
@@ -177,30 +177,69 @@ def test_vector_index_query_ivf(tmp_db):
def test_vector_index_nprobes(tmp_db):
dim = 128
from lancedb.index import IvfFlat
dim = 16
rng = np.random.default_rng(180)
data = [
{"id": i, "keywords_embeddings": np.random.random(dim).tolist()}
{"id": i, "vector": rng.random(dim).astype(np.float32).tolist()}
for i in range(512)
]
table = tmp_db.create_table("vector_index_nprobes", data, mode="overwrite")
table.create_index(
metric="cosine",
vector_column_name="keywords_embeddings",
"vector",
config=IvfFlat(distance_type="cosine", num_partitions=64, max_iterations=2),
)
query_vector = data[123]["vector"]
# --8<-- [start:vector_index_auto]
# Start with Auto.
auto = table.search(query_vector).limit(10).to_arrow()
# --8<-- [end:vector_index_auto]
# --8<-- [start:vector_index_search_effort]
# Search more partitions to try to improve recall.
higher_effort = table.search(query_vector).search_effort(0.75).limit(10).to_arrow()
# --8<-- [end:vector_index_search_effort]
# --8<-- [start:vector_index_fixed_probes]
# Use a fixed probe count.
fixed = table.search(query_vector).nprobes(20).limit(10).to_arrow()
# --8<-- [end:vector_index_fixed_probes]
# --8<-- [start:vector_index_nprobes]
# Always scan 10 partitions; scan up to 50 only if the initial pass
# returns fewer than `limit` results (common with narrow filters).
(
table.search(np.random.random(128))
# Let Auto choose between 10 and 50 partitions per segment, if available.
filtered = (
table.search(query_vector)
.minimum_nprobes(10)
.maximum_nprobes(50)
.where("id > 100")
.limit(5)
.to_pandas()
.to_arrow()
)
# --8<-- [end:vector_index_nprobes]
for result, expected_count in [
(auto, 10),
(higher_effort, 10),
(fixed, 10),
(filtered, 5),
]:
assert result.num_rows == expected_count
assert result["id"][0].as_py() == 123
assert np.isfinite(result["_distance"].to_numpy()).all()
exact_query = (
table.search(query_vector).distance_type("cosine").bypass_vector_index()
)
if result is filtered:
exact_query = exact_query.where("id > 100")
expected_ids = set(
exact_query.limit(expected_count).to_arrow()["id"].to_pylist()
)
recall = len(set(result["id"].to_pylist()) & expected_ids) / expected_count
assert recall >= 0.5
assert all(row_id > 100 for row_id in filtered["id"].to_pylist())
def test_vector_index_distance_range(tmp_db):
dim = 128
@@ -295,6 +334,7 @@ def test_vector_index_hnsw(tmp_db):
def test_vector_index_binary(tmp_db):
db = tmp_db
table_name = "hamming-index-tbl"
ndim = 256
schema = pa.schema(
@@ -305,7 +345,7 @@ def test_vector_index_binary(tmp_db):
)
# --8<-- [start:vector_index_binary_schema]
table = tmp_db.create_table(table_name, schema=schema, mode="overwrite")
table = db.create_table(table_name, schema=schema, mode="overwrite")
# --8<-- [end:vector_index_binary_schema]
data = []
+38 -43
View File
@@ -3,13 +3,13 @@
def test_create_table_from_dicts():
# --8<-- [start:create_table_from_dicts]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_dicts]
data = [
{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
{"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1},
@@ -24,13 +24,13 @@ def test_create_table_from_dicts():
def test_create_table_conflict_handling():
# --8<-- [start:create_table_conflict_handling]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_conflict_handling]
data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}]
db.create_table("conflict_table", data)
# Idempotent open: reuse the existing table if it exists.
@@ -45,13 +45,13 @@ def test_create_table_conflict_handling():
def test_create_table_custom_schema():
# --8<-- [start:create_table_custom_schema]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_custom_schema]
import pyarrow as pa
custom_schema = pa.schema(
@@ -76,13 +76,13 @@ def test_create_table_custom_schema():
def test_create_table_from_pandas():
# --8<-- [start:create_table_from_pandas]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_pandas]
import pandas as pd
data = pd.DataFrame(
@@ -98,13 +98,13 @@ def test_create_table_from_pandas():
def test_create_table_from_polars():
# --8<-- [start:create_table_from_polars]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_polars]
import polars as pl
data = pl.DataFrame(
@@ -122,13 +122,13 @@ def test_create_table_from_polars():
def test_create_table_from_arrow():
# --8<-- [start:create_table_from_arrow]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_arrow]
import numpy as np
import pyarrow as pa
@@ -158,13 +158,13 @@ def test_create_table_from_arrow():
def test_create_table_from_pydantic():
# --8<-- [start:create_table_from_pydantic]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_pydantic]
from lancedb.pydantic import LanceModel, Vector
class Content(LanceModel):
@@ -186,13 +186,13 @@ def test_create_table_from_pydantic():
def test_create_table_nested_schema():
# --8<-- [start:create_table_nested_schema]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_nested_schema]
from lancedb.pydantic import LanceModel, Vector
from pydantic import BaseModel
@@ -213,13 +213,13 @@ def test_create_table_nested_schema():
def test_create_empty_table():
# --8<-- [start:create_empty_table]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_empty_table]
import pyarrow as pa
schema = pa.schema(
@@ -237,13 +237,13 @@ def test_create_empty_table():
def test_create_empty_table_pydantic():
# --8<-- [start:create_empty_table_pydantic]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_empty_table_pydantic]
from lancedb.pydantic import LanceModel, Vector
class Item(LanceModel):
@@ -261,13 +261,13 @@ def test_create_empty_table_pydantic():
def test_open_existing_table():
# --8<-- [start:open_existing_table]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:open_existing_table]
# Create a table first
data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}]
db.create_table("test_table", data, mode="overwrite")
@@ -284,13 +284,13 @@ def test_open_existing_table():
def test_drop_table():
# --8<-- [start:drop_table]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:drop_table]
# Create a table first
data = [{"vector": [1.1, 1.2], "lat": 45.5}]
db.create_table("my_table", data, mode="overwrite")
@@ -300,40 +300,35 @@ def test_drop_table():
# --8<-- [end:drop_table]
def test_add_from_dataset():
def test_add_from_dataset(tmp_db, tmp_path, monkeypatch):
db = tmp_db
monkeypatch.chdir(tmp_path)
# --8<-- [start:add_from_dataset]
from tempfile import TemporaryDirectory
import pyarrow as pa
import pyarrow.parquet as pq
import lancedb
data_path = "input.parquet"
pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path)
import pyarrow.dataset as ds
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
from pathlib import Path
dataset = ds.dataset(data_path, format="parquet")
table = db.create_table("my_table", schema=dataset.schema, mode="overwrite")
table.add(dataset)
import pyarrow as pa
import pyarrow.parquet as pq
data_path = str(Path(uri) / "input.parquet")
pq.write_table(pa.table({"id": [1, 2], "name": ["Alice", "Bob"]}), data_path)
import pyarrow.dataset as ds
dataset = ds.dataset(data_path, format="parquet")
table = db.create_table("my_table", schema=dataset.schema, mode="overwrite")
table.add(dataset)
print("Rows:", table.count_rows())
# --8<-- [end:add_from_dataset]
assert table.count_rows() == 2
print("Rows:", table.count_rows())
# --8<-- [end:add_from_dataset]
assert table.count_rows() == 2
def test_create_table_from_iterator():
# --8<-- [start:create_table_from_iterator]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:create_table_from_iterator]
import pyarrow as pa
schema = pa.schema(
@@ -367,13 +362,13 @@ def test_create_table_from_iterator():
def test_update_operation():
# --8<-- [start:update_operation]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:update_operation]
import pyarrow as pa
table = db.create_table(
@@ -396,13 +391,13 @@ def test_update_operation():
def test_update_using_sql():
# --8<-- [start:update_using_sql]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:update_using_sql]
import pyarrow as pa
table = db.create_table(
@@ -425,13 +420,13 @@ def test_update_using_sql():
def test_merge_matched_update_only():
# --8<-- [start:merge_matched_update_only]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:merge_matched_update_only]
import pyarrow as pa
table = db.create_table(
@@ -462,13 +457,13 @@ def test_merge_matched_update_only():
def test_insert_if_not_exists():
# --8<-- [start:insert_if_not_exists]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:insert_if_not_exists]
import pyarrow as pa
table = db.create_table(
@@ -499,13 +494,13 @@ def test_insert_if_not_exists():
def test_merge_update_insert():
# --8<-- [start:merge_update_insert]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:merge_update_insert]
import pyarrow as pa
table = db.create_table(
@@ -542,13 +537,13 @@ def test_merge_update_insert():
def test_merge_delete_missing_by_source():
# --8<-- [start:merge_delete_missing_by_source]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:merge_delete_missing_by_source]
import pyarrow as pa
table = db.create_table(
@@ -586,13 +581,13 @@ def test_merge_delete_missing_by_source():
def test_merge_partial_columns():
# --8<-- [start:merge_partial_columns]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:merge_partial_columns]
import pyarrow as pa
table = db.create_table(
@@ -670,13 +665,13 @@ def test_write_workflow():
def test_append_rows():
# --8<-- [start:append_rows]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:append_rows]
table = db.create_table("users", [{"id": 1, "name": "Alice"}])
table.add([{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}])
rows = sorted(table.search().to_list(), key=lambda row: row["id"])
@@ -687,13 +682,13 @@ def test_append_rows():
def test_delete_rows():
# --8<-- [start:delete_rows]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:delete_rows]
table = db.create_table(
"users",
[
@@ -713,7 +708,6 @@ def test_delete_rows():
def test_add_progress():
# --8<-- [start:add_progress]
from tempfile import TemporaryDirectory
import lancedb
@@ -723,6 +717,7 @@ def test_add_progress():
with TemporaryDirectory(prefix="lancedb-ingestion-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:add_progress]
table = db.create_table("users", [{"id": 1, "name": "Alice"}])
table.add(
[{"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}],
+23 -28
View File
@@ -167,46 +167,31 @@ def test_embedding_huggingface_usage() -> None:
def test_frameworks_lerobot_lancedb_usage() -> None:
require_flag("RUN_LEROBOT_LANCEDB_SNIPPETS")
# --8<-- [start:frameworks_lerobot_lancedb_image_dataset]
from lerobot_lancedb import LeRobotLanceDataset
dataset = LeRobotLanceDataset(
repo_id="your-org/your-lerobot-lance-images",
delta_timestamps={
"observation.images.front": [-0.2, -0.1, 0.0],
},
return_uint8=True,
)
# --8<-- [start:frameworks_lerobot_lancedb_dataset]
from lerobot_lancedb import LanceDBDataset, lance_mp_context
from torch.utils.data import DataLoader
dataset = LanceDBDataset(root="hf://datasets/lance-format/pusht-lance")
sample = dataset[0]
print(sample["observation.state"].shape)
print(sample["action"].shape)
# --8<-- [end:frameworks_lerobot_lancedb_image_dataset]
# --8<-- [start:frameworks_lerobot_lancedb_video_dataset]
from lerobot_lancedb import LeRobotLanceVideoDataset
video_dataset = LeRobotLanceVideoDataset(
repo_id="lance-format/lerobot-pusht-lance",
delta_timestamps={
"observation.images.image": [-0.2, -0.1, 0.0],
},
return_uint8=True,
loader = DataLoader(
dataset,
batch_size=32,
num_workers=8,
multiprocessing_context=lance_mp_context(),
)
video_sample = video_dataset[0]
print(video_sample["observation.images.image"].shape)
# --8<-- [end:frameworks_lerobot_lancedb_video_dataset]
# --8<-- [end:frameworks_lerobot_lancedb_dataset]
# --8<-- [start:frameworks_lerobot_open_lance_tables]
import lancedb
db = lancedb.connect("hf://datasets/lance-format/lerobot-pusht-lance/data")
db = lancedb.connect("hf://datasets/lance-format/pusht-lance")
frames = db.open_table("frames")
episodes = db.open_table("episodes")
videos = db.open_table("videos")
print(len(frames), len(episodes), len(videos))
print(len(frames), len(videos))
print(frames.schema)
# --8<-- [end:frameworks_lerobot_open_lance_tables]
@@ -723,7 +708,9 @@ def test_embedding_voyageai_multimodal() -> None:
# Add images using URLs
tbl.add(
[
{"image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png"},
{
"image_uri": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png"
},
]
)
@@ -1359,6 +1346,8 @@ def test_frameworks_pydantic_examples() -> None:
# --8<-- [end:frameworks_pydantic_base_model]
# --8<-- [start:frameworks_pydantic_set_url]
import lancedb
db = lancedb.connect(str(Path(tempfile.mkdtemp()) / "pydantic-docs"))
# --8<-- [end:frameworks_pydantic_set_url]
@@ -1691,6 +1680,8 @@ def test_platforms_pandas_examples() -> None:
# --8<-- [end:platforms_pandas_imports]
# --8<-- [start:platforms_pandas_create_table]
import lancedb
pandas_df = pd.DataFrame(
[
{"id": "1", "text": "dragon", "vector": [0.9, 0.1, 0.3]},
@@ -1713,6 +1704,8 @@ def test_platforms_pandas_examples() -> None:
# --8<-- [end:platforms_pandas_vector_search]
# --8<-- [start:platforms_pandas_async_example]
import lancedb
async def run_pandas_async_example() -> pd.DataFrame:
async_db = await lancedb.connect_async(
str(Path(tempfile.mkdtemp()) / "pandas-async")
@@ -1752,6 +1745,8 @@ def test_platforms_polars_examples() -> None:
# --8<-- [end:platforms_polars_imports]
# --8<-- [start:platforms_polars_create_table]
import lancedb
birds = pl.DataFrame(
{
"text": ["phoenix", "sparrow"],
+178 -62
View File
@@ -45,6 +45,7 @@ class OwnedTables:
self.db = db
self.suffix = uuid.uuid4().hex[:12]
self.claimed = []
self.claimed_namespaces = []
def claim(self, name, existing, mode):
owned = f"{name}_{self.suffix}"
@@ -67,11 +68,42 @@ class OwnedTables:
owned, mode = self.claim(name, self.table_names(), mode)
return self.db.create_table(owned, *args, mode=mode, **kwargs)
def claim_namespace(self):
"""A namespace only this test can see, for SQL text that must show
readers a literal, unqualified table name (so suffixing the name
itself, as `claim` does, isn't an option). The namespace is created
exclusively (no check-then-act): a collision raises instead of
silently sharing someone else's. `drop_claimed` cascades through it,
so individual tables and views inside never need their own claim.
"""
namespace_path = [f"quickstart_{self.suffix}"]
self.db.create_namespace(namespace_path, mode="create")
self.claimed_namespaces.append(namespace_path)
return NamespacedDB(self.db, namespace_path)
def drop_claimed(self):
existing = self.table_names()
for name in self.claimed:
if name in existing:
self.db.drop_table(name)
for namespace_path in self.claimed_namespaces:
self.db.drop_namespace(namespace_path, mode="skip", behavior="cascade")
class NamespacedDB:
"""A `db.create_table` / `db.execute_query` view scoped to one namespace."""
def __init__(self, db, namespace_path):
self.db = db
self.namespace_path = namespace_path
def create_table(self, name, *args, **kwargs):
kwargs.setdefault("namespace_path", self.namespace_path)
return self.db.create_table(name, *args, **kwargs)
def execute_query(self, query, **kwargs):
kwargs.setdefault("default_namespace_path", self.namespace_path)
return self.db.execute_query(query, **kwargs)
class AsyncOwnedTables(OwnedTables):
@@ -193,21 +225,6 @@ def test_quickstart(db):
# --8<-- [end:quickstart_output_pandas]
assert result["frame_id"].to_list() == ["2", "4"]
# --8<-- [start:quickstart_curate_with_metadata]
curated = (
table.search(query_vector)
.where("stats.motion >= 4")
.select(["frame_id", "video_id", "caption", "_distance"])
.limit(2)
.to_polars()
)
print(curated)
# --8<-- [end:quickstart_curate_with_metadata]
assert curated["frame_id"].to_list() == ["2", "4"]
curated = table.search(query_vector).where("stats.motion < 4").limit(2).to_list()
assert [row["frame_id"] for row in curated] == ["1", "3"]
@pytest.mark.asyncio
async def test_quickstart_async_api(async_db):
@@ -234,66 +251,167 @@ async def test_quickstart_async_api(async_db):
query_vector = [0.2, 0.8, 0.4, 0.9]
# Ensure you run `pip install polars` beforehand
async_result = await (
await async_table.search(query_vector)
).select(["frame_id", "video_id", "caption", "_distance"]).limit(2).to_polars()
async_result = (
await (await async_table.search(query_vector))
.select(["frame_id", "video_id", "caption", "_distance"])
.limit(2)
.to_polars()
)
print(async_result)
# --8<-- [end:quickstart_vector_search_1_async]
assert async_result["frame_id"].to_list() == ["2"]
def test_quickstart_derived_feature(db):
def test_quickstart_curate_with_sql(deployment):
# create_frames and the dedupe statement below name tables directly, to
# keep the extracted snippets reading like the quickstart. Run inside a
# namespace only this test can see, so a concurrent run can never
# overwrite this run's 'frames' or drop it out from under this one.
db = deployment.claim_namespace()
table = create_frames(db)
# --8<-- [start:quickstart_add_feature]
# --8<-- [start:quickstart_curate_sample]
sample = db.execute_query(
"SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)"
).read_all()
print(sample.to_pylist())
# --8<-- [end:quickstart_curate_sample]
assert sample.num_rows == 2
# --8<-- [start:quickstart_curate_dedupe_setup]
# Frame 5 is a near-duplicate of frame 2: the gripper is still closing,
# one video frame later, with an almost identical embedding.
table.add(
[
{
"frame_id": "5",
"video_id": "clip-1",
"caption": "the two-finger gripper still closing on the cup",
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
"embedding": [0.2, 0.9, 0.4, 0.89],
}
]
)
from lancedb.index import IvfFlat
table.create_index(
"embedding", config=IvfFlat(num_partitions=1, distance_type="l2")
)
table.wait_for_index(["embedding_idx"])
# --8<-- [end:quickstart_curate_dedupe_setup]
# --8<-- [start:quickstart_curate_dedupe]
db.execute_query("""
CREATE MATERIALIZED VIEW frames_deduped AS
SELECT * FROM dedupe(
'frames',
'embedding',
distance_threshold => 0.03
)
""")
# --8<-- [end:quickstart_curate_dedupe]
# --8<-- [start:quickstart_curate_dedupe_query]
deduped = db.execute_query(
"SELECT frame_id FROM frames_deduped ORDER BY frame_id"
).read_all()
print(deduped.to_pylist())
# --8<-- [end:quickstart_curate_dedupe_query]
assert deduped.column("frame_id").to_pylist() in (
["1", "2", "3", "4"],
["1", "3", "4", "5"],
)
def quality_scores(table):
rows = table.search().select(["frame_id", "video_id", "quality_score"]).to_list()
return {row["frame_id"]: row["quality_score"] for row in rows}
EXPECTED_QUALITY_SCORES = {"1": 3.5, "2": 4.0, "3": 3.0, "4": 3.75}
def flatten_stats(table):
# --8<-- [start:quickstart_flatten_stats]
table.add_columns(
{
"quality_score": "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)"
"motion": "cast(stats.motion as float)",
"sharpness": "cast(stats.sharpness as float)",
"exposure": "cast(stats.exposure as float)",
"framing": "cast(stats.framing as float)",
}
)
# --8<-- [end:quickstart_flatten_stats]
def test_quickstart_derived_feature(db_path_factory):
db = lancedb.connect(db_path_factory("derived_feature"))
table = create_frames(db)
flatten_stats(table)
# --8<-- [start:quickstart_add_feature]
from lancedb import col, udf
@udf
def quality_score(
motion: float, sharpness: float, exposure: float, framing: float
) -> float:
return (motion + sharpness + exposure + framing) / 4.0
version = db.create_function_async(quality_score).wait()
table.add_columns(
{
"quality_score": version(
motion=col("motion"),
sharpness=col("sharpness"),
exposure=col("exposure"),
framing=col("framing"),
)
}
)
table.refresh_column("quality_score")
# --8<-- [end:quickstart_add_feature]
# --8<-- [start:quickstart_query_feature]
features = table.search().select(["frame_id", "video_id", "quality_score"]).to_polars()
features = (
table.search().select(["frame_id", "video_id", "quality_score"]).to_polars()
)
print(features)
# --8<-- [end:quickstart_query_feature]
assert sorted(zip(features["frame_id"], features["quality_score"])) == [
("1", 3.5),
("2", 4.0),
("3", 3.0),
("4", 3.75),
]
assert quality_scores(table) == EXPECTED_QUALITY_SCORES
def caption_lengths(table):
rows = table.search().select(["caption", "caption_length"]).to_list()
return {row["caption"]: row["caption_length"] for row in rows}
def test_quickstart_computed_column(db_path_factory):
table = create_frames(lancedb.connect(db_path_factory("computed")))
# --8<-- [start:quickstart_computed_feature]
table.add_columns(computed={"caption_length": "length(caption)"})
table.refresh_column("caption_length")
# --8<-- [end:quickstart_computed_feature]
lengths = caption_lengths(table)
assert lengths == {text: len(text) for text in lengths}
def test_quickstart_computed_column_on_a_deployment(deployment):
def test_quickstart_derived_feature_on_a_deployment(deployment):
table = create_frames(deployment)
flatten_stats(table)
# --8<-- [start:quickstart_computed_feature_enterprise]
table.add_columns(computed={"caption_length": "length(caption)"})
job = table.refresh_column_async("caption_length")
from lancedb import col, udf
@udf
def quality_score(
motion: float, sharpness: float, exposure: float, framing: float
) -> float:
return (motion + sharpness + exposure + framing) / 4.0
version = deployment.db.create_function_async(quality_score).wait()
table.add_columns(
{
"quality_score": version(
motion=col("motion"),
sharpness=col("sharpness"),
exposure=col("exposure"),
framing=col("framing"),
)
}
)
# --8<-- [start:quickstart_add_feature_enterprise]
job = table.refresh_column_async("quality_score")
job.wait()
# --8<-- [end:quickstart_computed_feature_enterprise]
lengths = caption_lengths(table)
assert len(lengths) == 4
assert lengths == {text: len(text) for text in lengths}
# --8<-- [end:quickstart_add_feature_enterprise]
assert quality_scores(table) == EXPECTED_QUALITY_SCORES
with pytest.raises(Exception):
table.refresh_column("caption_length")
table.refresh_column("quality_score")
def test_quickstart_multimodal(db, tmp_path, monkeypatch):
@@ -327,19 +445,17 @@ def test_quickstart_multimodal(db, tmp_path, monkeypatch):
def test_quickstart_training(db):
table = create_frames(db)
# The real walkthrough reaches this step with motion/sharpness already
# added back in flatten_stats(); add them here too so this test stands
# on its own, without repeating the add_columns call the snippet shows.
flatten_stats(table)
# --8<-- [start:quickstart_training]
import torch
from lancedb.permutation import Permutation
from lancedb.streaming import StreamingDataset
table.add_columns(
{
"motion": "cast(stats.motion as float)",
"sharpness": "cast(stats.sharpness as float)",
}
)
dataset = Permutation.identity(table).select_columns(["motion", "sharpness"])
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)
dataset = StreamingDataset(table, columns=["motion", "sharpness"], shuffle_seed=42)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0)
# --8<-- [end:quickstart_training]
batches = list(dataloader)
assert len(batches) == 1
+16 -17
View File
@@ -2,32 +2,31 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
def test_read_consistency():
def test_read_consistency(tmp_path):
uri = str(tmp_path)
# --8<-- [start:read_consistency]
from datetime import timedelta
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-consistency-") as uri:
writer = lancedb.connect(uri)
table = writer.create_table("documents", [{"id": 1, "text": "first"}])
writer = lancedb.connect(uri)
table = writer.create_table("documents", [{"id": 1, "text": "first"}])
default_reader = lancedb.connect(uri).open_table("documents")
latest_reader = lancedb.connect(
uri, read_consistency_interval=timedelta(0)
).open_table("documents")
default_reader = lancedb.connect(uri).open_table("documents")
latest_reader = lancedb.connect(
uri, read_consistency_interval=timedelta(0)
).open_table("documents")
table.add([{"id": 2, "text": "second"}])
table.add([{"id": 2, "text": "second"}])
default_count = default_reader.count_rows()
latest_count = latest_reader.count_rows()
print(f"Default reader: {default_count} rows") # 1
print(f"Zero-interval reader: {latest_count} rows") # 2
default_count = default_reader.count_rows()
latest_count = latest_reader.count_rows()
print(f"Default reader: {default_count} rows") # 1
print(f"Zero-interval reader: {latest_count} rows") # 2
default_reader.checkout_latest()
refreshed_count = default_reader.count_rows()
print(f"After explicit refresh: {refreshed_count} rows") # 2
default_reader.checkout_latest()
refreshed_count = default_reader.count_rows()
print(f"After explicit refresh: {refreshed_count} rows") # 2
# --8<-- [end:read_consistency]
assert default_count == 1
+12
View File
@@ -60,6 +60,8 @@ class LanceSchema(LanceModel):
def test_vector_search():
# --8<-- [start:exhaustive_search]
import lancedb
uri = "data/sample-lancedb"
db = lancedb.connect(uri)
data = [
@@ -112,6 +114,8 @@ def test_vector_search():
@pytest.mark.asyncio
async def test_vector_search_async():
# --8<-- [start:exhaustive_search_async]
import lancedb
uri = "data/sample-lancedb"
async_db = await lancedb.connect_async(uri)
data = [
@@ -240,6 +244,8 @@ def test_fts_boost_query():
def test_fts_native():
# --8<-- [start:basic_fts]
import lancedb
uri = "data/sample-lancedb"
db = lancedb.connect(uri)
@@ -287,6 +293,8 @@ def test_fts_native():
@pytest.mark.asyncio
async def test_fts_native_async():
# --8<-- [start:basic_fts_async]
import lancedb
uri = "data/sample-lancedb"
async_db = await lancedb.connect_async(uri)
@@ -651,6 +659,8 @@ def test_hybrid_search():
# --8<-- [end:class-Documents]
# --8<-- [start:basic_hybrid_search]
import lancedb
data = [
{"text": "rebel spaceships striking from a hidden base"},
{"text": "have won their first victory against the evil Galactic Empire"},
@@ -700,6 +710,8 @@ async def test_hybrid_search_async():
# --8<-- [end:class-Documents]
# --8<-- [start:basic_hybrid_search_async]
import lancedb
uri = "data/sample-lancedb"
async_db = await lancedb.connect_async(uri)
data = [
+5 -5
View File
@@ -3,13 +3,13 @@
def test_vector_search():
# --8<-- [start:vector_search]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-search-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:vector_search]
table = db.create_table(
"documents",
[
@@ -48,7 +48,6 @@ def test_vector_search():
def test_text_search():
# --8<-- [start:text_search]
from tempfile import TemporaryDirectory
import lancedb
@@ -56,6 +55,7 @@ def test_text_search():
with TemporaryDirectory(prefix="lancedb-search-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:text_search]
table = db.create_table(
"documents",
[
@@ -91,7 +91,6 @@ def test_text_search():
def test_hybrid_search():
# --8<-- [start:hybrid_search]
from tempfile import TemporaryDirectory
import lancedb
@@ -99,6 +98,7 @@ def test_hybrid_search():
with TemporaryDirectory(prefix="lancedb-search-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:hybrid_search]
table = db.create_table(
"documents",
[
@@ -143,13 +143,13 @@ def test_hybrid_search():
def test_filter_search():
# --8<-- [start:filter_search]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-search-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:filter_search]
table = db.create_table(
"documents",
[
@@ -188,13 +188,13 @@ def test_filter_search():
def test_query_plan():
# --8<-- [start:query_plan]
from tempfile import TemporaryDirectory
import lancedb
with TemporaryDirectory(prefix="lancedb-search-") as uri:
db = lancedb.connect(uri)
# --8<-- [start:query_plan]
table = db.create_table(
"documents",
[
+26
View File
@@ -43,18 +43,26 @@ def fake_connect(monkeypatch):
def test_storage_snippets(fake_connect):
# --8<-- [start:storage_connect_s3]
import lancedb
db = lancedb.connect("s3://bucket/path")
# --8<-- [end:storage_connect_s3]
# --8<-- [start:storage_connect_gcs]
import lancedb
db = lancedb.connect("gs://bucket/path")
# --8<-- [end:storage_connect_gcs]
# --8<-- [start:storage_connect_azure]
import lancedb
db = lancedb.connect("az://bucket/path")
# --8<-- [end:storage_connect_azure]
# --8<-- [start:storage_connect_timeout]
import lancedb
db = lancedb.connect(
"s3://bucket/path",
storage_options={"timeout": "60s"},
@@ -70,12 +78,16 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_table_timeout]
# --8<-- [start:storage_s3_ddb]
import lancedb
db = lancedb.connect(
"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table",
)
# --8<-- [end:storage_s3_ddb]
# --8<-- [start:storage_s3_ddb_local]
import lancedb
db = lancedb.connect(
"s3+ddb://bucket/path?ddbTableName=my-dynamodb-table",
storage_options={
@@ -87,6 +99,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_s3_ddb_local]
# --8<-- [start:storage_s3_sse_kms]
import lancedb
db = lancedb.connect(
"s3://bucket/path",
storage_options={
@@ -97,6 +111,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_s3_sse_kms]
# --8<-- [start:storage_azure_sas]
import lancedb
db = lancedb.connect(
"az://my-container/my-database",
storage_options={
@@ -107,6 +123,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_azure_sas]
# --8<-- [start:storage_s3_minio]
import lancedb
db = lancedb.connect(
"s3://bucket/path",
storage_options={
@@ -117,6 +135,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_s3_minio]
# --8<-- [start:storage_s3_express]
import lancedb
db = lancedb.connect(
"s3://my-bucket--use1-az4--x-s3/path",
storage_options={
@@ -127,6 +147,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_s3_express]
# --8<-- [start:storage_gcs_service_account]
import lancedb
db = lancedb.connect(
"gs://my-bucket/my-database",
storage_options={
@@ -136,6 +158,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_gcs_service_account]
# --8<-- [start:storage_azure_account]
import lancedb
db = lancedb.connect(
"az://my-container/my-database",
storage_options={
@@ -146,6 +170,8 @@ def test_storage_snippets(fake_connect):
# --8<-- [end:storage_azure_account]
# --8<-- [start:storage_tigris_connect]
import lancedb
db = lancedb.connect(
"s3://your-bucket/path",
storage_options={
+31 -24
View File
@@ -99,12 +99,12 @@ def test_update_connect_local_snippet(monkeypatch):
def test_table_creation_from_dicts(tmp_db):
# --8<-- [start:create_table_from_dicts]
data = [
{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
{"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1},
]
db = tmp_db
# --8<-- [start:create_table_from_dicts]
db.create_table("test_table", data, mode="overwrite")
tbl = db["test_table"]
tbl.head()
@@ -133,7 +133,6 @@ def test_create_table_conflict_handling(tmp_db):
def test_table_creation_from_pandas(tmp_db):
# --8<-- [start:create_table_from_pandas]
import pandas as pd
data = pd.DataFrame(
@@ -144,13 +143,13 @@ def test_table_creation_from_pandas(tmp_db):
}
)
db = tmp_db
# --8<-- [start:create_table_from_pandas]
db.create_table("my_table_pandas", data, mode="overwrite")
db["my_table_pandas"].head()
# --8<-- [end:create_table_from_pandas]
def test_table_creation_with_custom_schema(tmp_db):
# --8<-- [start:create_table_custom_schema]
import pyarrow as pa
custom_schema = pa.schema(
@@ -166,6 +165,7 @@ def test_table_creation_with_custom_schema(tmp_db):
{"vector": [0.2, 1.8, 0.4, 3.6], "lat": 40.1, "long": -74.1},
]
db = tmp_db
# --8<-- [start:create_table_custom_schema]
tbl = db.create_table(
"my_table_custom_schema", data, schema=custom_schema, mode="overwrite"
)
@@ -173,7 +173,6 @@ def test_table_creation_with_custom_schema(tmp_db):
def test_table_creation_from_polars(tmp_db):
# --8<-- [start:create_table_from_polars]
import polars as pl
data = pl.DataFrame(
@@ -184,12 +183,12 @@ def test_table_creation_from_polars(tmp_db):
}
)
db = tmp_db
# --8<-- [start:create_table_from_polars]
tbl = db.create_table("my_table_pl", data, mode="overwrite")
# --8<-- [end:create_table_from_polars]
def test_table_creation_from_arrow(tmp_db):
# --8<-- [start:create_table_from_arrow]
import numpy as np
import pyarrow as pa
@@ -209,12 +208,12 @@ def test_table_creation_from_arrow(tmp_db):
["vector", "text"],
)
db = tmp_db
# --8<-- [start:create_table_from_arrow]
tbl = db.create_table("f16_tbl", data, schema=schema, mode="overwrite")
# --8<-- [end:create_table_from_arrow]
def test_table_creation_from_pydantic(tmp_db):
# --8<-- [start:create_table_from_pydantic]
from lancedb.pydantic import LanceModel, Vector
class Content(LanceModel):
@@ -229,12 +228,12 @@ def test_table_creation_from_pydantic(tmp_db):
return f"https://www.imdb.com/title/tt{self.imdb_id}"
db = tmp_db
# --8<-- [start:create_table_from_pydantic]
tbl = db.create_table("movielens_small", schema=Content, mode="overwrite")
# --8<-- [end:create_table_from_pydantic]
def test_table_creation_nested_schema(tmp_db):
# --8<-- [start:create_table_nested_schema]
from lancedb.pydantic import LanceModel, Vector
# --8<-- [start:tables_document_model]
@@ -252,6 +251,7 @@ def test_table_creation_nested_schema(tmp_db):
document: Document
db = tmp_db
# --8<-- [start:create_table_nested_schema]
tbl = db.create_table("nested_table", schema=NestedSchema, mode="overwrite")
# --8<-- [end:create_table_nested_schema]
@@ -314,11 +314,11 @@ def test_add_from_dataset(tmp_db, tmp_path):
data_path = str(tmp_path)
# --8<-- [start:add_from_dataset]
import pyarrow.dataset as ds
dataset = ds.dataset(data_path, format="parquet")
db = tmp_db
# --8<-- [start:add_from_dataset]
table = db.create_table("my_table", schema=dataset.schema, mode="overwrite")
table.add(dataset)
# --8<-- [end:add_from_dataset]
@@ -326,7 +326,6 @@ def test_add_from_dataset(tmp_db, tmp_path):
def test_table_creation_from_iterator(tmp_db):
# --8<-- [start:create_table_from_iterator]
import pyarrow as pa
schema = pa.schema(
@@ -352,12 +351,13 @@ def test_table_creation_from_iterator(tmp_db):
)
db = tmp_db
# --8<-- [start:create_table_from_iterator]
db.create_table("batched_table", make_batches(), schema=schema, mode="overwrite")
# --8<-- [end:create_table_from_iterator]
def test_open_existing_table(tmp_db):
# --8<-- [start:open_existing_table]
db = tmp_db
# --8<-- [start:open_existing_table]
# Create a table first
data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7}]
db.create_table("test_table", data, mode="overwrite")
@@ -371,7 +371,6 @@ def test_open_existing_table(tmp_db):
def test_create_empty_table(tmp_db):
# --8<-- [start:create_empty_table]
import pyarrow as pa
schema = pa.schema(
@@ -382,12 +381,12 @@ def test_create_empty_table(tmp_db):
]
)
db = tmp_db
# --8<-- [start:create_empty_table]
tbl = db.create_table("test_empty_table", schema=schema, mode="overwrite")
# --8<-- [end:create_empty_table]
def test_create_empty_table_pydantic(tmp_db):
# --8<-- [start:create_empty_table_pydantic]
from lancedb.pydantic import LanceModel, Vector
class Item(LanceModel):
@@ -396,6 +395,7 @@ def test_create_empty_table_pydantic(tmp_db):
price: float
db = tmp_db
# --8<-- [start:create_empty_table_pydantic]
tbl = db.create_table(
"test_empty_table_new", schema=Item.to_arrow_schema(), mode="overwrite"
)
@@ -403,8 +403,8 @@ def test_create_empty_table_pydantic(tmp_db):
def test_drop_table(tmp_db):
# --8<-- [start:drop_table]
db = tmp_db
# --8<-- [start:drop_table]
# Create a table first
data = [{"vector": [1.1, 1.2], "lat": 45.5}]
db.create_table("my_table", data, mode="overwrite")
@@ -865,6 +865,7 @@ def _setup_schema_add_table(db):
def _setup_schema_alter_table(tmp_db, data=None):
db = tmp_db
# --8<-- [start:schema_alter_setup]
table_name = "schema_evolution_alter_example"
if data is None:
@@ -893,12 +894,13 @@ def _setup_schema_alter_table(tmp_db, data=None):
"vector": pa.list_(pa.float32(), 128),
}
)
table = tmp_db.create_table(table_name, data, schema=schema, mode="overwrite")
table = db.create_table(table_name, data, schema=schema, mode="overwrite")
# --8<-- [end:schema_alter_setup]
return table
def _setup_schema_drop_table(tmp_db, data=None):
db = tmp_db
# --8<-- [start:schema_drop_setup]
if data is None:
data = [
@@ -927,7 +929,7 @@ def _setup_schema_drop_table(tmp_db, data=None):
"vector": np.random.random(128).tolist(),
},
]
table = tmp_db.create_table("schema_evolution_drop_example", data, mode="overwrite")
table = db.create_table("schema_evolution_drop_example", data, mode="overwrite")
# --8<-- [end:schema_drop_setup]
return table
@@ -1061,9 +1063,10 @@ def test_alter_columns_multiple(tmp_db):
def test_alter_columns_with_expression(tmp_db):
db = tmp_db
# --8<-- [start:alter_columns_with_expression]
# For custom transforms, create a new column from a SQL expression.
expression_table = tmp_db.create_table(
expression_table = db.create_table(
"schema_evolution_expression_example",
[{"id": 1, "price_text": "$100"}],
mode="overwrite",
@@ -1111,10 +1114,10 @@ def test_drop_columns_multiple(tmp_db):
def test_alter_vector_column(tmp_db):
# --8<-- [start:alter_vector_column]
vector_dim = 768 # Your embedding dimension
table_name = "vector_alter_example"
db = tmp_db
# --8<-- [start:alter_vector_column]
data = [
{
"id": 1,
@@ -1197,10 +1200,10 @@ def _setup_versioning_table(tmp_db, data=None, table_name="quotes_versioning_exa
def test_versioning_basic_setup(tmp_db):
# --8<-- [start:versioning_basic_setup]
import pyarrow as pa
db = tmp_db
# --8<-- [start:versioning_basic_setup]
table_name = "quotes_versioning_example"
data = [
@@ -1478,11 +1481,12 @@ def test_branches(tmp_db):
# ============================================================================
def test_consistency_strong(tmp_db):
def test_consistency_strong(tmp_path):
uri = str(tmp_path)
# --8<-- [start:consistency_strong]
import lancedb
from datetime import timedelta
uri = str(tmp_db.uri)
writer_db = lancedb.connect(uri)
reader_db = lancedb.connect(uri, read_consistency_interval=timedelta(0))
writer_table = writer_db.create_table(
@@ -1496,11 +1500,12 @@ def test_consistency_strong(tmp_db):
assert rows_after_write == 2
def test_consistency_eventual(tmp_db):
def test_consistency_eventual(tmp_path):
uri = str(tmp_path)
# --8<-- [start:consistency_eventual]
import lancedb
from datetime import timedelta
uri = str(tmp_db.uri)
writer_db = lancedb.connect(uri)
reader_db = lancedb.connect(uri, read_consistency_interval=timedelta(seconds=3600))
writer_table = writer_db.create_table(
@@ -1514,9 +1519,11 @@ def test_consistency_eventual(tmp_db):
assert rows_after_write == 1
def test_consistency_checkout_latest(tmp_db):
def test_consistency_checkout_latest(tmp_path):
uri = str(tmp_path)
# --8<-- [start:consistency_checkout_latest]
uri = str(tmp_db.uri)
import lancedb
writer_db = lancedb.connect(uri)
reader_db = lancedb.connect(uri)
writer_table = writer_db.create_table(
+7 -66
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use lancedb::{connect, table::NewColumnTransform};
use lancedb::connect;
// --8<-- [start:quickstart_define_struct]
use std::sync::Arc;
@@ -54,14 +54,12 @@ fn frames_schema() -> Arc<Schema> {
]))
}
fn frames_to_reader(
schema: Arc<Schema>,
rows: &[Frame],
) -> Box<dyn RecordBatchReader + Send> {
let frame_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str()));
let video_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str()));
let captions =
LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str()));
fn frames_to_reader(schema: Arc<Schema>, rows: &[Frame]) -> Box<dyn RecordBatchReader + Send> {
let frame_ids =
LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str()));
let video_ids =
LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str()));
let captions = LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str()));
let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion));
let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness));
@@ -220,31 +218,6 @@ async fn main() {
assert_eq!(frame_id_col.get(0).unwrap(), "2");
assert_eq!(frame_id_col.get(1).unwrap(), "4");
// --8<-- [start:quickstart_curate_with_metadata]
let curated = table
.query()
.nearest_to(&query_vector)
.unwrap()
.only_if("stats.motion >= 4")
.select(Select::Columns(vec![
"frame_id".to_string(),
"video_id".to_string(),
"caption".to_string(),
"_distance".to_string(),
]))
.limit(2)
.execute()
.await
.unwrap()
.into_polars()
.await
.unwrap();
println!("{curated:?}");
// --8<-- [end:quickstart_curate_with_metadata]
let curated_frame_id_col = curated.column("frame_id").unwrap().str().unwrap();
assert_eq!(curated_frame_id_col.get(0).unwrap(), "2");
assert_eq!(curated_frame_id_col.get(1).unwrap(), "4");
// --8<-- [start:quickstart_output_array]
let result = table
.query()
@@ -268,38 +241,6 @@ async fn main() {
let frame_id_col = result.column("frame_id").unwrap().str().unwrap();
assert_eq!(frame_id_col.get(0).unwrap(), "2");
// --8<-- [start:quickstart_add_feature]
table
.add_columns(
NewColumnTransform::SqlExpressions(vec![(
"quality_score".to_string(),
"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)"
.to_string(),
)]),
None,
)
.await
.unwrap();
// --8<-- [end:quickstart_add_feature]
// --8<-- [start:quickstart_query_feature]
let features = table
.query()
.select(Select::Columns(vec![
"frame_id".to_string(),
"video_id".to_string(),
"quality_score".to_string(),
]))
.execute()
.await
.unwrap()
.into_polars()
.await
.unwrap();
println!("{features:?}");
// --8<-- [end:quickstart_query_feature]
assert_eq!(features.column("quality_score").unwrap().len(), 4);
// What the quickstart's download step leaves in an application's directory.
let app = tempfile::tempdir().unwrap();
std::fs::create_dir(app.path().join("data")).unwrap();
+16 -1
View File
@@ -93,6 +93,12 @@ async function connectObjectStorageExample() {
async function namespaceTableOpsExample() {
// --8<-- [start:namespace_table_ops]
async function collectNames(items: AsyncIterable<string>): Promise<string[]> {
const names: string[] = [];
for await (const name of items) names.push(name);
return names;
}
const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" });
// Create namespace tree: prod/search and prod/recommendations
@@ -124,6 +130,12 @@ async function namespaceTableOpsExample() {
async function namespaceAdminOpsExample() {
// --8<-- [start:namespace_admin_ops]
async function collectNames(items: AsyncIterable<string>): Promise<string[]> {
const names: string[] = [];
for await (const name of items) names.push(name);
return names;
}
const db = await lancedb.connectNamespace("dir", { root: "./local_lancedb" });
const namespace = ["prod", "search"];
@@ -131,7 +143,10 @@ async function namespaceAdminOpsExample() {
await db.createNamespace(["prod", "search"]);
const childNamespaces = await collectNames(db.listNamespaces(["prod"]));
console.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces);
console.log(
`Child namespaces under ${JSON.stringify(namespace)}:`,
childNamespaces,
);
// Child namespaces under ["prod","search"]: [ 'search' ]
const metadata = await db.describeNamespace(["prod", "search"]);
-43
View File
@@ -154,49 +154,6 @@ describe.each(connections)("quickstart (%s)", (connection) => {
console.table(result);
// --8<-- [end:quickstart_vector_search_1]
expect(result.map((row) => row.frame_id)).toEqual(["2", "4"]);
// --8<-- [start:quickstart_curate_with_metadata]
const curated = await table
.search(queryVector)
.where("stats.motion >= 4")
.select(["frame_id", "video_id", "caption", "_distance"])
.limit(2)
.toArray();
console.table(curated);
// --8<-- [end:quickstart_curate_with_metadata]
expect(curated.map((row) => row.frame_id)).toEqual(["2", "4"]);
});
});
test("a derived feature", async () => {
await withDatabase(connection, async (db) => {
const table = await createFrames(db);
// --8<-- [start:quickstart_add_feature]
await table.addColumns([
{
name: "quality_score",
valueSql:
"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)",
},
]);
// --8<-- [end:quickstart_add_feature]
// --8<-- [start:quickstart_query_feature]
const features = await table
.query()
.select(["frame_id", "video_id", "quality_score"])
.toArray();
console.table(features);
// --8<-- [end:quickstart_query_feature]
expect(
features.map((row) => [row.frame_id, row.quality_score]).sort(),
).toEqual([
["1", 3.5],
["2", 4],
["3", 3],
["4", 3.75],
]);
});
});
+8 -22
View File
@@ -1,22 +1,8 @@
# Functions are documented before their release. At release, remove these
# entries, restore the /feature-engineering/functions redirect to
# /management/function, publish the drafts marked "Draft for the Functions
# release", restore `availability` frontmatter (removed while gated, since
# the comparison table on index.mdx links every page that declares one,
# draft or not) to management/function.mdx and sql/ddl/function.mdx -- each
# currently carries a plain `<Badge color="red">Enterprise</Badge>` instead
# -- and re-link curation/chunking.mdx's plain-text `CREATE FUNCTION`/
# `add_columns` mentions to /management/function and /sql/ddl/function#create
# now that those pages have a route. Chunking stays published ahead of
# Functions shipping, so its examples intentionally do not link to either
# gated page -- only an unrouted page would break.
management/function.mdx
sql/ddl/function.mdx
# GRANT/REVOKE currently only covers privileges on Secrets and Functions
# (CREATE SECRET, CREATE FUNCTION, USAGE on a secret or function), which are
# themselves part of the Functions release: see the "Draft for the Functions
# release" block in governance/authorization.mdx#privileges. At release,
# remove this entry, add the page to the navigation in docs.json, and give it
# `availability` frontmatter like the rest of the SQL reference.
sql/ddl/grant.mdx
tools/cli.mdx
# Branching is Beta; not documented until early access. tables/branching.mdx
# stays reachable (out of the nav only): SDK error messages link to it.
# To restore: docs.json Tutorials > Feature Engineering, after tutorials/feature-engineering/materialized-views.
agent-branch-experiments.mdx
# JSON columns are Beta; not documented until early access.
# To restore: docs.json Documentation > SQL Reference > DQL, after sql/dql/vector-distance.
sql/dql/json-functions.mdx
+9 -7
View File
@@ -26,28 +26,30 @@ process-wide current branch.
Install the model packages, then download the `nomic-embed-text` model from Ollama
(or any other model you prefer):
```bash
<CodeGroup>
```bash Bash icon="terminal"
uv add sentence-transformers ollama
ollama pull nomic-embed-text
```
</CodeGroup>
It's always recommended to measure the results of an experiment on a fixed evaluation set.
Here's an example of how you could ask the agent to run both experiments and compare the results:
```text Agent prompt
Use the lancedb plugin and the LanceDB branching documentation to compare two
embedding experiments on the `camelot_multimodal` table.
embedding experiments on the `frames` table from the quickstart.
1. Fork `embed-minilm` from `main`. Build normalized embeddings from
`"{role}. {description}"` with
`sentence-transformers/all-MiniLM-L6-v2` and add them as `vector_minilm`.
`caption` with `sentence-transformers/all-MiniLM-L6-v2` and add them as
`vector_minilm`.
2. Fork `embed-nomic` from `main`. Embed the identical text with Ollama
`nomic-embed-text` and add the results as `vector_nomic`.
3. Process rows in batches and write only through each branch-scoped table
handle. Verify that neither new column appears on `main`.
4. Evaluate both branches with the queries "wise magical advisor",
"treacherous rebel", and "virtuous Grail knight". Report the top three names,
latency, and whether the expected character ranks first.
4. Evaluate both branches with the queries "a gripper closing on an object",
"a robot arm holding steady", and "lowering an object onto a surface".
Report the top match, latency, and whether the expected frame ranks first.
5. Do not modify `main` and do not delete either branch. Recommend a winner
based on the results.
```
+12 -4
View File
@@ -33,11 +33,13 @@ To authenticate to the Enterprise REST API, you need the endpoint for your deplo
2. Export those values in your terminal:
```bash
<CodeGroup>
```bash Bash icon="terminal"
export LANCEDB_API_KEY="<your-api-key>"
export LANCEDB_HOST_OVERRIDE="https://your-enterprise-endpoint.com"
export LANCEDB_DATABASE="your-database-name"
```
</CodeGroup>
`LANCEDB_HOST_OVERRIDE` is the endpoint the SDKs take as `host_override`; the
database name is the part of its `db://` URI after `db://`.
@@ -48,11 +50,13 @@ database name is the part of its `db://` URI after `db://`.
4. Check that you can reach the deployment and list tables:
```bash
<CodeGroup>
```bash Bash icon="terminal"
curl -X GET "$LANCEDB_HOST_OVERRIDE/v1/table/" \
-H "x-api-key: $LANCEDB_API_KEY" \
-H "x-lancedb-database: $LANCEDB_DATABASE"
```
</CodeGroup>
The response lists one page of table names, with a token for the next page when
there are more.
@@ -62,7 +66,8 @@ If your deployment endpoint already includes the database host name, you can omi
5. Create a table to confirm write access. Let's call it `words`. A table is
created from an Arrow IPC stream, which this writes with PyArrow:
```bash
<CodeGroup>
```bash Bash icon="terminal"
python -c "import pyarrow as pa, sys; t = pa.table({'word': ['hello', 'world']}); w = pa.ipc.new_stream(sys.stdout.buffer, t.schema); w.write_table(t); w.close()" > words.arrow
curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \
@@ -71,16 +76,19 @@ curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/create" \
-H "x-lancedb-database: $LANCEDB_DATABASE" \
--data-binary @words.arrow
```
</CodeGroup>
6. Check that the table has been created:
```bash
<CodeGroup>
```bash Bash icon="terminal"
curl -X POST "$LANCEDB_HOST_OVERRIDE/v1/table/words/describe" \
-H "Content-Type: application/json" \
-H "x-api-key: $LANCEDB_API_KEY" \
-H "x-lancedb-database: $LANCEDB_DATABASE" \
-d '{}'
```
</CodeGroup>
That's it. You're connected! Now, you can start adding data and querying it.
You can visit the tutorial section to build your own applications with LanceDB.
+54 -200
View File
@@ -6,12 +6,6 @@ icon: robot
keywords: ["agents", "plugin", "claude code", "codex", "cursor", "copilot"]
---
import {
PyCamelotSchema,
PyCamelotBatches,
PyCamelotOssIngestion,
} from '/snippets/build_with_ai_agents.mdx';
A coding agent writing LanceDB code from memory writes whatever was in its
training data: often an older API, sometimes one that never existed. The
LanceDB agent plugin fixes that by supplying the current reference at the point
@@ -74,219 +68,79 @@ The `npx plugins` installer defaults to the same user-wide scope. Pass
everyone working in it gets the same plugin, or `-t <target>` to install for a
single agent rather than every one it detects:
```bash
<CodeGroup>
```bash Bash icon="terminal"
npx plugins add lancedb/lancedb-agent-plugins --scope project -t cursor
```
</CodeGroup>
Not every agent supports project scope; `npx plugins targets` lists what it
found and what each target supports.
</Accordion>
### Get started with the LanceDB agent plugin {#get-started-with-the-lancedb-agent-plugin}
## Example prompts {#example-prompts}
This tutorial uses the Camelot dataset from the [quickstart](/quickstart), with
a portrait added for each character. Each LanceDB row contains validated
metadata and raw JPEG bytes. Text, images, and any embeddings you add later
remain in the same table.
These prompts show the kind of work the plugin helps an agent get right on
the first try. Adapt the dataset names, columns, and models to your own data.
### 1\. Download the multimodal dataset {#1-download-the-multimodal-dataset}
### Ingest and search robotics data {#example-robotics}
From a new project directory, download the JSON file and portraits:
<CodeGroup>
```text Prompt
Import the HuggingFace dataset `lance-format/koch_pick_place_5_lego-lance`
into LanceDB.
```bash
mkdir -p data/img
Create a Function `extract_frames(video, timestamp)` that extracts each frame
from the videos table and stores the output as JPEG in a Lance blob column.
Use `torchcodec` to decode frames on a GPU, and stream the video through the
blob input instead of loading it into memory. Install dependencies with pip,
not conda.
BASE_URL="https://docs.lancedb.com/static/assets/tutorials/build-with-ai-agents/camelot/data"
curl -fsSL "$BASE_URL/camelot.json" -o data/camelot.json
Create a table `koch_frames` from `extract_frames`, populated from the videos
and frames metadata in the existing tables.
for image in \
arthur.jpg \
guinevere.jpg \
merlin.jpg \
mordred.jpg \
sir_galahad.jpg \
sir_gawain.jpg \
sir_lancelot.jpg \
sir_percival.jpg
do
curl -fsSL "$BASE_URL/img/$image" -o "data/img/$image"
done
Create a Function that uses a vision-language model to caption each frame,
and add its output as a column named `caption` on `koch_frames`. It needs a
GPU.
Create a full-text search index on `koch_frames.caption`.
```
</CodeGroup>
Each JSON record has this shape:
### Deduplicate near-identical images {#example-dedup}
```json
{
"id": 2,
"name": "Merlin",
"role": "Wizard and Advisor",
"description": "A powerful wizard and prophet who mentors Arthur.",
"stats": {
"strength": 2,
"courage": 4,
"magic": 5,
"wisdom": 5
},
"img": "data/img/merlin.jpg"
}
<CodeGroup>
```text Prompt
Import the HuggingFace dataset `lance-format/BDD100K-enriched` into LanceDB.
Create a Function `phash(image)` that computes a perceptual hash with the
`ImageHash` package, and add it as a column named `phash`.
Build a vector index on `phash` using Hamming distance, and pick good index
parameters for this dataset size.
Create a materialized view that clusters images whose `phash` Hamming
distance is less than 1, using `duplicate_pairs`.
Summarize the result: cluster count, cluster size distribution, and the 10
largest clusters with sample image ids.
```
</CodeGroup>
JSON input may have missing fields, unexpected fields, or values of the wrong
type. The LanceDB plugin tells the agent to validate each record with strict
Pydantic models before writing it.
### Ingest a large code dataset {#example-code}
After the agent writes the pipeline, inspect the schema, batching, and write
path rather than assuming it followed the plugin's guidance correctly.
<CodeGroup>
```text Prompt
Import the C, C++, and Python metadata from the HuggingFace dataset
`bigcode/the-stack-v2` into a single table `stack_v2_code`, with an extra
`language` column recording which of the three it is.
### 2\. Prompt your agent to build the pipeline {#2-prompt-your-agent-to-build-the-pipeline}
Add a `content` column and backfill it with each file's source, downloaded
from `s3://softwareheritage/content/{blob_id}` using the `blob_id` already in
the table. Compress `content` with the best codec LanceDB supports for code
text.
Install the Python packages used by the example:
```bash icon="terminal"
uv init
uv add lancedb pyarrow pydantic
Use `bigcode/starcoder2-3b` to add a `perplexity_starcoder2` column, then
build an index on it.
```
If you're using LanceDB Enterprise, ask the agent to ingest into an Enterprise table,
provide the relevant environment variables for connecting to your Enterprise deployment
in a local `.env` file, and point the agent to it.
```text .env
LANCEDB_URI=db://your_project_name
LANCEDB_API_KEY=your_api_key_here
LANCEDB_REGION=us-east-1
LANCEDB_HOST_OVERRIDE=https://your-enterprise-endpoint.com
```
If you're using LanceDB Embedded, no connection settings are required, as it runs as an
embedded retrieval library. A simple prompt like this should work:
```text Agent prompt
# If using LanceDB Embedded
Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB
Embedded table.
# If using enterprise
Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB
Enterprise table using the connection information in `.env`.
```
Because the plugin is registered with the agent's own plugin system, the agent
should pick it up on its own once you restart the session. If it does not,
simply ask it to use the `lancedb` plugin in the prompt, as shown above.
That should be enough! The agent will create `ingest_multimodal.py`, or similar.
The following sections inspect the script to verify that it follows the plugin's guidance.
#### Data validation {#data-validation}
The plugin encourages the agent to validate each record with Pydantic before writing it.
The agent should ideally define a schema for the table and a nested schema for the
`stats` field.
<CodeBlock filename="ingest_multimodal.py" language="Python" icon="python">
{PyCamelotSchema}
</CodeBlock>
In this case, our agent correctly defined `Character` and `Stats` Pydantic models
and validated the JSON before adding it to the table.
#### Batched ingestion {#batched-ingestion}
Naively calling `table.add()` once per row is slow, and is considered an anti-pattern
in LanceDB. The plugin encourages the agent to collect incoming rows into batches and
write them with a single `table.add()` call. When you use the plugin, the agent should
produce something like this:
<CodeBlock filename="ingest_multimodal.py" language="Python" icon="python">
{PyCamelotBatches}
</CodeBlock>
The script calls `Character.model_validate(...)` before adding a record to the
batch. If validation fails, that batch is never written. The function yields up
to `batch_size` rows at a time, providing an iterable of batches for the ingestion step,
shown next.
#### Table maintenance {#table-maintenance}
For LanceDB Embedded, the plugin instructs the agent to call
`table.optimize()` after the ingestion loop. This compacts small fragments, cleans up
old versions according to the retention policy, and incorporates new data into indexes.
<CodeBlock filename="ingest_multimodal.py" language="Python" icon="python">
{PyCamelotOssIngestion}
</CodeBlock>
If you're using LanceDB Enterprise, the plugin mentions that this step is not needed
because LanceDB Enterprise handles maintenance automatically.
<Note>
This example dataset has only eight rows, so the default batch size writes it in
one call. Larger inputs should still avoid single-row write commits.
</Note>
### 3\. Run the Embedded pipeline {#3-run-the-oss-pipeline}
```bash
uv run python ingest_multimodal.py
```
The table now contains the validated character records and their JPEG bytes.
Here are the first three rows:
| Image | Character | Role |
| --- | --- | --- |
| <img src="/static/assets/tutorials/build-with-ai-agents/camelot/data/img/arthur.jpg" alt="King Arthur" width="128" height="128" /> | King Arthur | King of Camelot |
| <img src="/static/assets/tutorials/build-with-ai-agents/camelot/data/img/merlin.jpg" alt="Merlin" width="128" height="128" /> | Merlin | Wizard and Advisor |
| <img src="/static/assets/tutorials/build-with-ai-agents/camelot/data/img/guinevere.jpg" alt="Queen Guinevere" width="128" height="128" /> | Queen Guinevere | Queen of Camelot |
Once your pipeline works, you can [run experiments on branches](/agent-branch-experiments)
to try new embedding models, parsers, or search settings without touching `main`.
### Takeaways {#takeaways}
The example in this tutorial was small, but similar ideas apply to other workflows, too.
Give the agent the data source, the constraints it must respect, and the
artifacts it should return.
The plugin supplies LanceDB-specific guidance, but it's the user's responsibility to
ensure the output makes sense for the application.
### Try the plugin with your own dataset {#try-the-plugin-with-your-own-dataset}
The plugin shown in this tutorial should generalize reasonably well to other use cases.
If you find any issues, open [an issue](https://github.com/lancedb/lancedb-agent-plugins/issues)
on GitHub, clearly describing the intended behavior.
You can choose LanceDB Embedded or LanceDB Enterprise based on how the work will run:
Start with [LanceDB Embedded](/quickstart) during the early stages of a project
when an agent is helping you prototype,
explore a dataset, or run small workflows on a subset of the data. The application owns
the storage and lifecycle work, so ask the agent to validate inputs, write in
batches, and it will include table maintenance operations such as `optimize()`
where appropriate.
Choose [LanceDB Enterprise](/enterprise) when the resulting table becomes
shared production infrastructure, and the workload needs distributed capacity,
private deployment, or platform-managed operations. The data format and the core
table API stay the same, so the pipeline's table and search code carries over:
the agent connects to an Enterprise `db://` table, leaves maintenance to the
deployment instead of calling `optimize()`, and submits long-running work as
[jobs](/basics/jobs).
## What agents are good at here {#workflows}
The walkthrough above is one pattern. The other has its own tutorial.
<Columns cols={2}>
<Card title="Run experiments on branches" icon="flask" href="/agent-branch-experiments">
Isolate agent-driven experiments on a branch, evaluate them on a fixed test
set, and promote only the winner.
</Card>
</Columns>
It is the more interesting pattern. [Branches](/management/table#versioning)
give an agent somewhere to be wrong safely: it can rewrite a schema, recompute a
column, or try three embedding models without touching `main`, and you keep only
what measured better.
</CodeGroup>
+238 -65
View File
@@ -1,9 +1,9 @@
---
title: "LanceDB Catalog"
sidebarTitle: "LanceDB Catalog"
title: "LanceDB Lakehouse"
sidebarTitle: "LanceDB Lakehouse"
description: "LanceDB Lakehouse objects are organized into a catalog of databases, namespaces and tables -- connect to a database to work with them."
icon: sitemap
keywords: ["catalog", "namespace", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"]
keywords: ["catalog", "namespace", "namespace path", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"]
---
import {
@@ -17,39 +17,168 @@ import {
TsConnectEnterprisePlaceholders,
TsConnectObjectStorage,
} from '/snippets/connection.mdx';
import {
PyStorageS3Minio,
PyStorageS3Express,
PyStorageS3SseKms,
TsStorageS3Minio,
TsStorageS3Express,
TsStorageS3SseKms,
} from '/snippets/storage.mdx';
## Catalog overview {#catalog}
## Catalog Hierarchy {#hierarchy}
A catalog keeps track of named data objects, such as tables and views, so
applications can discover and access them. In LanceDB, it organizes those
objects into databases and namespaces -- similar to a catalog in Postgres,
Snowflake, or other database systems.
applications can discover and access them. In LanceDB Enterprise, the
catalog is the top-level entry point: it organizes databases, which in turn
organize namespaces and tables -- similar to a catalog in Postgres,
Snowflake, or other database systems. The catalog itself has no name of its
own -- it's just the root -- and an Enterprise deployment's catalog is
identified by its endpoint, not a name like the objects beneath it.
LanceDB Embedded has no catalog at all. Connect directly to a
[database](#connecting-to-database) instead of going through a catalog.
A database contains namespaces that group related tables and views.
Namespaces can also contain other namespaces, letting teams organize data by
project, environment or purpose.
For example, a search application can keep production and staging data in
separate namespaces within the same database, with `prod` further split into
a nested `search` namespace:
<div className="hidden dark:block">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8",
"primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8",
"edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart TD
catalog["root catalog"] --> database["ai_data · database"]
database --> prod["prod · namespace"]
database --> staging["staging · namespace"]
prod --> search["search · namespace"]
search --> search_docs["documents · table"]
search --> search_view["recent_documents · view"]
search --> search_fn["embed · function"]
staging --> staging_docs["documents · table"]
classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8
```
</div>
<div className="block dark:hidden">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19",
"primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19",
"edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart TD
catalog["root catalog"] --> database["ai_data · database"]
database --> prod["prod · namespace"]
database --> staging["staging · namespace"]
prod --> search["search · namespace"]
search --> search_docs["documents · table"]
search --> search_view["recent_documents · view"]
search --> search_fn["embed · function"]
staging --> staging_docs["documents · table"]
classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19
```
</div>
| Object | What it represents |
| --- | --- |
| [Catalog](/management/catalog) | The unnamed root of an Enterprise deployment, identified by its endpoint; lists, creates and drops databases. Not present in Embedded. |
| [Database](/management/database) | A container for namespaces and their data objects. |
| [Namespace](/management/namespace) | A named group of catalog objects -- tables, views, secrets, functions, storage integrations, or nested namespaces -- addressed by its namespace path. |
| [Table](/management/table) | Data stored as rows and columns. |
| [View](/management/view) | A saved query, evaluated when read. Available in Enterprise. |
| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. |
| [Secret](/management/secret) | A named credential that a Function binds by reference. Available in Enterprise. |
| [Storage integration](/management/storage-integration) | A named credential for reading or importing from storage outside the deployment's own tables, such as an S3 prefix or a HuggingFace repository. Available in Enterprise. |
| [Function](/management/function) | Registered code used to compute column values. Available in Enterprise. |
<span id="namespace-paths"></span>
### Namespace name and path {#namespace-path}
A namespace's **name** is just its own component, such as `search`. Its
**path** is the full sequence of names from the database down to it: in the
diagram above, `search` sits inside `prod`, so its path is the sequence
`prod`, `search`. A namespace path is never written by joining those names
with `.` -- a dot is a valid character inside a name, so a dot-joined path
couldn't always be split back into its components unambiguously. The two
forms below are how SQL actually writes one.
### Schema {#schema}
SQL addresses a namespace path as a **schema**, the ANSI standard's term for
the same concept: a nested path collapses into one identifier, its
components joined by `$` instead of `.`. The path's length changes what the
schema looks like:
| Path | Schema |
| --- | --- |
| `[]` (the database root) | `public` -- the reserved name for the empty path |
| `["prod"]` | `prod` -- one component needs no joining |
| `["prod", "search"]` | `` `prod$search` `` -- joined, and backtick-quoted because `$` isn't a bare-identifier character |
`$` can't appear in an ordinary name, so a schema can always be split back
into its exact path, unlike a dot-joined one. (This "schema" is the
namespace path as a SQL identifier -- distinct from a table's Arrow schema,
its column names and types.)
### Object identifier {#identifier}
An object -- a table, view, function, secret, or storage integration -- is
addressed in SQL by the ANSI three-part identifier `database.schema.name`,
where `schema` is exactly the `$`-joined path above. The `documents` table
in `search`, nested inside `prod`, in database `ai_data`, is
`` ai_data.`prod$search`.documents ``. One directly under the database root
uses `public`: `ai_data.public.documents`.
See [Namespace](/sql/ddl/namespace) for the full `CREATE`/`ALTER`/`DROP`
syntax.
## Connecting {#connecting}
You always run table and query operations within a **database**; cross-database
operations go through SQL instead. The same Python, TypeScript and Rust SDKs
reach a database two ways:
reach a database and the catalog separately.
- **Directly, the common case.** `lancedb.connect(uri)` opens one database in a
single call -- a local directory, an object-storage path, or (with a `db://`
URI) a specific Enterprise database.
- **Through the catalog, for admin and cross-database work.** `connect_catalog(endpoint)`
connects to Enterprise's root catalog, which can list, create and drop
databases across the whole deployment. Its `connect_database(name)` and
`create_database(name)` then return the same kind of database connection
`lancedb.connect()` does. Local filesystem and object-store deployments have
no catalog to connect to -- each is already scoped to one database.
### Connecting to Catalog {#connecting-to-catalog}
The table below shows which URI reaches which kind of database directly.
`connect_catalog(endpoint)` connects to Enterprise's root catalog, which can
list, create and drop databases across the whole deployment. Its
`connect_database(name)` and `create_database(name)` then return the same
kind of database connection `lancedb.connect()` does.
| URI | Where queries run |
| --- | --- |
| A local path, such as `./data` | Embedded: in your process |
| `s3://`, `gs://` or `az://` | Embedded: in your process, reading object storage |
| `db://` | LanceDB Enterprise: queries run on your cluster |
This connection is for database administration, not table or query work:
list, create and drop databases through it, then switch to a **database**
connection for everything else -- tables, queries, and SQL all run within a
database, never directly against the catalog. Local filesystem and
object-store deployments have no catalog to connect to -- each is already
scoped to one database.
### A local directory {#local}
### Connecting to Database {#connecting-to-database}
`lancedb.connect(uri)` opens one database in a single call -- a local
directory, an object-storage path, or (with a `db://` URI) a specific
Enterprise database. The table below shows which URI reaches which kind of
database directly.
| URI | Mode | Where queries run |
| --- | --- | --- |
| A local path, such as `./data` | <Badge color="green">Embedded</Badge> | In your process |
| `s3://`, `gs://` or `az://` | <Badge color="green">Embedded</Badge> | In your process, reading object storage |
| `db://` | <Badge color="red">Enterprise</Badge> | On your cluster |
#### A local directory {#local}
Embedded in your application, LanceDB reads and writes the tables in a
directory on disk.
@@ -75,12 +204,11 @@ directory on disk.
</CodeBlock>
</CodeGroup>
### Object storage {#object-storage}
#### Object storage {#object-storage}
With an object storage URI the library is still embedded: your process runs
every query and reads and writes the bucket directly, with the credentials from
its environment or its storage options. [Configuring storage](/deployment/storage)
covers credentials, endpoints and provider options.
every query and reads and writes the bucket directly, with credentials from
its environment or its connection's `storage_options`.
<CodeGroup>
<CodeBlock filename="Python (sync)" language="Python" icon="python">
@@ -99,7 +227,85 @@ covers credentials, endpoints and provider options.
In Rust, pass the same URI to `connect`.
### LanceDB Enterprise {#enterprise}
LanceDB supports these object storage backends:
| Backend | URI scheme | Credentials |
| --- | --- | --- |
| AWS S3, and S3-compatible stores (MinIO, Tigris, ...) | `s3://` | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, or `storage_options`. Compatible stores also need `endpoint` and `region`. |
| Google Cloud Storage | `gs://` | `GOOGLE_SERVICE_ACCOUNT` (path to a service account JSON), or `storage_options` |
| Azure Blob Storage | `az://` | `AZURE_STORAGE_ACCOUNT_NAME` + `AZURE_STORAGE_ACCOUNT_KEY` (or a SAS token), or `storage_options` |
| Tencent COS | `cos://` | `TENCENTCLOUD_SECRET_ID` / `TENCENTCLOUD_SECRET_KEY`, or `storage_options` |
| GooseFS (a cache layer over COS or S3) | `goosefs://` | Reads from the GooseFS client environment |
Pass credentials as environment variables (uppercase), or as a
`storage_options` dict at connection or table level (lowercase keys); a
table's `storage_options` inherit the connection's and override on a
per-key basis.
Choosing among these is a tradeoff between latency, scalability, cost and
operational complexity, before you even pick a cloud-specific backend:
object storage (S3, GCS, Azure Blob) has the highest latency but is the
cheapest and scales storage effectively without limit; networked file
storage (EFS, Filestore, Azure Files) and third-party stores (MinIO,
WekaFS) sit in between; block storage (EBS, Persistent Disk, Managed Disk)
and local NVMe are the fastest but tie data to one instance, so scaling
means sharding or copying it yourself.
##### S3-compatible stores {#s3-compatible-stores}
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyStorageS3Minio}
</CodeBlock>
<CodeBlock filename="TypeScript" language="TypeScript" icon="square-js">
{TsStorageS3Minio}
</CodeBlock>
</CodeGroup>
If the endpoint is `http://` (common in local development), also set
`ALLOW_HTTP=true` or pass `allow_http=True` in `storage_options`.
##### S3 Express {#s3-express}
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyStorageS3Express}
</CodeBlock>
<CodeBlock filename="TypeScript" language="TypeScript" icon="square-js">
{TsStorageS3Express}
</CodeBlock>
</CodeGroup>
Consult AWS's networking requirements for S3 Express before enabling it.
##### Server-side encryption with KMS {#server-side-encryption-with-kms}
Set `aws_server_side_encryption` to `aws:kms` and `aws_sse_kms_key_id` to
the key ID or ARN to encrypt at rest with an AWS KMS key. The same options
apply at connection or table level, and combine with bucket-level default
encryption.
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyStorageS3SseKms}
</CodeBlock>
<CodeBlock filename="TypeScript" language="TypeScript" icon="square-js">
{TsStorageS3SseKms}
</CodeBlock>
</CodeGroup>
The IAM principal needs `kms:Encrypt`, `kms:Decrypt` and
`kms:GenerateDataKey` on the configured KMS key.
<Note>
**Tencent COS and GooseFS build availability.** Both are bundled by
default in the Python wheel. In the Node binding, GooseFS is bundled by
default but COS is not -- build with the `cos` Cargo feature enabled to
use it there. In Rust, neither is in the default feature set; build with
the `cos` or `goosefs` Cargo feature enabled to use either one.
</Note>
#### LanceDB Enterprise {#enterprise}
A `db://` URI connects directly to one database in LanceDB Enterprise, where
your cluster runs queries and background work. Get the database URI, API key,
@@ -124,40 +330,6 @@ instead of an API key, see
[Authentication](/enterprise/authentication); for every connection option, see
[Database](/management/database#deployment).
## Databases, namespaces and tables {#objects}
A database contains namespaces that group related tables and views. Namespaces
can also contain other namespaces, allowing teams to organize data by project,
environment or purpose.
For example, a search application can keep production and staging data in
separate namespaces within the same database:
```mermaid
flowchart TD
database["ai_data · database"] --> prod["prod · namespace"]
database --> staging["staging · namespace"]
prod --> prod_docs["documents · table"]
staging --> staging_docs["documents · table"]
```
<span id="views" />
| Object | What it represents |
| --- | --- |
| [Database](/management/database) | A container for namespaces and their data objects. |
| [Namespace](/management/namespace) | A named group of tables, views or nested namespaces. |
| [Table](/management/table) | Data stored as rows and columns. |
| [View](/management/view) | A saved query, evaluated when read. Available in Enterprise. |
| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. |
{/*
Draft for the Functions release. Add this row to the table above:
| [Function](/management/function) | Registered code used to compute column values. Available in Enterprise. |
*/}
<span id="resolution" />
## Organization and access control {#governance}
- **Separate projects and environments.** Keep production and staging tables
@@ -167,12 +339,13 @@ Draft for the Functions release. Add this row to the table above:
- **Control access in Enterprise.** Use permissions on databases, namespaces
and tables to manage who can access shared data and what they can do with it.
<span id="elsewhere" />
## Learn more {#next}
- [Catalog](/management/catalog): initial access to a new deployment, and the superuser bootstrap.
- [Databases](/management/database): connect to and manage a database.
- [Namespaces](/management/namespace): create groups and address tables within them.
- [Tables](/management/table): create, inspect and manage your data.
- [Views](/management/view) and [materialized views](/management/materialized-view): work with query-defined data.
- [Secrets](/management/secret): store a credential that a Function can bind by reference.
- [Storage integrations](/management/storage-integration): read or import from storage outside your own tables.
- [Authorization](/governance/authorization): configure Enterprise access permissions.
+175
View File
@@ -0,0 +1,175 @@
---
title: "Embedded vs Enterprise"
sidebarTitle: "Embedded vs Enterprise"
description: "A feature-by-feature comparison between LanceDB Embedded and LanceDB Enterprise."
icon: "scale-balanced"
keywords: ["embedded vs enterprise", "comparison", "oss vs enterprise"]
---
LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage.
[LanceDB Enterprise](/enterprise/index) distributes query execution, indexing, maintenance and refresh work across
a cluster of many machines, outside your application. Both are built on the same [Lance](/basics/lance) columnar
file format, so moving data from one edition to the other does not require a data conversion step. See
[Architecture](/index#architecture) for how each one's components fit together.
## How they differ {#how-they-differ}
| Dimension | LanceDB Embedded | LanceDB Enterprise | What the difference means |
|:----------|:------------|:-------------------|:-------------------------|
| **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. |
| **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. |
| **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). |
| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). |
| **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. |
| **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. |
| **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). |
| **Native vector dedup** | Not available | `dedupe()` / `duplicate_pairs()` | Index-partition deduplication as a SQL table function, with no full pairwise scan. See [DEDUPE](/sql/dql/dedupe). |
| **Materialized views** | Not available | Server-side, distributed compute | Enterprise derives and refreshes a table from a query as a background job. See [Materialized views](/feature-engineering/materialized-views). |
## Compare features {#compare}
| Area | Feature | Embedded | Enterprise |
| --- | --- | :-: | :-: |
| **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ |
| | [RTE Write (Upsert)](/ingestion/realtime-write) | ✅ | ✅ |
| | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ |
| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ |
| | [Import Datasets](/ingestion/import) | ❌ | ✅ |
| | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ |
| **Search** | [Vector search](/search/vector-search) | ✅ | ✅ |
| | [Full-text search](/search/full-text-search) | ✅ | ✅ |
| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ |
| | [Filtering](/search/filtering) | ✅ | ✅ |
| | [Reranking](/reranking) | ✅ | ✅ |
| | [Distributed Search](/enterprise/distributed-search) | ❌ | ✅ |
| | [RTE Read](/search/realtime-read) | ✅ | ✅ |
| | [Distributed RTE Read](/enterprise/distributed-real-time-read) | ❌ | ✅ |
| | [Cache Prewarm](/enterprise/cache-prewarm) | ❌ | ✅ |
| **Data Curation** | [Inspect Datasets](/curation/inspect-datasets) | ❌ | ✅ |
| | [Statistical Sampling](/curation/statistical-sampling) | ❌ | ✅ |
| | [Selective Sampling](/curation/selective-sampling) | ✅ | ✅ |
| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ |
| | [Joins](/curation/join) | ❌ | ✅ |
| | [Blob Late Materialization](/curation/blob-late-materialization) | ❌ | ✅ |
| | [Ranking](/curation/windowing) | ❌ | ✅ |
| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ |
| | [Chunking](/curation/chunking) | ❌ | ✅ |
| | [Changes since a version](/curation/changes) | ❌ | ✅ |
| **Feature Engineering** | [Computed columns](/feature-engineering/add-computed-column) | ❌ | ✅ |
| | [Incremental Refresh](/enterprise/incremental-refresh) | ❌ | ✅ |
| | [Auto Refresh](/enterprise/auto-refresh) | ❌ | ✅ |
| | [Checkpointing](/enterprise/checkpointing) | ❌ | ✅ |
| | [Adaptive Execution](/enterprise/adaptive-execution) | ❌ | ✅ |
| | [Refresh Materialized View](/feature-engineering/refresh-materialized-view) | ❌ | ✅ |
| | [Embedding registry](/embedding) | ✅ | ✅ |
| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ |
| | [Training Cache](/training/training-cache) | ❌ | ✅ |
| | [Permutations](/training/permutation) | ✅ | ✅ |
| | [Distributed training](/training/distributed-training) | ✅ | ✅ |
| | [Observability](/training/observability) | ✅ | ✅ |
| | [Checkpointing](/training/checkpointing) | ✅ | ✅ |
| | [Resuming](/training/resuming) | ✅ | ✅ |
| **Management** | [Catalog](/management/catalog) | ❌ | ✅ |
| | [Database](/management/database) | ✅ | ✅ |
| | [Namespace](/management/namespace) | ✅ | ✅ |
| | [Table](/management/table) | ✅ | ✅ |
| | [View](/management/view) | ❌ | ✅ |
| | [Materialized view](/management/materialized-view) | ❌ | ✅ |
| | [Secret](/management/secret) | ❌ | ✅ |
| | [Function](/management/function) | ❌ | ✅ |
| | [Storage integration](/management/storage-integration) | ❌ | ✅ |
| | [Console](/enterprise/console) | ❌ | ✅ |
| **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) | ❌ | ✅ |
| | [Vector Indexing](/indexing/vector-index) | ✅ | ✅ |
| | [FTS Indexing](/indexing/fts-index) | ✅ | ✅ |
| | [Scalar Indexing](/indexing/scalar-index) | ✅ | ✅ |
| | [Incremental Indexing](/indexing/incremental-indexing) | ✅ | ✅ |
| | [Distributed Indexing](/enterprise/distributed-indexing) | ❌ | ✅ |
| | [GPU Indexing](/indexing/gpu-indexing) | ✅ | ✅ |
| | [Compaction](/maintenance/compaction) | ✅ | ✅ |
| | [RTE Compaction](/enterprise/realtime-engine-compaction) | ❌ | ✅ |
| | [Garbage Collection](/maintenance/cleanup) | ✅ | ✅ |
| | [Distributed Compaction](/enterprise/distributed-compaction) | ❌ | ✅ |
| | [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) | ❌ | ✅ |
| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ |
| | [Authorization](/governance/authorization) | ❌ | ✅ |
| | [Audit Log](/governance/audit-log) | ❌ | ✅ |
| **Deployment** | [Horizontal Scaling](/enterprise/horizontal-scaling) | ❌ | ✅ |
| | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ |
| | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ |
| | [Multicloud](/deployment/multicloud) | ❌ | ✅ |
| | [Slurm](/deployment/slurm) | ❌ | ✅ |
{/*
Draft until branching reaches early access; restore to the Management rows.
| | [Branches](/tables/branching) | ✅ | ✅ |
*/}
## Usage differences between Enterprise and Embedded {#usage-differences-between-enterprise-and-oss}
The [quickstart](/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...`
connections. Once connected to LanceDB, the table API is largely the same: create a table, search,
filter, evolve the schema, and store multimodal records. However, there are some semantic differences
worth understanding when your code is talking to LanceDB Enterprise.
### 1\. Connection model {#1-connection-model}
In LanceDB Enterprise, your app connects via a `db://...` URI and sends requests to the cluster API.
The cluster executes table operations on your behalf. Your code is coupled to a **managed service endpoint**,
whereas LanceDB Embedded is directly coupled to local or object-storage paths.
### 2\. Returned table type {#2-returned-table-type}
Connecting to an Enterprise table via `open_table(...)` returns a `RemoteTable`, unlike LanceDB Embedded,
which returns a `LanceTable`. `RemoteTable` is a catalog-backed table accessed through a server/cluster,
and does not support all the same methods as `LanceTable` (see below).
### 3\. Materialization APIs {#3-materialization-apis}
For Python users working with LanceDB Enterprise, `RemoteTable` does not support table-level
materialization methods like `table.to_arrow()` or `table.to_pandas()`. This protects users from
accidentally materializing tables that are too large to fit in memory.
Instead, materialize results through query/search builders, for example
`table.search(...).limit(...).to_pandas()` for a vector or full-text search, or
`table.search().where(...).limit(...).to_arrow()` for a filtered scan. For quick previews, use
`table.head()`.
### 4\. Maintenance lifecycle {#4-maintenance-lifecycle}
In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to
existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with
async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger
it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and
`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients
reject `optimize()` as not supported.
That means maintenance is managed by platform behavior and cluster configuration, not by explicit
per-table maintenance calls in your application code.
### 5\. Guardrails and limits {#5-guardrails-and-limits}
Enterprise can enforce platform-level guardrails, such as index/table limits and safety checks around
operations like `merge_insert` when too many rows are unindexed. LanceDB Embedded mostly exposes
storage/format-level behavior, and you tune many lifecycle tasks yourself.
This means an operation in LanceDB Enterprise can fail due to service-level policy, not just because
of local table shape or schema mismatch.
<Info>
As a rule of thumb, all you need to remember is this: treat `db://...` as a network service boundary,
use query builders to fetch results, and otherwise interact with your tables as you would in LanceDB
Embedded.
</Info>
## Which one should I use? {#which-one-should-i-use}
[It's very simple to get started with LanceDB Embedded](/quickstart/): Get started with `pip install lancedb` and begin ingesting
your data and vectors into LanceDB. LanceDB Embedded (open source) makes sense when your dataset fits on one machine, traffic is still
modest, and your team is comfortable handling maintenance tasks such as compaction or reindexing itself.
Move to LanceDB Enterprise when retrieval becomes shared infrastructure for your business: your data or traffic has
outgrown a single machine, you need private deployment options, or you want platform support for monitoring, security,
and large-scale feature workflows.
If these sound like your use cases, [reach out to us](https://www.lancedb.com/contact) and we can help you scope your workload and arrange an Enterprise proof of concept.
+2 -2
View File
@@ -85,7 +85,7 @@ cannot undo `drop_table`.
- [Consistency](/tables/consistency): control when reads observe updates.
- [Table versioning](/management/table#versioning): inspect and restore history.
- [Cleanup](/maintenance/cleanup): configure retention and understand protected versions.
- [Jobs](/basics/jobs): distinguish submission, completion and cancellation.
- [Garbage Collection](/maintenance/cleanup): configure retention and understand protected versions.
- [Job Framework](/basics/jobs): distinguish submission, completion and cancellation.
- [Refresh a computed column](/feature-engineering/refresh-column): understand partial progress.
- [Architecture](/index#architecture): understand storage and background maintenance.
+152 -31
View File
@@ -1,11 +1,11 @@
---
title: "Jobs"
sidebarTitle: "Job"
title: "Job Framework"
sidebarTitle: "Job Framework"
description: "Track background work from submission to completion."
icon: hourglass-half
keywords: ["job", "background", "progress", "events", "cancel"]
availability:
embedded: available
embedded: unavailable
enterprise: available
---
@@ -23,13 +23,15 @@ so check its status before
waiting or requesting cancellation. See the operation's API reference for when
the method returns.
```python
<CodeGroup>
```python Python icon="python"
job = tbl.create_index_async("vector", replace=True)
print(job.id)
print(job.job_type)
print(job.status())
```
</CodeGroup>
## Submit and wait for a job {#waiting}
@@ -41,14 +43,22 @@ print(job.status())
results it committed before stopping.
In Python, `job.status()` reports the current state and `job.wait()` waits for
completion, raising if the job fails or is cancelled. If `job.wait()` times out, the client stops waiting.
The timeout does not cancel the server job.
completion, raising if the job fails or is cancelled. Both `Job.wait()` and
`AsyncJob.wait()` retry transient connection and read errors with capped
exponential backoff within the caller's timeout. Without a timeout, retries
continue indefinitely.
```python
If the timeout expires while disconnected, the wait raises `ConnectionError`
with the job ID and instructions to resume waiting. A timeout while connected
raises `TimeoutError`. The job may still be running; timing out does not cancel it.
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
from lancedb.exceptions import JobFailedError, JobCancelledError
job = tbl.create_index_async("vector", replace=True)
job_id = job.id # Save the ID to reopen an Enterprise registry job later.
try:
result = job.wait(timeout=timedelta(minutes=10))
@@ -56,9 +66,23 @@ except JobFailedError:
print(f"job failed: {job.failure}")
except JobCancelledError:
print("job was cancelled")
except ConnectionError as exc:
print(exc) # The job may still be running on the server.
except TimeoutError:
print(f"still running: {job.status()}")
```
</CodeGroup>
After connectivity returns, reopen an Enterprise registry job by its saved ID
and continue waiting on the existing operation:
```python
job = db.open_job(job_id)
result = job.wait(timeout=timedelta(minutes=10))
```
For SQL-backed jobs, call `wait()` again on the original handle. These jobs
cannot be reopened with `db.open_job()`; see [SQL-backed job handles](#sql-backed-job-handles).
<span id="inspecting" />
<span id="events" />
@@ -75,7 +99,8 @@ except TimeoutError:
Reopening a job retrieves the existing operation; it does not restart failed
work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API.
```python
<CodeGroup>
```python Python icon="python"
job = db.open_job(job_id) # raises JobNotFoundError if unknown
job.refresh() # pull the latest status from the server
print(job.status())
@@ -85,23 +110,113 @@ print(events.to_pylist())
job.cancel()
```
</CodeGroup>
List jobs on a connection, paging through the results:
```python
<CodeGroup>
```python Python icon="python"
for info in db.list_jobs(page_limit=50):
print(info.job_id, info.job_type, info.state)
```
</CodeGroup>
Event responses have [row limits](/basics/limits#jobs). An explicit limit can
request more than the default, but it does not guarantee a complete event
history.
## Embedded and Distributed execution {#in-process}
{/*
Draft for the Functions release. Add this section before "Embedded and
Enterprise execution":
### Progress snapshots and observers
Enterprise registry handles expose a structured progress snapshot. This
includes index and refresh handles returned directly by their async submission
methods, as well as handles reopened with `open_job()`. Call `progress()` for a
point-in-time snapshot, or pass a callback to `wait()` to observe the same
server polls that drive completion. The callback receives running and terminal
observations; it does not start another polling loop. It is a synchronous
observer and is not awaited. If it throws, `wait()` logs the error and continues
waiting; callback exceptions do not reject `wait()`.
```python
def show_progress(progress):
print(
progress.get("state"),
progress.get("phase"),
progress.get("rows_computed"),
progress.get("rows_planned"),
)
job = tbl.refresh_column_async("embedding")
snapshot = job.progress()
if snapshot is not None:
show_progress(snapshot)
result = job.wait(progress=show_progress)
```
```typescript
const showProgress = (progress: lancedb.JobProgress) => {
console.log(
progress.state,
progress.phase,
progress.rows_computed,
progress.rows_planned,
);
};
const job = await tbl.refreshColumnAsync("embedding");
const snapshot = await job.progress();
if (snapshot !== null) {
showProgress(snapshot);
}
await job.wait(showProgress);
```
```rust
let job = table.refresh_column_async("embedding").await?;
if let Some(progress) = job.progress().await? {
println!(
"state={:?} rows={:?}/{:?}",
progress.get("state"),
progress.get("rows_computed"),
progress.get("rows_planned"),
);
}
let result = job
.wait_with_progress(|description| {
let progress = description.progress_snapshot();
println!(
"state={:?} rows={:?}/{:?}",
progress.get("state"),
progress.get("rows_computed"),
progress.get("rows_planned"),
);
})
.await?;
```
Job-type-specific counters are optional. A missing `rows_computed`,
`rows_planned`, or `rows_remaining` field means the server did not report that
counter; it does not mean zero, complete, or failed. Embedded handles and
SQL-backed query handles do not have registry progress records. Use their
`status()` and `wait()` APIs, and use registry progress only on handles backed
by the jobs API.
`estimated_remaining_time_millis` is a best-effort client-side estimate. It is
omitted while a job is initializing, queued, or paused, and when there is no
positive progress rate from two compatible samples.
*/}
## Embedded and Enterprise execution {#in-process}
The following table describes LanceDB Embedded operations and registry jobs on
LanceDB Distributed (provided by LanceDB Enterprise).
SQL-backed job handles follow the query lifecycle described below.
LanceDB Enterprise. SQL-backed job handles follow the query lifecycle
described below.
| | Embedded | Enterprise registry job |
| --- | --- | --- |
@@ -112,31 +227,37 @@ SQL-backed job handles follow the query lifecycle described below.
### SQL-backed job handles
On Enterprise, materialized-view CREATE, REFRESH, and DROP use the SQL query backend.
Python's `create_materialized_view_async()`, `mv.refresh_async()`, and
`drop_materialized_view_async()` return job handles with `status()`, `wait()`,
and `cancel()`. Synchronous creation, refresh, and drop wait on the same SQL
execution before returning. A completed DROP means the catalog binding has been
removed; physical cleanup continues in the background.
On Enterprise, several catalog operations return a job handle backed by the
SQL query engine rather than the job registry:
The existing `job.job_type` identifies query-backed handles as `"query"` from
submission, and `job.id` contains the connection-scoped SQL query UUID string.
Use `describe_query(job.id)` on the submitting connection to inspect the query.
Registry handles retain their server-reported job types (available after
`status()` or `refresh()`) and registry IDs. Local handles have no ID or job type.
| Operation | SDK methods | Behavior |
| --- | --- | --- |
| Materialized views | `create_materialized_view_async()`, `refresh_async()`, `drop_materialized_view_async()` | Synchronous variants wait on the same SQL execution. Drop removes the catalog binding immediately; physical cleanup continues in the background. |
| Functions | Registration, `drop_function_async()` | Registration waits for catalog publication before returning the immutable FunctionVersion. Drop confirms catalog removal while cleanup continues separately. |
| Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. |
| Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. |
SQL-backed handles do not expose registry records or event history and cannot
be reopened through `open_job()` or reattached after a client restart. Their IDs
are not durable resume tokens. Cancellation follows the SQL server's
capabilities and can be unsupported.
All of these report `job.job_type` as `"query"`, with `job.id` holding the
connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect
one. Unlike registry handles, they don't expose event history, can't be
reopened through `open_job()` or reattached after a client restart, and
cancellation depends on the SQL server's support for it.
The server decides whether SQL executes on its serving fleet or starts SQL job
workers. That placement does not change the handle's query-backed identity.
### Object teardown {#teardown}
The "physical cleanup continues in the background" behavior above, for a
dropped table, view, materialized view, Secret or Function, is a job type of
its own: `drop_object` deletes the dropped object's content, then clears it
from the database's cleanup backlog. You trigger it indirectly, by dropping
one of those objects or a [namespace](/management/namespace) -- it runs as
this job rather than inline with the call. Whether a dropped table runs as
`drop_object` or as [`drop_table`](/management/table#drop), which fences the
table's directory with its own marker instead, depends on how the deployment
stores its catalog.
## Learn more {#next}
- [Build and repair indexes](/indexing/reindexing): submit index work.
- [Incremental Indexing](/indexing/incremental-indexing): submit index work.
- [Refresh a computed column](/feature-engineering/refresh-column): populate derived values.
- [Background jobs](/maintenance/background-jobs): understand Enterprise maintenance.
- [SQL job commands](/sql/ddl/job): list jobs and inspect errors.
- [SDKs](/basics/sdk): find the job API for your client.
+33
View File
@@ -34,12 +34,45 @@ those fields together.
- **Independent column updates.** Add embeddings or other derived features
without rewriting the existing image, video or text columns.
## Opening Lance datasets in Python {#python-packages}
Any `.lance` dataset directory is a LanceDB table. Pass the parent directory to
`lancedb.connect()` and open the table by its directory stem:
```python
import lancedb
db = lancedb.connect("/data") # pass storage_options=... for S3, GCS or Azure
tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a version
```
Use `lancedb` for search, retrieval, data curation, multimodal blob access and
application code. Install `pylance` (`import lance`) only when building query
engines or connectors, calling format-level fragment APIs directly, or
converting plain-scan lazy or legacy blob columns with `to_pandas()` (see
[Multimodal data and blobs](/management/table#multimodal) for `pylance`-free
conversions).
| `pylance` (`import lance`) | `lancedb` (`import lancedb`) |
| --- | --- |
| `lance.dataset("/data/frames.lance")` | `lancedb.connect("/data").open_table("frames")` |
| `lance.write_dataset(data, "/data/frames.lance")` | `lancedb.connect("/data").create_table("frames", data)` |
| `lance.vector.vec_to_table(mat)` | `db.create_table(name, pa.table({"vector": list(mat)}))` |
| `lance.blob_field("video")` | `lancedb.blob("video")` |
| `ds.take_blobs("video", ids=row_ids)` | `tbl.fetch_blob_files("video", row_ids)` (seekable handles) or `tbl.fetch_blobs("video", row_ids)` (`pa.LargeBinaryArray`) |
| `ds.to_table(columns=cols, filter=expr, limit=n)` | `tbl.search().where(expr).select(cols).limit(n).to_arrow()` |
| `ds.to_batches(batch_size=k)` | `tbl.search().to_batches(k)` |
| `ds.take(offsets)` | `tbl.__getitems__(offsets)` (preserves offset order) or `tbl.take_offsets(offsets).to_arrow()` (unordered) |
| `ds.versions()`, `ds.checkout_version(v)`, `ds.restore()` | `tbl.list_versions()`, `tbl.checkout(v)`, `tbl.restore()` |
| `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(compaction_options=..., cleanup_older_than=...)` |
## Learn more {#next}
<span id="versioning" />
<span id="evolution" />
- [Lance format specification](https://lance.org/format): how the format works.
- [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand.
- [Table versioning](/management/table#versioning): read and manage table versions.
- [Computed columns](/feature-engineering/add-computed-column): add derived features to your data.
- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance.
+46
View File
@@ -0,0 +1,46 @@
---
title: "LanceDB Embedded"
sidebarTitle: "LanceDB Embedded"
description: "The open-source, embedded retrieval library that runs inside your application process."
icon: cube
keywords: ["embedded", "open source", "oss", "local", "sdk", "lancedb embedded"]
---
**LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and
Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database
server to deploy. It reads and writes tables on local disk or in object storage from inside your application
process, on the same [Lance](/basics/lance) format and table model that [LanceDB Enterprise](/enterprise/index)
builds on.
<Frame caption="LanceDB Embedded: the LanceDB SDK and the Lance format run in your application, reading and writing tables on local disk or in object storage.">
<img src="/static/assets/images/overview/lancedb-embedded.png" alt="LanceDB Embedded architecture" width="440" />
</Frame>
## Why use LanceDB Embedded? {#why-use-lancedb-embedded}
LanceDB Embedded fits local retrieval applications, notebooks, development, and single-node data pipelines, where
your application controls its own compute resources and [table maintenance](/maintenance/compaction).
- **No infrastructure to run** -- the library runs inside your process. There is no server to deploy, configure,
or keep available.
- **Free and open source** -- `pip install lancedb` (or the TypeScript or Rust equivalent) and start reading and
writing tables, with no account or service to set up first.
- **Full local control** -- your application decides where table data lives, when maintenance such as compaction
and indexing runs, and how much compute each operation gets.
- **The same table format as Enterprise** -- Embedded and [Enterprise](/enterprise/index) share the same Lance
format and table model, so moving to a distributed deployment later does not require a data conversion step.
## Get started {#get-started}
<CardGroup cols={2}>
<Card title="Quickstart" icon="rocket" href="/quickstart">
Create a table, add data, and run your first search in a few lines of code.
</Card>
<Card title="Choose an SDK" icon="code-compare" href="/basics/sdk">
Pick between the Python, TypeScript, and Rust SDKs.
</Card>
</CardGroup>
When your data or traffic outgrows a single machine, or you need managed infrastructure, private deployment, or
platform support, see [LanceDB Enterprise](/enterprise/index) and the
[feature-by-feature comparison](/basics/embedded-vs-enterprise).
+1 -1
View File
@@ -65,7 +65,7 @@ before creating one over it.
## Learn more {#next}
- [Naming Rules](/basics/naming): choose portable names and paths.
- [Jobs](/basics/jobs): track work and inspect events.
- [Job Framework](/basics/jobs): track work and inspect events.
- [Full-text indexes](/indexing/fts-index): configure tokenization.
- [SQL](/basics/sql) and [SDKs](/basics/sdk): check interface support.
- [Enterprise support](/deployment/support): discuss deployment capacity.
+13 -10
View File
@@ -10,7 +10,7 @@ keywords: ["names", "naming", "table name", "namespace", "identifier", "limits"]
<span id="objects" />
Databases, namespaces, tables, views and branches all have names. Choose names
Databases, namespaces, tables and views all have names.{/* Draft until branching reaches early access: restore "Databases, namespaces, tables, views and branches all have names." */} Choose names
that describe their purpose, such as `documents`, `prod` or `training_2026`.
Consistent names make data easier to find and application code easier to read.
@@ -21,21 +21,20 @@ Use the following rules for names that work across LanceDB Embedded and LanceDB
| Table, materialized view, view | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters |
| Namespace component | ASCII letters and digits, `-`, `_`, `.` | 1 to 64 characters; at most 10 components in a path |
| Database | ASCII letters and digits, `-`, `_`, `.`, with `/` between components | 1 to 64 characters for the whole name |
| Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters |
| Function | ASCII letters and digits, `_` | 1 to 128 characters |
{/*
Draft until branching reaches early access; restore after the Database row.
| Branch | Avoid `$` and `:`; use ASCII letters, digits, `-` and `_` for portability | Keep to 1 to 64 characters |
*/}
- Names and individual namespace or database components must not be empty.
- Table, view, namespace and database components cannot be `.` or `..`.
- Secret names cannot be `.` or `..`.
- Avoid `$` and `:` because they separate parts of qualified identifiers.
- A namespace path beginning with `public` cannot contain another component.
{/*
Draft for the Functions release. Add these rows to the end of the table above:
| Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters |
| Function | ASCII letters and digits, `_` | 1 to 128 characters |
Add this item to the list above, after the rule for `.` and `..`:
- Secret names cannot be `.` or `..`.
*/}
## Namespace paths {#paths}
A namespace path is a list of names. `["prod", "search"]` identifies the
@@ -65,5 +64,9 @@ The empty path `[]` identifies the root namespace.
## Learn more {#next}
- [Namespaces](/management/namespace): create namespaces and address tables.
- [Branches](/tables/branching): name and manage separate lines of table history.
- [Limits](/basics/limits): check other constraints before designing your schema.
{/*
Draft until branching reaches early access; restore after Namespaces.
- [Branches](/tables/branching): name and manage separate lines of table history.
*/}
+13 -16
View File
@@ -3,15 +3,15 @@ title: "SDKs"
sidebarTitle: "SDKs"
description: "Choose a LanceDB SDK and find the API reference for your language."
icon: code-compare
keywords: ["python", "typescript", "rust", "java", "sdk", "rest", "api reference"]
keywords: ["python", "typescript", "rust", "java", "sdk", "api reference"]
---
Use a LanceDB SDK to create tables, add data, build indexes and run searches
from your application. Python, TypeScript and Rust work with both LanceDB
Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's
process; your data can live on local disk or in object storage. LanceDB
Enterprise runs LanceDB Distributed: query execution, indexing and maintenance
run on the Enterprise service, outside your application.
Enterprise distributes query execution, indexing, maintenance and refresh
work across the service, outside your application.
The [quickstart](/quickstart) includes installation instructions and complete
examples in all three languages. For connection settings, see
@@ -36,16 +36,13 @@ provide a SQL execution method.
## Lance Namespace SDKs {#lance-namespace-sdks}
LanceDB Enterprise's catalog and table operations follow
[Lance Namespace](https://lance.org/format/namespace), an open specification
for describing access to tables in a multimodal lakehouse, including its REST
Namespace Spec. LanceDB Enterprise exposes this as an HTTP API for catalog and
table operations -- the [REST API reference](/api-reference/rest) describes
its endpoints and request formats. Use it when integrating a language or tool
without a LanceDB SDK; for SQL queries, connect through
[Flight SQL](/basics/sql) instead. Any client that implements a Lance
Namespace REST client can integrate with LanceDB this way, not only the
official SDKs above.
LanceDB Enterprise's catalog and table operations follow the
[Lance Namespace Client SDK Specification](https://lance.org/format/namespace),
an open specification for describing access to tables in a multimodal
lakehouse. Any client that implements it can integrate with LanceDB this
way, not only the official SDKs above -- useful for a language or tool
without a LanceDB SDK. For SQL queries, connect through
[Flight SQL](/basics/sql) instead.
| Language | Package | Used by |
| --- | --- | --- |
@@ -55,13 +52,13 @@ official SDKs above.
LanceDB's Java client builds on this Lance Namespace Java core: table creation,
listing and most other catalog operations go through the generated
`LanceNamespace` interface talking to Enterprise's REST Namespace endpoint.
`LanceNamespace` interface talking to Enterprise's Namespace endpoint.
The [real time engine](/tables/realtime-engine) is the one area with its own,
LanceDB-specific Java client on top, since RTE's LSM write path is not part of
the Lance Namespace specification.
the Lance Namespace Client SDK Specification.
See [lance.org/format/namespace](https://lance.org/format/namespace) for the
full spec and its other catalog implementations (Directory, Apache Polaris,
full specification and its other catalog implementations (Directory, Apache Polaris,
Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more).
## Community SDKs {#community-sdks}
+639 -52
View File
@@ -3,33 +3,85 @@ title: "SQL"
sidebarTitle: "SQL"
description: "Query LanceDB Enterprise with SQL from Python or an Arrow Flight SQL client."
icon: table-list
keywords: ["sql", "flight sql", "datafusion", "reference", "dialect"]
keywords: ["sql", "flight sql", "datafusion", "reference", "dialect", "query plan", "explain"]
---
import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx';
import { RsExampleBody as RsQueryPlanBody, RsExampleTail as RsQueryPlanTail } from '/snippets/search_query_plan.mdx';
Use SQL in LanceDB Enterprise to filter records, join tables, calculate
aggregates, and prepare datasets. SQL queries work with the same Lance tables
you create and update through the SDKs, without exporting the data to another
system.
This guide covers the two ways to run SQL, connection settings, a first query,
This guide starts with when to reach for SQL instead of SDK table operations,
then covers the three ways to run SQL, connection settings, a first query,
parameterized queries, and how to read and manage the results.
## Choose SQL or SDK table operations {#choosing}
An SDK gives you a programming-language-specific API for invoking LanceDB's
functionality: create a table, insert rows, build an index, run a vector
search, each its own method call. Every one of those functionalities also
has a corresponding SQL operation. SQL covers a wider surface than any one
SDK method and lets you chain operations together in a single statement --
running a vector search and then joining the results with another table,
for example -- where SDK methods stay separate calls.
Use **SQL** for joins, aggregations, window functions, analytical queries,
and whenever you want to chain operations together. Use **SDK table
operations** to build applications around table management, ingestion,
filtering, and search, including applications that run with LanceDB
Embedded, where SQL is not available.
You can combine them. For example, create and populate a table with an SDK,
then query it with SQL to prepare a training dataset. In Python, both
workflows can use the same Enterprise connection.
Both interfaces work with the same Lance tables, through the same Arrow
schema. Applications in different languages can work with the same tables:
connect to the same database and namespace, use the appropriate credentials,
and account for [read consistency](/tables/consistency) when another process
writes data. A fixed-size vector column stores vectors of a consistent
dimension; see the [data types reference](/sql/data-types) for the supported
element types and other column types.
### Common SQL operations {#sdk-parity}
Several tasks are available through both interfaces, but the methods and SQL
statements do not have identical coverage. SDK support also differs by
language. These SQL reference pages describe the supported statements:
| Task | SQL reference |
| --- | --- |
| Create a table | [CREATE TABLE](/sql/ddl/table) |
| Insert or change rows | [INSERT](/sql/dml/insert), [UPDATE](/sql/dml/update), [DELETE](/sql/dml/delete) |
| Build an index | [CREATE INDEX](/sql/ddl/index) |
| Join and aggregate data | [SELECT](/sql/dql/select) |
| Save a query as a view | [CREATE VIEW](/sql/ddl/view) |
[Computed columns](/feature-engineering/add-computed-column) store SQL
expressions whose values are populated by a refresh. They are separate
from registered Python Functions. See the computed-column and
[materialized-view](/management/materialized-view) guides for their SDK and SQL
operations and Enterprise setup requirements.
## Access LanceDB with SQL {#access}
There are two ways to run SQL against LanceDB Enterprise, both against the
There are three ways to run SQL against LanceDB Enterprise, all against the
same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html)
endpoint, returning results as Arrow record batches:
1. **`db.execute_query()`** on the Python SDK's Enterprise connection, shown
below. This is LanceDB's native SQL execution method, and we recommend it
below, or **`Connection::execute_query_async()`** on the Rust SDK's. These
are LanceDB's native SQL execution methods, and we recommend them
for the best performance -- see [Adaptive query execution](#adaptive).
2. **An Arrow Flight SQL client.** Use this from TypeScript and other
languages, whose LanceDB SDKs do not expose a SQL execution method, or from
any tool with its own Flight SQL integration. A LanceDB-specific SDK is not
required to submit SQL.
From the command line, use `lancedb` to open the [SQL shell](/tools/cli)
or execute a statement or file.
2. **An Arrow Flight SQL client.** Use this from TypeScript, whose LanceDB SDK
does not expose a SQL execution method, or from any tool with its own
Flight SQL integration. A LanceDB-specific SDK is not required to submit
SQL.
3. **The LanceDB CLI.** Open an interactive SQL shell, or run a
statement or file, directly from the command line with no code at all.
The [SQL reference](/sql#connecting) shows a query from Python. See
[SDKs](/basics/sdk) for the LanceDB language clients.
@@ -78,8 +130,6 @@ This example reads an existing `frames` table, with a `video_id` and a
<CodeGroup>
```python Python icon="python"
import lancedb
db = lancedb.connect(
"db://your-database",
api_key="your-api-key",
@@ -109,7 +159,8 @@ separately, use `execute_query_async()`.
Pass a `parameters` argument to bind values into a query, instead of
formatting them into the SQL string:
```python
<CodeGroup>
```python Python icon="python"
import numpy as np
reader = db.execute_query(
@@ -117,6 +168,7 @@ reader = db.execute_query(
parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10],
)
```
</CodeGroup>
Values travel as Arrow, not interpolated SQL text, so a vector binds as a
fixed-size list with no manual formatting and no injection risk. Reference a
@@ -132,12 +184,47 @@ binding:
<Note>
`parameters` is a LanceDB-specific mechanism, separate from the Flight SQL
protocol's `PREPARE`/bind step, which
[a deployment does not implement](/sql/prepared-statements#parameters). Bind
values with `parameters` from the Python SDK; a generic Flight SQL client has
no equivalent.
protocol's `PREPARE`/bind step, which a deployment does not implement; see
[Prepared statements](#prepared-statements) below. Bind values with
`parameters` from the Python SDK; a generic Flight SQL client has no
equivalent.
</Note>
## Prepared statements {#prepared-statements}
A Flight SQL client can prepare a statement before it runs it. A deployment
accepts that, but it keeps no plan between runs and does not accept the
parameter values described above at this protocol layer.
<Warning>
There is no SQL `PREPARE` / `EXECUTE` here. Preparation is part of the
**Arrow Flight SQL protocol**, so you reach it through your client rather than
by sending a statement. A script containing `PREPARE name AS SELECT ...` will
not run.
</Warning>
A Flight SQL client takes these steps, whatever it calls them:
1. **Prepare:** send the SQL and get back a handle and the result schema. The
statement is parsed and planned at this point, so a syntax or name error
surfaces here rather than at execution.
2. **Execute:** run the handle and read the result. The deployment plans the
statement again each time it runs, so reusing a handle does not save
planning time.
3. **Close:** release the handle.
A client that binds values to placeholders such as `$1` and `$2` at this
protocol layer gets a "not implemented" error when it executes the
statement. Use `parameters` [above](#parameters) instead; do not put
untrusted input directly into prepared statement text, since quoting it does
not protect the statement the way binding a parameter would.
Prepare a statement when your client requires it, or to get a statement's
result schema and catch syntax and name errors without running it. Preparing
does not make a repeated statement faster. To give a reusable query a name,
create a [view](/management/view). To store its result for later queries,
create a [materialized view](/management/materialized-view).
## Read and manage results {#results}
- **Collect the results** when you want a list, Arrow table or DataFrame that
@@ -160,45 +247,545 @@ cancellation. Background operations such as index builds return a
[job](/basics/jobs) handle instead. Use the API for the returned handle to
check status and retrieve results.
## Choose SQL or SDK table operations {#choosing}
## Query plans {#query-plans}
Use **SQL** for joins, aggregations, window functions, and analytical queries
written in SQL. Use **SDK table operations** to build applications around table
management, ingestion, filtering, and search, including applications that run
with LanceDB Embedded.
Use query plans to understand how LanceDB reads data, applies filters and uses
indexes. `explain_plan()` shows the planned operations. `analyze_plan()` runs
the query and adds measurements, including execution time and rows processed.
You can combine them. For example, create and populate a table with an SDK,
then query it with SQL to prepare a training dataset. In Python, both workflows
can use the same Enterprise connection.
### Inspect a plan or measure execution {#inspect-a-query-plan}
Both interfaces work with the same Lance tables, through the same Arrow
schema. Applications in different languages can work with the same tables:
connect to the same database and namespace, use the appropriate credentials,
and account for [read consistency](/tables/consistency) when another process
writes data. A fixed-size vector column stores vectors of a consistent
dimension; see the [data types reference](/sql/data-types) for the supported
element types and other column types.
| Operation | Python / Rust | TypeScript |
|:----------|:--------------|:-----------|
| Inspect the plan without executing the query | `explain_plan()` | `explainPlan()` |
| Execute the query and report runtime measurements | `analyze_plan()` | `analyzePlan()` |
### Common SQL operations {#sdk-parity}
Use the first to inspect query structure and the second to investigate work
actually performed. Operator names and available measurements can differ
between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain).
Several tasks are available through both interfaces, but the methods and SQL
statements do not have identical coverage. SDK support also differs by
language. These SQL reference pages describe the supported statements:
<span id="try-both-methods-on-a-local-table"></span>
| Task | SQL reference |
| --- | --- |
| Create a table | [CREATE TABLE](/sql/ddl/table) |
| Insert or change rows | [INSERT](/sql/dml/insert), [UPDATE](/sql/dml/update), [DELETE](/sql/dml/delete) |
| Build an index | [CREATE INDEX](/sql/ddl/index) |
| Join and aggregate data | [SELECT](/sql/dql/select) |
| Save a query as a view | [CREATE VIEW](/sql/ddl/view) |
<Accordion title="Explain and analyze a query in Python, TypeScript or Rust">
[Computed columns](/feature-engineering/add-computed-column) store SQL
expressions whose values are populated by a refresh. {/* Draft for the Functions release:
They are separate from registered Python Functions. */}
See the computed-column and
[materialized-view](/management/materialized-view) guides for their SDK and SQL
operations and Enterprise setup requirements.
These examples use three sample records and hand-written vectors, so no
embedding service is needed. Each program creates a temporary local table
and removes it when finished.
- **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`.
- **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later.
- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory.
<CodeGroup>
<CodeBlock filename="Python" language="python" icon="python">
{PyQueryPlan}
</CodeBlock>
<CodeBlock filename="TypeScript" language="typescript" icon="square-js">
{TsQueryPlanBody + "\n" + TsQueryPlanTail}
</CodeBlock>
<CodeBlock filename="Rust" language="rust" icon="rust">
{RsQueryPlanBody + "\n" + RsQueryPlanTail}
</CodeBlock>
</CodeGroup>
This tiny table demonstrates the API, not a performance benchmark. The plan
uses a scan because the example has no vector index. The following larger
example illustrates how to read scans, filters and index operations.
</Accordion>
### Read scans, filters and result retrieval {#reading-the-execution-plan}
The recorded example below uses 1.2 million rows sampled from the
[Wikipedia dataset](https://huggingface.co/datasets/wikimedia/wikipedia).
The counts describe that run. The table initially has no indexes, so the plan
shows a scan. This Enterprise plan includes `RemoteTake` and hides storage paths
as `uri=***`. A local plan shows the dataset path instead, and fetches the result
rows with Lance's `Take` or, depending on the library version, a second
`LanceRead` whose `source` is `stream(_rowid)`.
Let's examine a vector search query that:
- Filters rows where `identifier` is between 0 and 1,000,000
- Returns the top 100 matches
- Projects specific columns: `chunk_index`, `title`, and `identifier`
<CodeGroup>
```python Python icon="python"
# explain_plan
query_explain_plan = (
table.search(query_embed)
.where("identifier > 0 AND identifier < 1000000")
.select(["chunk_index", "title", "identifier"])
.limit(100)
.explain_plan(True)
)
```
```typescript TypeScript icon="square-js"
// explain_plan
const explainPlan = await table
.search(queryEmbed)
.where("identifier > 0 AND identifier < 1000000")
.select(["chunk_index", "title", "identifier"])
.limit(100)
.explainPlan(true);
```
</CodeGroup>
#### Execution Plan Components {#execution-plan-components}
<Accordion title="Read the recorded vector plan operator by operator">
The execution plan reveals the sequence of operations performed to execute your query. Let's examine each component:
```
ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance]
RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title"
CoalesceBatchesExec: target_batch_size=1024
GlobalLimitExec: skip=0, fetch=100
FilterExec: _distance@3 IS NOT NULL
SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
FilterExec: identifier@1 > 0 AND identifier@1 < 1000000
LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false
```
##### 1\. Base Layer (LanceScan) {#1-base-layer-lancescan}
- Initial data scan loading only specified columns to minimize I/O
- Unordered scan enabling parallel processing
```
LanceScan:
- projection=[vector, identifier]
- row_id=true, row_addr=false, ordered=false
```
##### 2\. First Filter {#2-first-filter}
- Apply requested filter on `identifier` column
- Reduces the number of vectors that need KNN computation
```
FilterExec: identifier@1 > 0 AND identifier@1 < 1000000
```
##### 3\. Vector Search {#3-vector-search}
- Computes squared L2 distances between query vector and all vectors that passed the filter
```
KNNVectorDistance: metric=l2
```
##### 4\. Results Processing {#4-results-processing}
- Filters out null distance results
- Sorts by distance and takes top 100 results
- Coalesces output into batches targeting 1,024 rows in this plan
```
SortExec: TopK(fetch=100)
- expr=[_distance@3 ASC NULLS LAST]
- preserve_partitioning=[false]
FilterExec: _distance@3 IS NOT NULL
GlobalLimitExec: skip=0, fetch=100
CoalesceBatchesExec: target_batch_size=1024
```
##### 5\. Data Retrieval {#5-data-retrieval}
- `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version
- Handles efficient data retrieval from remote storage locations
- Fetches specific rows and columns needed for the final output
- Optimizes network bandwidth by only retrieving required data
```
RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title"
```
##### 6\. Final Output {#6-final-output}
- Returns only requested columns and maintains column ordering
```text
ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance]
```
This plan demonstrates a basic search without index optimizations: it performs a full scan and filter before vector search.
</Accordion>
### Non-vector queries {#analyzing-non-vector-queries}
Query plans also cover filters and full-text search. Python can show both
sub-plans of a hybrid query. Check where a filter runs and how many rows flow
through each operator; a separate `FilterExec` does not by itself establish
that the plan is inefficient or that an index is missing.
#### FTS queries {#fts-queries}
<CodeGroup>
```python Python icon="python"
plan = (
table.search("puppy", query_type="fts")
.where("category = 'animals'", prefilter=True)
.limit(10)
.explain_plan(True)
)
print(plan)
```
```typescript TypeScript icon="square-js"
const plan = await table
.query()
.fullTextSearch("puppy")
.where("category = 'animals'")
.limit(10)
.explainPlan(true);
```
</CodeGroup>
Look for the text-index operation and any scan of unindexed rows. A scan can
be needed to include records written after the index was built. Use index
coverage and execution measurements to determine whether that extra work
matters. Check filter placement separately from text-index use.
#### Hybrid queries {#hybrid-queries}
For hybrid queries, `explain_plan` returns the reranker label followed by the vector and FTS sub-plans, indented for readability:
<CodeGroup>
```python Python icon="python"
plan = (
table.search("flower moon", query_type="hybrid")
.where("category = 'film'", prefilter=True)
.limit(10)
.explain_plan(True)
)
print(plan)
# RRFReranker(...)
# <vector sub-plan>
# <FTS sub-plan>
```
</CodeGroup>
`analyze_plan` executes both sub-queries and labels them `Vector Search Plan:`
and `FTS Search Plan:`. Compare their filter placement and execution measurements.
`analyze_plan` executes the query and returns the physical plan annotated with
runtime metrics such as elapsed time, rows produced, bytes read and index comparisons.
Where [`explain_plan`](#inspect-a-query-plan) tells you what a query intends to do,
analysis shows the work performed.
<Note>
The SQL equivalent is [`EXPLAIN ANALYZE`](/sql/dql/explain).
</Note>
### Read execution measurements {#analyze-a-query-plan}
Executes the query and provides detailed runtime metrics, including:
- Operation duration (`_elapsed_compute_`)
- Data processing statistics (`_output_rows_`, `_bytes_read_`)
- Index effectiveness (`_index_comparisons_`, `_indices_loaded_`)
- Resource utilization (`_iops_`, `_requests_`)
### Measure the example query {#performance-analysis}
Let's use `analyze_plan` to run the query and analyze the query performance, which will help us identify potential bottlenecks:
<CodeGroup>
```python Python icon="python"
# analyze_plan
query_analyze_plan = (
table.search(query_embed)
.where("identifier > 0 AND identifier < 1000000")
.select(["chunk_index", "title", "identifier"])
.limit(100)
.analyze_plan()
)
```
```typescript TypeScript icon="square-js"
// analyze_plan
const analyzePlan = await table
.search(queryEmbed)
.where("identifier > 0 AND identifier < 1000000")
.select(["chunk_index", "title", "identifier"])
.limit(100)
.analyzePlan();
```
</CodeGroup>
#### Performance Metrics Analysis {#performance-metrics-analysis}
<Accordion title="Inspect the recorded execution measurements">
```
ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier@1 as identifier, _distance@3 as _distance], metrics=[output_rows=100, elapsed_compute=1.424µs]
RemoteTake: columns="vector, identifier, _rowid, _distance, chunk_index, title", metrics=[output_rows=100, elapsed_compute=175.53097ms, output_batches=1, remote_takes=100]
CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=100, elapsed_compute=2.748µs]
GlobalLimitExec: skip=0, fetch=100, metrics=[output_rows=100, elapsed_compute=1.819µs]
FilterExec: _distance@3 IS NOT NULL, metrics=[output_rows=100, elapsed_compute=10.275µs]
SortExec: TopK(fetch=100), expr=[_distance@3 ASC NULLS LAST], preserve_partitioning=[false], metrics=[output_rows=100, elapsed_compute=39.259451ms, row_replacements=546]
KNNVectorDistance: metric=l2, metrics=[output_rows=1099508, elapsed_compute=56.783526ms, output_batches=1076]
FilterExec: identifier@1 > 0 AND identifier@1 < 1000000, metrics=[output_rows=1099508, elapsed_compute=17.136819ms]
LanceScan: uri=***, projection=[vector, identifier], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1200000, elapsed_compute=21.348178ms, bytes_read=1852931072, iops=78, requests=78]
```
##### 1\. Data Loading (LanceScan) {#1-data-loading-lancescan}
- Scanned 1,200,000 rows from the LanceDB table
- Read 1.86GB of data in 78 I/O operations
- Only loaded necessary columns (`vector` and `identifier`)
- Unordered scan for parallel processing
##### 2\. Filtering and Search {#2-filtering-and-search}
- Applied prefilter condition (`identifier > 0 AND identifier < 1000000`)
- Reduced dataset from 1.2M to 1,099,508 rows
- KNN search used L2 (Euclidean) distance metric
- Vector comparisons processed in 1076 batches
##### 3\. Results Processing {#3-results-processing}
- KNN results sorted by distance (TopK with fetch=100)
- Null distances filtered out
- Batches coalesced to target size of 1024 rows
- Additional columns fetched for final results
- Remote take operation for 100 results
- Final projection of required columns
</Accordion>
#### Distributed metrics on LanceDB Enterprise {#distributed-metrics-on-remote-tables}
<Badge color="red">Enterprise</Badge>
When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers:
| Mode | What it shows | When to use it |
| :------------ | :----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- |
| `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. |
| `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. |
| `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. |
Python exposes this option through `distributed_metrics`. In TypeScript, pass
the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python
queries on LanceDB Embedded ignore the distributed mode and return single-node
measurements.
<CodeGroup>
```python Python icon="python"
# Show a per-worker breakdown for a query on LanceDB Enterprise
plan = (
table.search(query_embed)
.where("identifier > 0 AND identifier < 1000000")
.limit(100)
.analyze_plan(distributed_metrics="per_worker")
)
print(plan)
```
</CodeGroup>
<Note>
Use `per_worker` or `full` sparingly; the plan output grows with the size of your worker pool. Stick with the default `aggregate` mode for routine tuning.
</Note>
#### Identify expensive operations {#key-observations}
- The query computes distances for 1,099,508 vectors; inspect timings to assess its contribution to latency
- The scan reads 1.86 GB in this recorded run
- Full table scan due to lack of indices
- Compare this scan with an indexed plan using the same query
### Compare the query after adding indexes {#optimized-query-execution}
<Accordion title="Compare the recorded indexed and unindexed plans">
The recorded query after adding vector and scalar indexes produced this plan:
```
ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance]
RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title"
CoalesceBatchesExec: target_batch_size=1024
GlobalLimitExec: skip=0, fetch=100
SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false]
ANNSubIndex: name=vector_idx, k=100, deltas=1
ANNIvfPartition: uuid=83916fd5-fc45-4977-bad9-1f0737539bb9, nprobes=20, deltas=1
ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000)
```
#### Optimized Plan Analysis {#optimized-plan-analysis}
##### 1\. Scalar Index Query {#1-scalar-index-query}
```
ScalarIndexQuery: query=AND(identifier > 0,identifier < 1000000)
metrics=[
output_rows=2
index_comparisons=2,301,824
indices_loaded=2
output_batches=1
parts_loaded=562
elapsed_compute=86.979354ms
]
```
- Range filter using scalar index
- Only 2 index files and 562 scalar index parts loaded
- 2.3M index comparisons for matches
##### 2\. Vector Search {#2-vector-search}
```
ANNSubIndex: name=vector_idx, k=100, deltas=1
metrics=[
output_rows=2,000
index_comparisons=25,893
indices_loaded=0
output_batches=20
parts_loaded=20
elapsed_compute=111.849043ms
]
```
- IVF index with 20 probes
- Only 20 index parts loaded
- 25,893 vector comparisons
- 2,000 matching vectors
##### 3\. Results Processing {#3-results-processing-2}
```
SortExec: TopK(fetch=100), expr=[_distance@0 ASC NULLS LAST], preserve_partitioning=[false]
GlobalLimitExec: skip=0, fetch=100
CoalesceBatchesExec: target_batch_size=1024
```
- Sorts by distance
- Limits to top 100 results
- Batches into groups of 1024
##### 4\. Data Fetching {#4-data-fetching}
```
RemoteTake: columns="_distance, _rowid, identifier, chunk_index, title"
metrics=[output_rows=100, elapsed_compute=113.491859ms, output_batches=1, remote_takes=100]
```
- Single output batch
- One remote take per row
##### 5\. Final Projection {#5-final-projection}
```
ProjectionExec: expr=[chunk_index@3 as chunk_index, title@4 as title, identifier@2 as identifier, _distance@0 as _distance]
```
- Returns specified columns: chunk_index, title, identifier, and distance
#### Performance Improvements {#performance-improvements}
##### 1\. Initial Data Access {#1-initial-data-access}
```
ScalarIndexQuery metrics:
- indices_loaded=2
- parts_loaded=562
- output_batches=1
```
- Before: Full table scan of 1.2M rows, 1.86GB data
- After: Only 2 indices and 562 scalar index parts loaded
- Benefit: Eliminated table scans for prefilter
##### 2\. Vector Search Efficiency {#2-vector-search-efficiency}
```
ANNSubIndex:
- index_comparisons=25,893
- indices_loaded=0
- parts_loaded=20
- output_batches=20
```
- Before: L2 calculations on 1,099,508 vectors
- After:
- About 97.6% fewer vector comparisons (25,893 versus 1,099,508)
- Decreased output batches from 1,076 to 20
##### 3\. Data Retrieval Optimization {#3-data-retrieval-optimization}
```
RemoteTake:
- remote_takes=100
- output_batches=1
```
- RemoteTake operation remains consistent
</Accordion>
### Choose a change to measure {#performance-optimization-guide}
#### 1\. Index Implementation {#1-index-implementation}
##### When to Create Indices {#when-to-create-indices}
- Columns used in WHERE clauses
- Vector columns for similarity searches
- Join columns used in `merge_insert`
##### Index Type Selection {#index-type-selection}
| Data Type | Recommended Index | Use Case |
| ----------- | ------------------ | ---------------------------------------- |
| Vector | IVF_PQ/IVF_HNSW_SQ/IVF_HNSW_FLAT | Approximate nearest neighbor search |
| Scalar | B-Tree | Equality and range filters |
| Categorical | Bitmap | Multi-value filters and set operations |
| `List` | Label_list | Multi-label classification and filtering |
<Card title="Index Coverage Monitoring" icon="lightbulb">
Use `table.index_stats()` to monitor index coverage.
Unindexed rows can add scan work. Use their count alongside query measurements
to decide when index maintenance is needed.
</Card>
#### 2\. Query Plan Optimization {#2-query-plan-optimization}
##### Common Patterns and Fixes {#common-patterns-and-fixes}
| Plan Pattern | Optimization |
| ------------------------------------------ | --------------------------------------------- |
| Scan with high bytes read or I/O count | Check index coverage and whether the query can use an index |
| | Use `select()` to limit returned columns |
| | Check whether the dataset has been compacted |
| Multiple filters | Check their placement and row counts; compare the plan after changing the query |
<Note>
Regularly analyze your query plans to identify and address performance
bottlenecks. The `analyze_plan` output provides detailed metrics to guide
optimization efforts.
</Note>
#### 3\. Getting Started with Optimization {#3-getting-started-with-optimization}
Keep the query, data and result limit fixed while changing one factor. Compare
rows processed, bytes read, timings and returned results. For ANN changes,
measure recall too: doing less work is useful only if retrieval quality meets
your application's needs. See [vector indexes](/indexing/vector-index) and
[scalar indexes](/indexing/scalar-index) for index choices.
## Vector and full-text search {#no-vector-sql}
@@ -212,8 +799,8 @@ The [SDK vector search API](/search/vector-search) is also available in
LanceDB Enterprise and LanceDB Embedded. Use it when you prefer the SDK query builder or need to
search embedded tables.
For full-text search in SQL, use the [`fts()`](/sql/functions#fts) table
function or the [`contains_tokens`](/sql/scalar-functions#contains-tokens)
For full-text search in SQL, use the [`fts()`](/sql/dql/fts) table
function or the [`contains_tokens`](/sql/dql/contains-tokens)
predicate.
## SQL syntax and API references {#reference}
+48 -8
View File
@@ -27,7 +27,8 @@ a record; `doc_id` identifies the document it describes.
Run each statement separately in a scratch database or namespace. Create these
tables once for the whole section, using fresh names if they already exist.
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_documents (
row_id BIGINT, doc_id BIGINT, version BIGINT,
source VARCHAR, caption VARCHAR, score DOUBLE
@@ -44,6 +45,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR);
INSERT INTO curation_labels VALUES
(10, 'cat'), (20, 'dog'), (30, 'cat');
```
</CodeGroup>
`score` is a sample quality score, not a search result score. Document 10 has
two versions. Document 30 has two records at the same version. Document 40
@@ -56,13 +58,15 @@ has no label. These cases let you check the effect of each operation.
Use `count(*)` to count rows and `count(column)` to count non-null values.
Add `DISTINCT` to count unique values:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT count(*) AS records,
count(DISTINCT doc_id) AS documents,
count(caption) AS captioned,
count(*) FILTER (WHERE caption IS NULL) AS missing_caption
FROM curation_documents;
```
</CodeGroup>
The example returns **6 records, 4 documents, 4 populated captions and 2 missing
captions**. `count(column)` excludes null values; it does not check whether a
@@ -72,12 +76,14 @@ string is empty or whether a value is useful for the task.
Use `GROUP BY` to calculate a summary for each label:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT label, count(*) AS documents
FROM curation_labels
GROUP BY label
ORDER BY documents DESC, label;
```
</CodeGroup>
There are **2 cats and 1 dog** in the label table. Document 40 is absent, so this
query does not measure labeling coverage across all source documents. Use a
@@ -90,7 +96,8 @@ To cap the number selected per label, use
## Count records that match a condition {#conditional}
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT source,
count(*) AS records,
count(*) FILTER (WHERE score >= 0.9) AS high_score,
@@ -99,6 +106,7 @@ FROM curation_documents
GROUP BY source
ORDER BY source;
```
</CodeGroup>
`FILTER` applies a condition to one aggregate. Here, `books` has 2 records,
1 high-score record and no missing captions. `web` has 4 records, 1 high-score
@@ -112,22 +120,54 @@ Use `count(DISTINCT column)` for the number of distinct non-null values.
For numeric fields, group by a range or summarize their distribution. For
example, this query counts records in score buckets of width 0.1:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT floor(score * 10) / 10 AS score_bucket, count(*) AS records
FROM curation_documents
GROUP BY score_bucket
ORDER BY score_bucket;
```
</CodeGroup>
For time-based data, group by the time interval relevant to the task. The
[aggregation reference](/sql/dql/aggregation) and
[scalar function reference](/sql/scalar-functions) cover additional summaries,
[scalar function reference](/sql/dql/scalar-functions) cover additional summaries,
including approximate counts and percentiles. Use an approximate aggregate when an estimate is sufficient; use an exact
count when the result must be precise.
## Aggregate over a Function's result {#functions}
An aggregate can summarize a [Function](/curation/create-function)'s
output the same as any other expression -- the engine computes the
Function once per row, then aggregates. Register `caption_quality` the
same way any other curation Function is registered:
<CodeGroup>
```python Python icon="python"
from lancedb import udf
@udf
def caption_quality(caption: str) -> float:
... # score the caption, e.g. with a lightweight heuristic or model
db.create_function_async(caption_quality).wait()
```
```sql SQL icon="database"
SELECT source, avg(caption_quality(caption)) AS avg_quality
FROM curation_documents
WHERE caption IS NOT NULL
GROUP BY source
ORDER BY source;
```
</CodeGroup>
Filtering out null captions first avoids calling the Function on rows with
nothing to score.
## Profile a sample {#sampling}
A [sample](/curation/sampling) can help you explore a large dataset before a
A [sample](/curation/statistical-sampling) can help you explore a large dataset before a
full scan. Report the sample size and method alongside the result. A sample can miss rare classes, and fragment sampling can reflect the order
in which records were written.
@@ -136,7 +176,7 @@ constraints directly rather than inferring them from a small sample.
## Continue curating {#reference}
Use these measurements to choose a [sample](/curation/sampling),
Use these measurements to choose a [sample](/curation/statistical-sampling),
[attach missing metadata](/curation/join), or
[select one record per document](/curation/windowing).
See [Aggregation](/sql/dql/aggregation) for complete SQL syntax.
@@ -0,0 +1,176 @@
---
title: "Blob Late Materialization"
sidebarTitle: "Blob Late Materialization"
description: "Deferring a wide BlobV2 or vector column's read until after a join has already narrowed down which rows survive."
icon: clock
keywords: ["late materialization", "blob", "blobv2", "join", "remotetake", "take"]
availability:
embedded: unavailable
enterprise: available
---
A join that includes a wide column -- a [BlobV2](/management/table#managed-blobs)
or an embedding -- can multiply that column's read far past the result's
own row count: a naive plan reads the wide column for every candidate row
the join considers, then throws most of that work away once the join
condition filters non-matches. Blob late materialization is the
optimizer rewrite that avoids this, deferring the wide read until after
the join has already settled which rows survive.
## The two plan shapes {#plan-shapes}
<div className="hidden dark:block">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8",
"primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8",
"clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513",
"fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart TB
subgraph Naive["Naive: wide column read before filtering"]
direction TB
N1["Scan wide column<br/>for every row"] --> N2["Join"]
N2 --> N3["Rows that didn't match<br/>are discarded --<br/>their wide read was wasted"]
end
subgraph Deferred["Late materialization: wide column read after filtering"]
direction TB
D1["Scan only the join key<br/>(+ early columns)"] --> D2["Join on the key"]
D2 --> D3["RemoteTake:<br/>fetch the wide column,<br/>once per surviving row"]
end
classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8
classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8
class D3 accent
```
</div>
<div className="block dark:hidden">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19",
"primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19",
"clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff",
"fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart TB
subgraph Naive["Naive: wide column read before filtering"]
direction TB
N1["Scan wide column<br/>for every row"] --> N2["Join"]
N2 --> N3["Rows that didn't match<br/>are discarded --<br/>their wide read was wasted"]
end
subgraph Deferred["Late materialization: wide column read after filtering"]
direction TB
D1["Scan only the join key<br/>(+ early columns)"] --> D2["Join on the key"]
D2 --> D3["RemoteTake:<br/>fetch the wide column,<br/>once per surviving row"]
end
classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19
classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19
class D3 accent
```
</div>
In the naive plan, the wide column is read once per **candidate** row --
every row either side of the join could possibly produce -- before the
join has thrown any of them away. In the rewritten plan, the join
operates on a narrowed schema (the key, any small "early" columns, and a
row id), and a `RemoteTake` node fetches the wide column afterward, once
per row that actually **survived** the join.
## Eligibility {#eligibility}
This is a physical-plan optimizer rewrite, not something you opt into
with special syntax -- the optimizer decides whether a given join
qualifies. It applies to a plain inner equi-join (a single `ON left_col
= right_col` condition, no additional filter fused into the join, no
`LIMIT` fused into it) where one side -- and only one side -- bottoms out
at a single, otherwise-unfiltered table scan: no existing row filter,
scan range, fragment subset, deleted-row handling, or
[RTE write](/ingestion/realtime-write) tier. If both sides would
otherwise qualify, the side with a BlobV2 column is preferred over the
other; if neither or both sides have one, the rewrite declines rather
than guessing which to narrow.
Which columns actually get deferred differs by which side of the join is
narrowed:
- **The side that builds the join's hash table:** every column beyond
the join key is deferred, regardless of size. The hash table holds
everything this side reads for the lifetime of the join, so even a
modestly-sized column adds up across every row the join holds in
memory at once.
- **The side that probes the hash table:** only columns wide enough to
cross a size heuristic are deferred; small columns stay in the initial
scan, since reading them eagerly doesn't carry the same memory risk.
A BlobV2 column's **descriptor** (small, pointer-like) is early and
stays in the scan either way -- only the raw **bytes** of the blob are
late and deferred, so narrowing doesn't lose track of which rows have a
blob at all, just postpones reading its payload.
## Where the deferred read actually happens {#remotetake}
The take itself runs through the same replica-group-aware routing as any
other distributed table read (see [Horizontal Scaling](/enterprise/horizontal-scaling)) --
it is not shipped back to the query node to be joined there directly.
Routing is resolved once per query and reused across every batch the
take processes, rather than re-resolved per batch, which is what keeps
repeated takes in the same query hitting a cache that's already warm
instead of bouncing between replica groups. Where the executing node
already holds the needed data, the take can also resolve natively
without a separate network round trip at all.
## Confirming it happened {#explain}
A join written this way is a **candidate** for the rewrite, not a
guarantee -- confirm it per query with
[`EXPLAIN`](/basics/sql#query-plans). A `Take` or `RemoteTake` node by
itself isn't proof either way -- it's the general operator that fetches
columns for selected rows from remote storage, and shows up in an
ordinary, join-free query just as it does here (see the
[recorded vector-search plan](/basics/sql#5-data-retrieval)); the
rewrite itself inserts a plain `Take`, which only a later, separate pass
turns into `RemoteTake`. What confirms the deferral specifically is a
`Take`/`RemoteTake` node sitting above a `HashJoinExec`, fetching a
column set that includes `__join_late_materialization_key` -- that key
column only exists when this rewrite fired. Join on a narrow, selective
key and project the wide columns only in the final select list, rather
than alongside the join condition:
<CodeGroup>
```sql SQL icon="database"
SELECT s.frame_id, f.image, f.embedding
FROM selected AS s
JOIN frames AS f ON f.frame_id = s.frame_id
```
</CodeGroup>
`selected` is narrow -- just the frame IDs an earlier curation step
already kept. `frames` is wide -- a BlobV2 `image` and a vector
`embedding` alongside its key. Neither a passing query nor an `EXPLAIN`
that omits `RemoteTake` tells you how much I/O a plan did or did not
save on its own -- use [`EXPLAIN ANALYZE`](/sql/dql/explain) for the
plan's actual row and byte counts, since plain `EXPLAIN` shows the
planned shape without executing the query.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Joining datasets" icon="link" href="/curation/join">
Join types, duplicate keys, and calling a Function across a join.
</Card>
<Card title="Joins" icon="link" href="/sql/dql/join">
Join syntax and semantics in the SQL reference.
</Card>
<Card title="Query plans" icon="map" href="/basics/sql#query-plans">
Reading `EXPLAIN` output in general.
</Card>
<Card title="Horizontal Scaling" icon="arrows-left-right" href="/enterprise/horizontal-scaling">
The replica-group routing a RemoteTake's read goes through.
</Card>
</CardGroup>
+12 -4
View File
@@ -20,7 +20,8 @@ to what is new.
`curation_batches` gets a batch of new documents appended periodically, with
no updates or deletes between appends:
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR);
INSERT INTO curation_batches VALUES
(1, 'web', 'A cat on a chair'),
@@ -31,15 +32,18 @@ INSERT INTO curation_batches VALUES
(4, 'books', 'A cat by a window');
-- the table is now at a later version, for example 7
```
</CodeGroup>
## Read only what is new {#read-new}
`CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)` reads the rows
appended after version 5 -- documents 3 and 4 -- without rescanning 1 and 2:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)
```
</CodeGroup>
Record the table's version after each curation run, then start the next
run's `CHANGES` from it. See [Versioning](/management/table#versioning) for
@@ -52,12 +56,14 @@ the rest of this page: chunk, dedupe, or join only the new rows, instead of
the whole table. Materializing the result keeps a running, append-only table
of work already done:
```sql
<CodeGroup>
```sql SQL icon="database"
INSERT INTO curated_batches
SELECT doc_id, source, text
FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)
WHERE source = 'books'
```
</CodeGroup>
A [chunker Function](/curation/chunking) or a [`dedupe`](/sql/dql/dedupe)
call works the same way: put the `CHANGES` relation where the source table
@@ -70,10 +76,12 @@ other than a pure append happened to the table between the starting version
and the current one -- an update, a delete, a merge -- the query is refused
rather than silently returning an incomplete or wrong result:
```sql
<CodeGroup>
```sql SQL icon="database"
-- refused if any row in curation_batches was updated or deleted after version 5
SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)
```
</CodeGroup>
When that happens, either re-run from a later starting version that is
itself after the non-append write, or read the table in full instead of
+48 -37
View File
@@ -25,7 +25,11 @@ Functions, and scalar versus batch calling, if you have not registered one
before.
A function that splits text into fixed-size passages turns a `documents`
table into one row per passage:
table into one row per passage. Registration details, environment and
dependency declarations, and how a version stays immutable once rows are
filled from it, are the same for a chunker as for any other Function --
register it from Python, or the same function from SQL with
[`CREATE FUNCTION`](/sql/ddl/function#create):
**Source: `documents`**
@@ -36,9 +40,9 @@ table into one row per passage:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
from lancedb.functions import udf
from lancedb.functions import function
@udf(
@function(
output_schema=pa.list_(
pa.struct([
pa.field("chunk_index", pa.int64(), nullable=False),
@@ -55,36 +59,37 @@ def split_into_passages(text: str) -> list[dict]:
version = db.create_function_async(split_into_passages).wait()
```
</CodeGroup>
Registration details, environment and dependency declarations, and how a
version stays immutable once rows are filled from it, are the same for a
chunker as for any other Function. The same function can be registered from
SQL with `CREATE FUNCTION`:
<CodeGroup>
```sql SQL
```sql SQL icon="database"
CREATE FUNCTION split_into_passages(text utf8)
RETURNS list<struct<chunk_index: int64, chunk_text: utf8>>
LANGUAGE python
AS 'def split_into_passages(text): size = 200; return [{"chunk_index": i, "chunk_text": text[i:i+size]} for i in range(0, len(text), size)]'
AS '
def split_into_passages(text):
size = 200
return [
{"chunk_index": i, "chunk_text": text[i:i+size]}
for i in range(0, len(text), size)
]
'
```
</CodeGroup>
## Explode it in a query {#explode}
Call the function in the `FROM` clause, after the source table, with an
alias: a Function there yields one row per element of the list it returns,
with every other column repeated. Reference the function's output fields
through the alias:
Wrap the function call in `UNNEST` in the `SELECT` list, with an alias: it
yields one row per element of the list the function returns, with every
other selected column repeated. Reference the exploded struct's fields
through that alias in a query over this one:
<CodeGroup>
```python Python icon="python"
reader = db.execute_query("""
SELECT doc_id, title, p.chunk_index, p.chunk_text
FROM documents, split_into_passages(text) AS p
""")
print(reader.read_all().to_pylist())
```sql SQL icon="database"
WITH exploded AS (
SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p
FROM documents
)
SELECT doc_id, title, p.chunk_index, p.chunk_text
FROM exploded
```
</CodeGroup>
@@ -112,7 +117,7 @@ A chunker that samples one timestamp per second needs no blob access at all
<CodeGroup>
```python Python icon="python"
@udf(
@function(
output_schema=pa.list_(
pa.struct([
pa.field("frame_index", pa.int64(), nullable=False),
@@ -134,11 +139,10 @@ rather than loading the whole clip -- and returns one JPEG per call:
<CodeGroup>
```python Python icon="python"
import lancedb
from datetime import timedelta
from lancedb import BlobReader
@udf(
@function(
name="extract_frame",
gpu=True,
pip=["av==13.1.0", "pillow==11.0.0"],
@@ -159,11 +163,13 @@ Compose both in one query: explode `videos` into one row per sampled
timestamp, then call `extract_frame` on each row to produce its image:
<CodeGroup>
```python Python icon="python"
reader = db.execute_query("""
SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg
FROM videos, sample_frame_timestamps(duration_seconds) AS f
""")
```sql SQL icon="database"
WITH sampled AS (
SELECT video_id, video, UNNEST(sample_frame_timestamps(duration_seconds)) AS f
FROM videos
)
SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg
FROM sampled
```
</CodeGroup>
@@ -179,10 +185,14 @@ to keep a real table that stays current as the source changes, instead of
recomputing the explosion on every query:
<CodeGroup>
```sql SQL
```sql SQL icon="database"
CREATE MATERIALIZED VIEW chunks AS
WITH exploded AS (
SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p
FROM documents
)
SELECT doc_id, title, p.chunk_index, p.chunk_text
FROM documents, split_into_passages(text) AS p
FROM exploded
```
</CodeGroup>
@@ -196,15 +206,16 @@ FROM documents, split_into_passages(text) AS p
The view refreshes like any other materialized view: new source rows are
chunked and inserted, deleted source rows drop their children, and an
updated row's old children are replaced by freshly chunked ones on the next
[refresh](/feature-engineering/refresh-column). A single Function call or
`UNNEST(column)` is the only lateral source a materialized view can carry --
not both, and not combined with `GROUP BY` -- so keep aggregation or further
curation in a second step over the chunked table.
[refresh](/feature-engineering/refresh-column). A single `UNNEST(...)` --
whether unnesting a Function's list output directly, as above, or an
existing list column -- is the only lateral expansion a materialized view
can carry, and it can't be combined with `GROUP BY`, so keep aggregation or
further curation in a second step over the chunked table.
## Chunk, then curate {#next}
A freshly chunked table is a normal table: [dedupe](/curation/dedupe) it to
collapse near-identical chunks, [sample](/curation/sampling) it for a quick
collapse near-identical chunks, [sample](/curation/statistical-sampling) it for a quick
look, or [profile it](/curation/aggregate) to check how many chunks each
source row produced. Continue with
[choosing a curation task](/curation#questions).
+166
View File
@@ -0,0 +1,166 @@
---
title: "Cluster records by index partition"
sidebarTitle: "Clustering"
description: "Group records by the partition an existing IVF vector index already assigns them to, without training a new clustering model."
icon: circle-nodes
keywords: ["clustering", "ivf_partition", "ivf", "vector index", "group by", "centroid"]
availability:
embedded: unavailable
enterprise: available
---
`ivf_partition` groups records by the partition a vector falls into, using the
centroids of an IVF-family vector index you already built for search -- no
separate clustering model to train or maintain. Use it as a `GROUP BY` key to
aggregate per cluster, or to sample across clusters instead of across rows.
## Example data {#example-data}
Connect with an [Enterprise connection](/basics/catalog#enterprise).
<Accordion title="Create the example table">
Use the same `curation_embeddings` fixture as [dedupe](/curation/dedupe#example-data)
-- eight records, where rows 10 and 20 are near-identical, 30, 40 and 50
form one looser cluster, and 60, 70 and 80 are each distinct and
increasingly far apart -- but build the index with more partitions.
Clustering wants partitions fine-grained enough to tell the two clusters
apart; deduplication only needs a distance threshold within one:
<CodeGroup>
```python Python icon="python"
table.create_index("embedding", config=IvfFlat(num_partitions=5, distance_type="l2"))
table.wait_for_index(["embedding_idx"])
```
```typescript TypeScript icon="square-js"
await table.createIndex("embedding", {
config: lancedb.Index.ivfFlat({ numPartitions: 5, distanceType: "l2" }),
});
await table.waitForIndex(["embedding_idx"], 300);
```
```rust
use std::time::Duration;
use lancedb::index::vector::IvfFlatIndexBuilder;
use lancedb::index::Index;
use lancedb::DistanceType;
table
.create_index(
&["embedding"],
Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(5).distance_type(DistanceType::L2)),
)
.execute()
.await?;
table.wait_for_index(&["embedding_idx"], Duration::from_secs(300)).await?;
```
</CodeGroup>
`ivf_partition` reads an existing index's trained centroids; it does not
train one. The column needs an up-to-date, single-segment IVF-family index
before the function runs, the same requirement [`dedupe`](/curation/dedupe#example-data)
has.
</Accordion>
## Group records by partition {#group}
`ivf_partition(column)` returns the partition each row's vector falls into.
Rows closer to the same centroid than to any other land in the same
partition, so the near-identical cat photos (10, 20) group together, the
three dog photos (30, 40, 50) group together, and the three increasingly
distant photos (60, 70, 80) are more likely to each keep their own partition:
<CodeGroup>
```sql SQL icon="database"
SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids, count(*) AS n
FROM curation_embeddings
GROUP BY cluster
ORDER BY cluster
```
</CodeGroup>
The exact partition numbers depend on how the index's centroids were trained,
but rows that are close together in embedding space consistently land in the
same group. Aggregate anything per cluster this way -- `count(*)` for cluster
sizes, `avg(score)` for a per-cluster quality signal, or `array_agg(id)` to
collect candidate rows for a downstream pass.
## Sample across clusters instead of across rows {#sample}
Pass a selection mode to group by only a subset of the index's partitions,
instead of all of them:
<CodeGroup>
```sql SQL icon="database"
-- The first 2 partitions, deterministically
SELECT ivf_partition(embedding, 'first', 2) AS cluster, array_agg(id) AS ids
FROM curation_embeddings
GROUP BY cluster;
-- 2 partitions chosen at random, reproducible via the seed
SELECT ivf_partition(embedding, 'random', 2, 42) AS cluster, array_agg(id) AS ids
FROM curation_embeddings
GROUP BY cluster;
```
</CodeGroup>
`'first'` takes the first `count` partitions and accepts no seed, since the
result is already deterministic. `'random'` requires a seed, so the same
call reproduces the same partitions. Either way, the result is a
spatially-stratified sample across the embedding space: one that covers
each selected region of the data, rather than a plain row sample that can
easily pick many near-duplicate rows from a dense cluster and miss a sparse
one entirely.
## Keep a clustering current with a materialized view {#materialized}
Wrap a `GROUP BY ivf_partition(...)` query in a
[materialized view](/management/materialized-view) so the grouping stays
current as new records arrive:
<CodeGroup>
```sql SQL icon="database"
CREATE MATERIALIZED VIEW curation_embeddings_clustered AS
SELECT ivf_partition(embedding) AS cluster, array_agg(id) AS ids
FROM curation_embeddings
GROUP BY cluster
```
</CodeGroup>
A refresh reassigns every row's partition from the index's current centroids,
so retraining the index with
[`replace=True`](/feature-engineering/add-computed-column) regroups the view
on the next refresh. See
[Refresh a materialized view](/feature-engineering/refresh-materialized-view)
for manual and automatic refresh options.
## A typical use case: deduplication {#dedupe}
Near-duplicate records are close together in embedding space, so they
consistently land in the same or a neighboring partition. Grouping by
`ivf_partition` first, then comparing distances only within each group, finds
near-duplicate candidates without a full pairwise scan across the whole
table.
This is exactly the approach [`dedupe` and `duplicate_pairs`](/curation/dedupe)
use internally, packaged as a table function with a `distance_threshold`
instead of a `GROUP BY` clause to write yourself. Reach for those directly for
deduplication; use `ivf_partition` when the task is a different kind of
per-cluster grouping or sampling, not deduplication specifically.
## Related guides {#next}
<CardGroup cols={2}>
<Card title="IVF_PARTITION" icon="circle-nodes" href="/sql/dql/ivf-partition">
The full function signature: arguments, sampling modes, and positional syntax.
</Card>
<Card title="Deduplicate near-duplicates" icon="clone" href="/curation/dedupe">
The packaged table function for the deduplication use case above.
</Card>
<Card title="Statistical Sampling" icon="dice" href="/curation/statistical-sampling">
Row-level and fragment-level sampling, without clustering.
</Card>
</CardGroup>
+231 -59
View File
@@ -1,5 +1,6 @@
---
title: "Create a Function"
tag: "Early access"
sidebarTitle: "Create Function"
description: "Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch."
icon: code
@@ -9,12 +10,17 @@ availability:
enterprise: available
---
<Badge color="purple">Early access</Badge>
Some curation steps cannot be written as a SQL expression: an embedding
model, an image decode, a call to an external service. A Function is a
Python callable registered with the database, versioned, and then applied as
a column or called in a query -- the code runs where the data is, not pulled
into your process first. This page covers how to shape one; later curation
tasks such as [Chunking](/curation/chunking) assume you have read it.
tasks such as [Chunking](/curation/chunking) assume you have read it. The
full registration, listing, refresh and drop lifecycle is covered on the
[Function management reference](/management/function); the examples below
focus on shaping a Function for common curation tasks.
## Scalar: once per row {#scalar}
@@ -23,9 +29,9 @@ inferred from the annotations:
<CodeGroup>
```python Python icon="python"
from lancedb import udf
from lancedb import function
@udf(pip=["numpy==2.2.0"])
@function(pip=["numpy==2.2.0"])
def score(value: float) -> float:
return value * 2
@@ -49,9 +55,13 @@ same doubling logic, vectorized over a whole batch at once:
```python Python icon="python"
import pyarrow as pa
import pyarrow.compute as pc
from lancedb import udf
from lancedb import function
@udf(pip=["numpy==2.2.0"])
@function(
pip=["numpy==2.2.0"],
batch_size=32,
row_timeout_seconds=90,
)
def score_batch(value: pa.Array) -> pa.Array:
return pc.multiply(value, 2)
```
@@ -61,17 +71,25 @@ Batching amortizes per-call overhead across many rows, which matters most
once a function also does something with real fixed cost per call -- loading
a model, opening a connection, making a network round trip.
`batch_size` caps the number of input rows in each execution batch; actual
batches may be smaller. `row_timeout_seconds` bounds each Python call: one
row for scalar Functions or the entire batch for vectorized Functions. It
does not include the instance's `__init__`. Both settings are fixed into the
registered version and apply to direct calls, computed columns, and
materialized-view refreshes alike. Omit them to use adaptive batching and the
service's default per-call deadline.
## Stateful Functions: load once, call many times {#stateful}
A `@udf`-decorated **class** is the same callable with state. Each remote
A `@function`-decorated **class** is the same callable with state. Each remote
instance calls `__init__` once, calls `__call__` for every row or batch it
processes, and calls `close()`, if defined, once when it retires:
<CodeGroup>
```python Python icon="python"
from lancedb import udf
from lancedb import function
@udf
@function
class scale:
def __init__(self, factor: float, offset: float = 0.0):
self.factor = factor
@@ -92,16 +110,26 @@ and remote-API Functions both build on below.
## GPU: batch inference, loaded once {#gpu}
`gpu=True` requires a GPU-capable worker for every execution. Combined with
the batch and stateful forms above, a realistic embedding model loads once
in `__init__` and runs one forward pass per batch, not one per row:
`db.list_gpu_classes()` lists the GPU classes configured for the deployment.
Each record reports the operator's hardware description and limits; it does
not mean a GPU is currently free. Listing requires the System Usage
permission. Pass a returned class name to `gpu_class` to fix that placement
in the Function version. `gpu=True` remains required:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
from lancedb import udf
from lancedb import function
@udf(gpu=True, pip=["torch==2.12.0", "sentence-transformers==5.7.0"])
gpu_class = next(
gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G"
)
@function(
gpu=True,
gpu_class=gpu_class,
pip=["torch==2.12.0", "sentence-transformers==5.7.0"],
)
class embed_text:
def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
import torch
@@ -120,6 +148,12 @@ table.add_columns({"embedding": version(text=col("caption"))})
```
</CodeGroup>
Older servers that do not implement `GET /v1/gpu/classes` raise
`NotImplementedError`. Without `gpu_class`, the deployment's default GPU
class is used. The class is immutable with the Function version; set a
per-refresh class or aggregate GPU budget through
[`refresh_column_async`](/feature-engineering/refresh-column#resources).
The model loads once per worker instance, in `__init__`; `__call__` only
encodes the batch it was handed. Registering the same logic as a plain
function instead would reload the model on every single row.
@@ -132,56 +166,59 @@ in the function's source. A Secret is a database-scoped named credential:
puts it in the environment variable the function reads, without ever
returning it from any API or recording it in the function's own definition.
Combine it with the stateful form so the HTTP client -- and any rate limiter
around it -- is built once, not reopened on every row:
around it -- is built once, not reopened on every row. There is no built-in
retry or per-row error-skip policy -- a function that calls a flaky service
should handle timeouts and retries itself, inside `__call__`.
<CodeGroup>
```python Python icon="python"
import os
from lancedb import EnvVarSecret, udf
See [Vend a Secret to a Function](/curation/vend-secret#specify) for the
full worked example, how the bound value actually reaches a running
evaluation, and how that differs from rotating or revoking it later.
db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"])
@udf
class embed_remote:
def __init__(self, model: str = "text-embedding-3-small"):
import os
from openai import OpenAI
self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
self.model = model
def __call__(self, text: str) -> list[float]:
response = self.client.embeddings.create(input=text, model=self.model)
return response.data[0].embedding
version = db.create_function_async(
embed_remote,
secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")],
).wait()
```
</CodeGroup>
A mistyped Secret name is caught at registration; a mistyped environment
variable name only surfaces on the first rows, since nothing records which
variables a function reads. There is no built-in retry or per-row
error-skip policy -- a function that calls a flaky service should handle
timeouts and retries itself, inside `__call__`.
## Blob v2 input and output {#blob}
## Read and produce blobs {#blobs}
A Function can bind a [Blob v2 column](/management/table#managed-blobs) and
return another one, including a blob nested inside a struct field, not only
at the top level. In row mode, a blob parameter arrives as Python `bytes`
(or a `BlobReader` for incremental, seekable access, so a function never
has to materialize a payload it only partially needs):
return another blob, including a blob nested inside a struct field, not only
at the top level. In row mode, a top-level blob parameter arrives as Python
`bytes`, or `None` for a nullable input, after the worker has read the
payload. Return bytes and let the destination table store the Managed
payload and descriptor.
This section extracts a frame from a stored video and captions it,
continuing as one example across chaining, persisting and incremental reads
below. `videos` holds raw clips in a `video` Blob v2 column; `frames` names
one timestamp per clip to extract, with a `selected` flag to skip some:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
import lancedb
from lancedb import BlobReader, udf
@udf(
videos = db.create_table("videos", schema=pa.schema([
pa.field("id", pa.utf8(), nullable=False),
lancedb.blob("video", nullable=False),
]))
frames = db.create_table("frames", [
{"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True},
{"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True},
])
```
</CodeGroup>
### Produce a blob {#produce-blobs}
Declare blob inputs and outputs explicitly. `extract_frame` reads one frame
out of a video at a timestamp and returns it as a JPEG, without loading the
whole clip first -- see [Read a blob incrementally](#incremental) below for
how the `video: BlobReader` parameter does that:
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
from lancedb import BlobReader, col
from lancedb.functions import function
@function(
name="extract_frame",
gpu=True,
pip=["av==13.1.0", "pillow==11.0.0"],
input_schema=pa.schema([
@@ -192,18 +229,153 @@ from lancedb import BlobReader, udf
)
def extract_frame(video: BlobReader, ts: float) -> bytes:
... # decode the frame at ts, encode as JPEG, return its bytes
extract_frame_version = db.create_function_async(extract_frame).wait(
timeout=timedelta(minutes=15)
)
```
</CodeGroup>
`output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather
than plain Arrow `binary` -- returning `bytes` with no explicit blob output
schema still holds the right bytes, but skips the Managed storage path and
`fetch_blobs`. Declare it explicitly on every function whose output should
be a blob.
An empty byte string is a filled result. A scalar output cannot be nullable,
because a physical NULL marks an unfilled computed row. To return a nullable
blob as a value, use a named-struct output schema with a nullable blob field;
the struct itself records whether the result has been filled. Read a nested
blob with `table.fetch_blobs("payload.image", hits)`.
A list or large-list output may also contain Blob v2 elements; inputs and
fixed-size lists do not support this layout. List-nested values are queryable
as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their
payloads.
<Warning>
`output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2
rather than plain Arrow `binary`. Returning `bytes` from a function whose
output type is inferred from a bare annotation, with no explicit
`lancedb.blob(...)` output schema, persists as ordinary `binary`: the column
still holds the right bytes, but it skips the Managed storage path, descriptor
reads, and `fetch_blobs`. Declare it explicitly on every function whose output
should be a blob, not just the first one in a chain.
</Warning>
### Chain a Function on its output {#chain}
A second Function can bind a blob another Function produced. Register
`caption` the same way, consuming a blob instead of producing one:
<CodeGroup>
```python Python icon="python"
@function(gpu=True, pip=["transformers==4.47.0"])
def caption(jpeg: bytes) -> str:
... # run a vision-language model over the JPEG, return one sentence
caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15))
```
</CodeGroup>
Compose both in one SQL statement over a join, instead of applying each as
its own column. The join supplies `video` and `ts` from two different
tables, and `caption` reads `extract_frame`'s result as it is computed,
before anything is written:
<CodeGroup>
```sql SQL
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
```
</CodeGroup>
[`EXPLAIN`](/sql/dql/explain) on a query like this shows `RemoteTake`: the
blob is read once, where the worker runs, and never pulled into the query
node first.
### Persist it as a column, or a materialized view {#persist}
Apply the same registered version with `add_columns` to persist its output as
an ordinary table column, on a table that already has both of its inputs --
here, a single-clip table with its own `video` and `ts`, rather than the two
tables the join above reads from:
<CodeGroup>
```python Python icon="python"
clips = db.create_table("clips", schema=pa.schema([
pa.field("frame_id", pa.int64(), nullable=False),
lancedb.blob("video", nullable=False),
pa.field("ts", pa.float64(), nullable=False),
]))
clips.add_columns({"jpeg": extract_frame_version(video=col("video"), ts=col("ts"))})
result = clips.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15))
assert result.rows_failed == 0
hits = clips.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow()
values = clips.fetch_blobs("jpeg", hits).to_pylist()
```
</CodeGroup>
Or wrap the join and both Functions in a
[materialized view](/sql/ddl/materialized-view) instead, so the extracted
frame and its caption stay current as new videos and frames arrive. See
[Auto Refresh](/enterprise/auto-refresh) for
keeping either one fresh without calling refresh yourself.
On deployments that support computed-column inputs, another Function can
bind to `col("jpeg")` directly, the same as the SQL join above does through
its own expression. Refresh the producer first, then the consumer. Once
outputs are current, a later refresh fills appended rows. A filtered
refresh preserves payload references for unselected Managed outputs. An
unfiltered refresh can recompute a whole fragment when it cannot establish
that the fragment's outputs are current.
Function output blobs follow the same compaction and cleanup lifecycle as
ingested Managed blobs. Retained versions continue to own their payloads;
cleanup reclaims an object only after its retained references are gone.
### Read a blob incrementally {#incremental}
Annotate a row Function parameter with `BlobReader` to read a Blob v2 input
incrementally, the way `extract_frame` above does, instead of materializing
the whole payload first. The signature selects the access mode without
another registration option. A minimal example, reading only the first MP4
box type without loading the rest of the video:
<CodeGroup>
```python Python icon="python"
from lancedb import BlobReader, function
@function
def first_box_type(video: BlobReader) -> bytes:
video.seek(4)
return video.read(4)
```
</CodeGroup>
The worker passes a seekable reader backed by the stored blob --
`video.seekable()` is `True`. `read(size)` reads from the current cursor;
`read_range(offset, length)` reads a byte range without moving it, the same
bytes a `seek(offset)` followed by `read(length)` would read. `size()`
returns the payload size without reading it. Each row call receives its own
reader, which closes when the call returns or raises. Do not retain it for
another invocation.
Use `video: bytes` when the Function needs the complete payload. Bytes inputs
materialize before invocation and remain subject to eager input limits.
Reader inputs keep the unread payload out of the input batch, but calling
`video.read()` without a size loads all remaining bytes in Python. Reader
inputs are supported in row mode. Return values remain ordinary values such
as `bytes`; this feature does not add streamed outputs.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Function" icon="code" href="/management/function">
List, describe and drop registered Function versions.
</Card>
<Card title="Vend a Secret to a Function" icon="key" href="/curation/vend-secret">
Bind a credential by reference instead of putting it in the function's source.
</Card>
<Card title="Chunk records into multiple rows" icon="diagram-subtask" href="/curation/chunking">
A Function whose output is a list, exploded into one row per element.
</Card>
+31 -23
View File
@@ -9,7 +9,7 @@ availability:
enterprise: available
---
[Ranking and deduplication](/curation/windowing#dedup) removes records by an
[Ranking](/curation/windowing#dedup) removes records by an
explicit rule, such as keeping the latest version of a known key. This page
covers the other kind of duplicate: records with no shared key that are still
nearly identical, judged by distance between their embeddings -- a stopped
@@ -57,23 +57,27 @@ table.wait_for_index(["embedding_idx"])
before either function runs; a query against unindexed fragments is rejected
rather than silently returning stale or wrong results.
For an `l2` index, `distance_threshold` and the `distance` column below are
both **squared** L2, not the plain L2 a plain SQL `distance()` call returns.
</Accordion>
## Collapse near-duplicates {#dedupe}
`dedupe` returns one representative row per cluster of records within
`distance_threshold` of each other -- rows 10/20 collapse to one, 30/40/50
collapse to one, and the four distinct rows pass through unchanged:
collapse to one, and the four distinct rows pass through unchanged, leaving
ids 10, 30, 60, 70 and 80:
<CodeGroup>
```python Python icon="python"
reader = db.execute_query("""
SELECT id, caption FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06)
ORDER BY id
""")
print(reader.read_all().to_pylist())
# [{'id': 10, 'caption': 'a cat on a chair'}, {'id': 30, 'caption': 'a dog in a field'},
# {'id': 60, ...}, {'id': 70, ...}, {'id': 80, ...}]
```sql SQL icon="database"
SELECT id, caption
FROM dedupe(
'curation_embeddings',
'embedding',
distance_threshold => 0.003
)
ORDER BY id
```
</CodeGroup>
@@ -96,18 +100,20 @@ id as a stable identifier for its cluster.
anything -- useful for review, or for a threshold that is still being tuned:
<CodeGroup>
```python Python icon="python"
db.execute_query("""
SELECT id_a, id_b, distance FROM duplicate_pairs(
'curation_embeddings', 'embedding', distance_threshold => 0.06, id_column => 'id'
)
ORDER BY id_a
""")
```sql SQL icon="database"
SELECT id_a, id_b, distance
FROM duplicate_pairs(
'curation_embeddings',
'embedding',
distance_threshold => 0.003,
id_column => 'id'
)
ORDER BY id_a
```
</CodeGroup>
This returns the pairs `(10, 20)`, `(30, 40)` and `(40, 50)` -- note 30 and 50
are not a direct pair here (they sit `0.10` apart, outside the threshold),
are not a direct pair here (their squared L2 distance is `0.01`, outside the threshold),
even though `dedupe` merges all three transitively above.
## Keep it current with a materialized view {#materialized}
@@ -117,11 +123,13 @@ the deduplicated set stays current as new records arrive, instead of
recomputing it from scratch on every curation pass:
<CodeGroup>
```python Python icon="python"
db.execute_query("""
CREATE MATERIALIZED VIEW curation_embeddings_deduped AS
SELECT * FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06)
""")
```sql SQL icon="database"
CREATE MATERIALIZED VIEW curation_embeddings_deduped AS
SELECT * FROM dedupe(
'curation_embeddings',
'embedding',
distance_threshold => 0.003
)
```
</CodeGroup>
+111
View File
@@ -0,0 +1,111 @@
---
title: "Distributed Shuffle"
sidebarTitle: "Distributed Shuffle"
description: "How a SQL query's intermediate results move between plan executors for a join, aggregate or sort."
icon: shuffle
availability:
embedded: unavailable
enterprise: available
---
A distributed SQL query plans as a sequence of **stages**, each with its
own set of partitions, connected by an **exchange**: a streaming gRPC
service that carries one stage's output to the next stage's plan
executors. [Distributed Search](/enterprise/distributed-search) covers
how a query gets placed on the fleet in the first place; this page covers
what happens between placement and the final result, for a query whose
plan needs data repartitioned across machines -- a hash join or a grouped
aggregate, for example, where rows with the same key must land on the
same worker regardless of which plan executor originally read them.
<div className="hidden dark:block">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8",
"primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8",
"clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513",
"fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart LR
subgraph Stage1["Stage: scan"]
direction TB
PE1["Plan executor<br/>reads its partition"]
PE2["Plan executor<br/>reads its partition"]
end
EX["Exchange<br/>streaming gRPC,<br/>repartitions by join/group key,<br/>backpressure via a byte budget"]
subgraph Stage2["Stage: join / aggregate"]
direction TB
PE3["Plan executor<br/>probes its share of keys"]
PE4["Plan executor<br/>probes its share of keys"]
end
PE1 --> EX
PE2 --> EX
EX --> PE3
EX --> PE4
classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8
classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8
class EX accent
```
</div>
<div className="block dark:hidden">
```mermaid
%%{init: {"theme": "base", "themeVariables": {
"background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19",
"primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19",
"clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff",
"fontFamily": "Inter, sans-serif", "fontSize": "18px"
}}}%%
flowchart LR
subgraph Stage1["Stage: scan"]
direction TB
PE1["Plan executor<br/>reads its partition"]
PE2["Plan executor<br/>reads its partition"]
end
EX["Exchange<br/>streaming gRPC,<br/>repartitions by join/group key,<br/>backpressure via a byte budget"]
subgraph Stage2["Stage: join / aggregate"]
direction TB
PE3["Plan executor<br/>probes its share of keys"]
PE4["Plan executor<br/>probes its share of keys"]
end
PE1 --> EX
PE2 --> EX
EX --> PE3
EX --> PE4
classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19
classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19
class EX accent
```
</div>
## Pipelined, not batched {#pipelined}
The exchange moves data as a gRPC stream of row batches, not a file a
later stage waits for: a consuming plan executor pulls batches as they
become available, and a slow consumer throttles its producer through a
byte budget on unread messages rather than letting memory grow without
bound. A partition that stops being read -- for example the probe side of
a hash join whose build side turned out empty -- is drained rather than
left to stall the budget for every other partition sharing the same
connection.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Distributed Search" icon="network-wired" href="/enterprise/distributed-search">
How a query gets placed on the query-serving fleet in the first place.
</Card>
<Card title="Query plans" icon="map" href="/basics/sql#query-plans">
Inspect a specific query's plan and its actual execution metrics.
</Card>
</CardGroup>
+14 -6
View File
@@ -18,17 +18,21 @@ records belong, and save the selected data or the rules used to produce it.
| Task | What it helps you decide |
| --- | --- |
| [Create a Function](/curation/create-function) | How to run your own Python -- on CPU, on GPU, or against a remote service -- as part of SQL. |
| [Vend a Secret to a Function](/curation/vend-secret) | How a bound Secret's value actually reaches a running Function. |
| [Inspect Datasets](/curation/inspect-datasets) | How to query a table, a HuggingFace dataset, or an object-storage dataset the same way, and import without a separate download step. |
| [Chunk records](/curation/chunking) | How to split one record into several -- passages, clips, or tiles. |
| [Scope to what changed](/curation/changes) | How to process only the rows added since your last run. |
| [Profile a dataset](/curation/aggregate) | Whether coverage, missing values and class balance suit the task. |
| [Sample records](/curation/sampling) | Which subset to inspect or use for an experiment. |
| [Statistical Sampling](/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. |
| [Selective Sampling](/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. |
| [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. |
| [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. |
| [Cluster by index partition](/curation/clustering) | How to group records by vector proximity without training a new clustering model. |
| [Deduplicate near-duplicates](/curation/dedupe) | Which records to collapse when they only look alike, with no shared key. |
The analytical examples in this section use **Enterprise SQL**. Connect with
the [SQL guide](/basics/sql). For sampling through the Python SDK in LanceDB Embedded or
LanceDB Enterprise, see [Sample without SQL](/curation/sampling#training).
the [SQL guide](/basics/sql). For a random subset through the Python SDK in
LanceDB Embedded or LanceDB Enterprise, see [Permutation](/training/permutation).
## Prepare a labeled document dataset {#shape}
@@ -50,7 +54,8 @@ a record; `doc_id` identifies the document it describes.
Run each statement separately in a scratch database or namespace. Create these
tables once for the whole section, using fresh names if they already exist.
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_documents (
row_id BIGINT, doc_id BIGINT, version BIGINT,
source VARCHAR, caption VARCHAR, score DOUBLE
@@ -67,6 +72,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR);
INSERT INTO curation_labels VALUES
(10, 'cat'), (20, 'dog'), (30, 'cat');
```
</CodeGroup>
`score` is a sample quality score, not a search result score. Document 10 has
two versions. Document 30 has two records at the same version. Document 40
@@ -77,7 +83,8 @@ has no label. These cases let you check the effect of each operation.
The following query chooses the latest record for each document, then keeps
only documents with a label:
```sql
<CodeGroup>
```sql SQL icon="database"
WITH ranked AS (
SELECT *, row_number() OVER (
PARTITION BY doc_id ORDER BY version DESC, row_id DESC
@@ -90,6 +97,7 @@ JOIN curation_labels AS l ON l.doc_id = d.doc_id
WHERE d.rn = 1
ORDER BY d.doc_id;
```
</CodeGroup>
The result contains documents **10, 20 and 30**, with labels **cat, dog and
cat**. Document 40 is excluded because this particular task requires a label.
@@ -108,7 +116,7 @@ This example has two cats and one dog. That distribution may be appropriate
for exploration, but it does not establish a representative evaluation set.
[Profiling](/curation/aggregate) provides the counts to inspect.
[Sampling](/curation/sampling) and [ranking](/curation/windowing) help you
[Statistical Sampling](/curation/statistical-sampling) and [ranking](/curation/windowing) help you
adjust the selection without changing the original records.
## Save and reuse the result {#next}
+241
View File
@@ -0,0 +1,241 @@
---
title: "Inspect Datasets"
sidebarTitle: "Inspect Datasets"
description: "Query a table, a HuggingFace dataset, or a dataset in object storage the same way, with plain SELECT, WHERE, projection and LIMIT."
icon: database
keywords: ["select", "where", "filter", "projection", "limit", "huggingface", "storage integration", "sql", "inspect"]
availability:
embedded: unavailable
enterprise: available
---
The same `SELECT` statement inspects three kinds of source: a table
already in your database, a HuggingFace dataset, or a dataset in object
storage -- once a [storage integration](/management/storage-integration)
covers the latter two. Nothing is downloaded or imported until you choose
to import it.
## The basics: project, filter, limit {#basics}
A table name, a HuggingFace URI, and an object-storage URI all work the
same way after `FROM`:
<CodeGroup>
```sql SQL icon="database"
SELECT id, text
FROM documents
WHERE text IS NOT NULL
LIMIT 100
```
</CodeGroup>
- **Project** -- name the columns you need (`id, text`) instead of
`SELECT *`, especially for a source with large or many columns.
- **Filter** -- `WHERE` narrows rows before they come back; combine
predicates with `AND`/`OR` the same as any other table.
- **Limit** -- `LIMIT n` caps how many rows return. It bounds the result,
not the read: a remote source is still fetched at file or row-group
granularity, so a small `LIMIT` on a source with large files or row
groups can still touch more data than the row count suggests.
The rest of this page swaps `documents` for a HuggingFace or
object-storage source -- the `SELECT`/`WHERE`/`LIMIT` syntax above doesn't
change.
## Inspect a HuggingFace dataset {#huggingface}
A single-quoted HuggingFace dataset URI works directly in a SQL `FROM`
clause, the same as a table name -- no separate download, no intermediate
file on disk:
<CodeGroup>
```sql SQL icon="database"
SELECT id, text
FROM 'hf://datasets/owner/repo/data/train-*.parquet'
WHERE text IS NOT NULL
LIMIT 100
```
</CodeGroup>
<CodeGroup>
```python Python icon="python"
reader = db.execute_query("""
SELECT id, text
FROM 'hf://datasets/owner/repo/data/train-*.parquet'
WHERE text IS NOT NULL
LIMIT 100
""")
sample = reader.read_all().to_pylist()
```
</CodeGroup>
The URI is `hf://datasets/<owner>/<repo>[@<revision>]/<path>`. `<path>` can
be one Parquet file, a directory, or a glob: `*` matches within one
directory, `**` matches across directories, and a repository root selects
every Parquet file beneath it. Select a dataset configuration or split by
including it in the path. The default revision is `main`; each statement
resolves the revision to a commit once, so every worker reads the same
snapshot. This source reads Parquet files -- it does not run a dataset's
own generation scripts, and it does not compute embeddings or build
indexes, so [chunk](/curation/chunking), embed, or index the result as a
separate step, the same as data from any other source.
<Note>
Files matched by one statement must have compatible schemas, and an
unmatched path is an error rather than a silent fallback to a different
split. Nested Parquet values come through as-is; a floating-point list is
not automatically converted into a fixed-size vector column.
</Note>
## Inspect a dataset in object storage {#object-storage}
An `s3://`, `gs://` or `az://` prefix covered by a storage integration
reads an existing **Lance** dataset at that prefix, the same way as a
managed table:
<CodeGroup>
```sql SQL icon="database"
SELECT id, text
FROM 's3://customer-data/raw/documents.lance'
WHERE text IS NOT NULL
LIMIT 100
```
</CodeGroup>
This reads a dataset another process already wrote in Lance format, not
an arbitrary file format -- there is no Parquet-style reader for cloud
storage the way there is for `hf://`. See
[Storage Integration](/sql/ddl/storage-integration#read-import) for every
provider's setup.
## Access a private repository or bucket {#access}
A private HuggingFace repository, one subject to HuggingFace's
authenticated rate limits, or any non-public bucket needs a
[storage integration](/management/storage-integration) covering it. For
HuggingFace that integration is bound to a token
[Secret](/management/secret); for a non-public S3 bucket it can instead be
an IAM role integration, which needs no Secret at all -- see
[AWS S3](/ingestion/define-storage-integration#aws).
<CodeGroup>
```python Python icon="python"
db.create_secret("hf_token", "<your-hugging-face-token>")
# create_storage_integration is not in a released SDK yet; use the SQL
# form below until it ships.
db.execute_query("""
CREATE STORAGE INTEGRATION private_hub
STORAGE_PROVIDER = 'HUGGINGFACE'
STORAGE_PREFIX = 'hf://datasets/owner/private/data/'
HUGGINGFACE_TOKEN_SECRET = hf_token
""").read_all()
reader = db.execute_query(
"SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10"
)
```
```sql SQL icon="database"
CREATE SECRET hf_token TYPE = GENERIC_STRING SECRET_STRING = '<your-hugging-face-token>'
CREATE STORAGE INTEGRATION private_hub
STORAGE_PROVIDER = 'HUGGINGFACE'
STORAGE_PREFIX = 'hf://datasets/owner/private/data/'
HUGGINGFACE_TOKEN_SECRET = hf_token
SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10
```
</CodeGroup>
{/*
Draft for the storage-integration SDK release (#4618, #4775). Keep this
section unpublished until create_storage_integration ships in a release; it
is not in v0.41.0.
<CodeGroup>
```python Python icon="python"
db.create_secret("hf_token", "<your-hugging-face-token>")
db.create_storage_integration(
"private_hub", "hf://datasets/owner/private/data/",
storage_provider="HUGGINGFACE",
huggingface_token_secret="hf_token",
)
reader = db.execute_query(
"SELECT * FROM 'hf://datasets/owner/private/data/*.parquet' LIMIT 10"
)
```
</CodeGroup>
*/}
A query never names the integration: the planner matches the most specific
`STORAGE_PREFIX` that covers the URI being read, across every integration
the caller has `USAGE` on. A HuggingFace integration always needs
`HUGGINGFACE_TOKEN_SECRET`; creating one without it is rejected. For public
access, register no integration for that prefix at all -- an `hf://` read
that matches no integration is anonymous, with no environment-variable
fallback. See
[Storage Integration](/management/storage-integration) for every provider
and the full credential model.
## Import into a table {#import}
Once you've inspected a source and it looks right, `CREATE TABLE ... AS
SELECT` imports it:
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE imported AS
SELECT *
FROM 'hf://datasets/owner/repo/data/train-*.parquet'
```
</CodeGroup>
<CodeGroup>
```python Python icon="python"
db.execute_query("""
CREATE TABLE imported AS
SELECT * FROM 'hf://datasets/owner/repo/data/train-*.parquet'
""").read_all()
table = db.open_table("imported")
```
</CodeGroup>
This `CREATE TABLE AS SELECT` runs as a distributed import when the
deployment has an available plan-executor fleet: the planner assigns
disjoint file and row-group ranges to workers, each worker writes
uncommitted Lance files directly to the destination, and a coordinator
commits the completed table from their transaction metadata once every
worker finishes. A query with a global limit, aggregation or join keeps
its usual coordination; a small import can run as one local task without a
fleet. The table becomes queryable only after that final commit --
nothing partial is ever visible, and a failed or cancelled import can
resume the same durable job from its retained attempt rather than
restarting from nothing. To start over after a failed one-off import
instead, drop the partial table and rerun the statement.
<Note>
Importing requires a native database with `database_manifest_enabled`.
Combining a HuggingFace source with a WAL-backed destination table in one
CTAS is rejected, since the import cannot publish a base-only read that
omits the destination's unflushed data.
</Note>
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Storage Integration" icon="cloud" href="/management/storage-integration">
The credential object behind private repository access.
</Card>
<Card title="Create a Function" icon="code" href="/curation/create-function">
Add embeddings or derived columns to the imported data.
</Card>
<Card title="Chunk records into multiple rows" icon="diagram-subtask" href="/curation/chunking">
Split long text or media fields after importing.
</Card>
<Card title="Table" icon="table" href="/sql/ddl/table#create">
`CREATE TABLE AS SELECT` syntax and options in full.
</Card>
</CardGroup>
+49 -34
View File
@@ -27,7 +27,8 @@ a record; `doc_id` identifies the document it describes.
Run each statement separately in a scratch database or namespace. Create these
tables once for the whole section, using fresh names if they already exist.
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_documents (
row_id BIGINT, doc_id BIGINT, version BIGINT,
source VARCHAR, caption VARCHAR, score DOUBLE
@@ -44,6 +45,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR);
INSERT INTO curation_labels VALUES
(10, 'cat'), (20, 'dog'), (30, 'cat');
```
</CodeGroup>
`score` is a sample quality score, not a search result score. Document 10 has
two versions. Document 30 has two records at the same version. Document 40
@@ -55,12 +57,14 @@ has no label. These cases let you check the effect of each operation.
An inner join keeps matching records:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT d.row_id, d.doc_id, l.label
FROM curation_documents AS d
JOIN curation_labels AS l ON l.doc_id = d.doc_id
ORDER BY d.row_id;
```
</CodeGroup>
This returns **5 rows**: both records for document 10, one for document 20,
and both records for document 30. To produce one row per document,
@@ -71,13 +75,15 @@ and both records for document 30. To produce one row per document,
A left join keeps every record from the left table and fills missing right-side
values with `NULL`. Add `WHERE l.doc_id IS NULL` to return only unlabeled documents:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT DISTINCT d.doc_id
FROM curation_documents AS d
LEFT JOIN curation_labels AS l ON l.doc_id = d.doc_id
WHERE l.doc_id IS NULL
ORDER BY d.doc_id;
```
</CodeGroup>
The result is **document 40**. You might send it for annotation, retain it for
an unlabeled-data workflow, or exclude it from a task that requires labels.
@@ -87,17 +93,49 @@ an unlabeled-data workflow, or exclude it from a task that requires labels.
This example joins `curation_documents.doc_id` to `curation_labels.doc_id`.
First check whether the label table contains more than one row per document:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT doc_id, count(*) AS labels
FROM curation_labels
GROUP BY doc_id
HAVING count(*) > 1;
```
</CodeGroup>
The example returns no rows. If your data returns duplicates, decide whether
they represent valid multiple labels or records that need consolidation.
A join does not enforce one-to-one matching.
## Call a Function across the join {#functions}
A [Function](/curation/create-function) can read columns from either side
of a join, the same as any other expression -- it runs once the join has
matched rows, not before. Register `caption_quality` first:
<CodeGroup>
```python Python icon="python"
from lancedb import udf
@udf
def caption_quality(caption: str) -> float:
... # score the caption, e.g. with a lightweight heuristic or model
db.create_function_async(caption_quality).wait()
```
```sql SQL icon="database"
SELECT d.row_id, l.label, caption_quality(d.caption) AS quality
FROM curation_documents AS d
JOIN curation_labels AS l ON l.doc_id = d.doc_id
WHERE d.caption IS NOT NULL
ORDER BY d.row_id;
```
</CodeGroup>
Scoring after the join, rather than before, means `caption_quality` only
runs on rows that actually matched a label -- a document with no label
never pays for the Function call.
## Join tables across namespaces {#namespaces}
Use a table's qualified path to address it in another
@@ -121,41 +159,18 @@ Check the row count, unmatched keys and duplicate matches before using a
joined dataset. Select only the columns needed for the next step, especially
when source records include large media or embedding columns.
Use [Explain a query plan](/search/explain) to see how the query reads and
Use [Query plans](/basics/sql#query-plans) to see how the query reads and
combines data. Check the plan to see whether the query uses indexes and how it performs the
join. An index on a key does not guarantee that the join will use it.
### Defer wide columns until after the join {#late-materialization}
When one side of a join carries a BlobV2 column, an embedding, or both, join
on a narrow key first -- `row_id`, `_rowid`, or another selective column --
and project the wide columns only in the final select list, rather than
selecting them alongside the join condition. The planner can then defer
reading those columns until after the join has already narrowed down which
rows survive, instead of reading them for every candidate row.
`frames` is wide: a BlobV2 `image` and a vector `embedding` alongside its
key. `selected` is narrow: the frame IDs an earlier curation step already
kept, such as a sample or a dedupe result. Join on the key, project the wide
columns last:
```sql
SELECT s.frame_id, f.image, f.embedding
FROM selected AS s
JOIN frames AS f ON f.frame_id = s.frame_id
```
`selected` narrows the row set before `image` or `embedding` is ever touched
on the `frames` side, rather than reading every row's blob and vector just
to discard most of them after the join.
This is query planning the optimizer may or may not apply to a given query,
not a guarantee from writing the join this way. Confirm it per query with
[`EXPLAIN`](/search/explain): a plan containing `RemoteTake` deferred the
wide read; a plan without it read the wide columns eagerly, even for a query
shaped exactly like the one above. See
[Late materialization for wide columns](/sql/dql/join#late-materialization)
in the SQL reference for the underlying mechanism.
When one side of a join carries a BlobV2 column, an embedding, or both,
join on a narrow key first and project the wide columns only in the
final select list, so the planner can defer reading them until after the
join has already narrowed down which rows survive. See
[Blob Late Materialization](/curation/blob-late-materialization) for the
mechanism, eligibility, and how to confirm it happened.
## Save the result or continue curating {#reference}
+128
View File
@@ -0,0 +1,128 @@
---
title: "Selective Sampling"
sidebarTitle: "Selective Sampling"
description: "Fetch specific rows by row ID, row address or offset instead of drawing a random fraction."
icon: crosshairs
keywords: ["sampling", "row id", "row address", "offset", "take", "rowid", "rowaddr", "rowoffset"]
availability:
embedded: available
enterprise: available
---
Selective sampling fetches specific, already-known rows -- by row ID, row
address or offset -- rather than drawing a random fraction of the table.
Use it to re-fetch rows a previous query identified, resume from a saved
position, or pull a batch by index for a data loader. For a random subset
instead, see [Statistical Sampling](/curation/statistical-sampling).
LanceDB exposes three ways to address a row:
| Identifier | Stability | Typical source |
| --- | --- | --- |
| Row ID (`_rowid`) | Stable across compaction, with [stable row IDs](/basics/guarantees) enabled | A previous query's result, or `function_errors()` |
| Row address (`_rowaddr`) | Changes on compaction; encodes `(fragment_id << 32) \| row_offset` | A previous query's result, when you need the physical location |
| Offset | Table-wide position; **not** stable -- a row's offset shifts when an earlier row is deleted | `range(len(table))`, since every valid offset is known in advance |
## From Python {#python}
The SDK takes a list of row IDs or offsets directly, without going through
SQL:
<CodeGroup>
```python Python icon="python"
# By row ID -- from a previous search or scan that selected "_rowid"
rows = tbl.take_row_ids([1001, 1002, 1005]).to_arrow()
# By offset -- the full range is always [0, len(tbl))
rows = tbl.take_offsets([0, 1, 2]).to_arrow()
```
```typescript TypeScript icon="square-js"
// By row ID -- from a previous search or scan that selected "_rowid"
const rowsById = await tbl.takeRowIds([1001n, 1002n, 1005n]).toArray();
// By offset -- the full range is always [0, tbl.countRows())
const rowsByOffset = await tbl.takeOffsets([0, 1, 2]).toArray();
```
```rust
use lancedb::query::ExecutableQuery;
// By row ID -- from a previous search or scan that selected "_rowid"
let rows_by_id = tbl.take_row_ids(vec![1001, 1002, 1005]).execute().await?;
// By offset -- the full range is always [0, tbl.count_rows().await?)
let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?;
```
</CodeGroup>
Both methods return a query builder; call `.to_arrow()`, `.to_list()` or
similar to execute it.
<Note>
The guarantees for row IDs below apply to SDK releases containing
[the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826).
Earlier releases may collapse repeated IDs and return rows in a different
order.
</Note>
`take_row_ids` returns matching rows in the order of the input IDs and
preserves repeated IDs in both LanceDB Embedded and LanceDB Enterprise. For example,
`take_row_ids([1005, 1001, 1005])` returns row 1005, row 1001, then row 1005
again if both IDs exist. Missing or deleted IDs are omitted. This supports
sampling with replacement. In Rust, an explicit nonempty
`QueryBase::order_by` list overrides the requested order; limits and offsets
apply after restoring repeated rows.
`take_offsets` also preserves repeated offsets, but does not guarantee
input order. It tracks `_rowoffset` internally to restore repeated rows
and drops that column from the output unless you explicitly `select` it.
Add `_rowoffset` to your selection when you need to align a `take_offsets`
result with the input offsets.
<Note>
Ordered takes by row ID collect all matching batches, combine them into one
batch and reorder the rows before returning output batches. Even
`to_batches(max_batch_length=1)` only limits the returned batch size; it
does not bound working memory. For large requests or rows with large
column values, split the input IDs into smaller requests and use
`.select(...)` to fetch only the columns you need.
</Note>
Offsets are mostly useful for sampling: the valid range is always
`[0, len(table))`, so you can draw a random sample of offsets without
reading the table first. Row IDs require you to already have them, from an
earlier query's `_rowid` column -- but unlike offsets, a row ID keeps
addressing the same logical row even after compaction, as long as the
table has stable row IDs enabled.
## From SQL {#sql}
The same three identifiers are available as
[pseudo-columns](/sql/data-types#pseudo-columns) -- select or filter on
them like any other column:
<CodeGroup>
```sql SQL icon="database"
-- By row ID
SELECT * FROM documents WHERE _rowid IN (1001, 1002, 1005);
-- By row address
SELECT * FROM documents WHERE _rowaddr IN (4294967296, 4294967297);
-- Including the identifier in the result, to save for a later take
SELECT _rowid, * FROM documents WHERE score > 0.9;
```
</CodeGroup>
There is no dedicated Python method for taking by row address -- use
`.where("_rowaddr IN (...)")` on the SDK query builder, or the SQL form
above, since the expression language is the same either way.
## Related guides {#reference}
[Query plans](/basics/sql#query-plans) show whether a row-ID or offset
filter reads the whole table or seeks directly to the requested rows. See
[Statistical Sampling](/curation/statistical-sampling) for a random
fraction instead of specific rows, and [Permutation](/training/permutation)
for shuffled, batched reads through the Python SDK.
@@ -1,22 +1,21 @@
---
title: "Sampling"
sidebarTitle: "Sampling"
description: "Choose a sample for exploration or evaluation and preserve the selected records when reproducibility matters."
title: "Statistical Sampling"
sidebarTitle: "Statistical Sampling"
description: "Draw a random subset of a table with SQL TABLESAMPLE, by rows or by fragments."
icon: dice
keywords: ["sampling", "tablesample", "subset", "eval set", "reproducible", "shuffle"]
keywords: ["sampling", "tablesample", "bernoulli", "system", "repeatable", "random", "eval set"]
availability:
embedded: unavailable
enterprise: available
---
import { PySampleDataset } from '/snippets/curation_sampling.mdx';
Sampling selects records from a larger table. Use it to explore unfamiliar
data, run a smaller experiment, or prepare an evaluation dataset. Enterprise
SQL provides `TABLESAMPLE` for selecting a percentage or number of rows.
This page covers Enterprise SQL sampling and a complete
[Python SDK example](#training) that runs locally.
Statistical sampling draws a random subset of a table's rows using SQL's
`TABLESAMPLE` clause, attached directly to a table in `FROM`. Use it to
explore unfamiliar data, run a smaller experiment, or estimate aggregate
statistics without reading every row. For a random subset through the
Python SDK instead -- in Embedded or Enterprise -- see
[Permutation](/training/permutation). To select specific, known rows
rather than a random fraction, see [Selective Sampling](/curation/selective-sampling).
## Example data {#example-data}
@@ -32,7 +31,8 @@ a record; `doc_id` identifies the document it describes.
Run each statement separately in a scratch database or namespace. Create these
tables once for the whole section, using fresh names if they already exist.
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_documents (
row_id BIGINT, doc_id BIGINT, version BIGINT,
source VARCHAR, caption VARCHAR, score DOUBLE
@@ -49,6 +49,7 @@ CREATE TABLE curation_labels (doc_id BIGINT, label VARCHAR);
INSERT INTO curation_labels VALUES
(10, 'cat'), (20, 'dog'), (30, 'cat');
```
</CodeGroup>
`score` is a sample quality score, not a search result score. Document 10 has
two versions. Document 30 has two records at the same version. Document 40
@@ -60,10 +61,12 @@ has no label. These cases let you check the effect of each operation.
A percentage selects a fraction of the source; `ROWS` requests a row count:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (50);
SELECT row_id, doc_id FROM curation_documents TABLESAMPLE (3 ROWS);
```
</CodeGroup>
A percentage sample does not guarantee an exact number of rows. Use a count
when the desired sample size is the main constraint, and inspect the result
@@ -82,13 +85,15 @@ Choose a method according to how records should be selected:
| `BERNOULLI` (default) | Select individual rows | When records should be sampled independently of their storage fragments |
| `SYSTEM` | Select whole Lance fragments | When reducing reads matters and grouping by fragment is acceptable |
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT row_id, doc_id
FROM curation_documents TABLESAMPLE BERNOULLI (50);
SELECT row_id, doc_id
FROM curation_documents TABLESAMPLE SYSTEM (50);
```
</CodeGroup>
If write order groups records by label, date or source, a fragment sample can
reflect that grouping. On a tiny table stored in one fragment, it may include
@@ -99,19 +104,23 @@ represent rare groups; check that the resulting sample covers the groups you nee
A seed requests a repeatable draw:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT row_id, doc_id
FROM curation_documents TABLESAMPLE (50) REPEATABLE (42);
```
</CodeGroup>
Keep the source data and sampling configuration fixed when comparing draws.
For a lasting evaluation set, save the selected records rather than relying
on a seed to preserve membership as the source changes:
```sql
<CodeGroup>
```sql SQL icon="database"
CREATE TABLE curation_eval AS
SELECT * FROM curation_documents TABLESAMPLE (50) REPEATABLE (42);
```
</CodeGroup>
Create this output once with a fresh name and keep it unchanged. Record the
source version and selection policy. Sampling records independently can place
@@ -128,43 +137,50 @@ about 1% probability, not 10%.
To sample documents while retaining their available labels, sample only the
document table:
```sql
<CodeGroup>
```sql SQL icon="database"
SELECT curation_documents.row_id, curation_documents.doc_id, l.label
FROM curation_documents TABLESAMPLE (50)
JOIN curation_labels AS l ON l.doc_id = curation_documents.doc_id;
```
</CodeGroup>
This samples source records, not distinct documents. If you need to sample the
result of a join or deduplication, first save that result as a table suitable
for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result.
## Sample without SQL {#training}
## Apply a Function to a sample {#functions}
The Python SDK provides a permutation builder for selecting and ordering rows
in LanceDB Embedded and LanceDB Enterprise. A split selects a subset; a shuffle changes the order
in which records are read. `Permutation.identity(table)` retains stored order.
Sample first, then call a [Function](/curation/create-function) only on
the rows you drew -- useful for trying an expensive Function on a subset
before running it over the whole table. Register `caption_quality` first:
<Accordion title="Complete Python example: read a random subset">
<CodeGroup>
```python Python icon="python"
from lancedb import udf
Install the Python SDK with `pip install lancedb`, save the program as
`sample_dataset.py`, and run `python sample_dataset.py`. It creates a temporary
local database with ten rows and reads a random split containing three rows.
The temporary database is removed when the program finishes.
@udf
def caption_quality(caption: str) -> float:
... # score the caption, e.g. with a lightweight heuristic or model
<CodeBlock filename="sample_dataset.py" language="python" icon="python">
{PySampleDataset}
</CodeBlock>
db.create_function_async(caption_quality).wait()
```
The program prints three distinct IDs. It uses a fixed seed, but does not
promise the same IDs across SDK versions or changes to the source dataset.
```sql SQL icon="database"
SELECT row_id, caption, caption_quality(caption) AS quality
FROM curation_documents TABLESAMPLE (50)
WHERE caption IS NOT NULL;
```
</CodeGroup>
</Accordion>
For shuffled training reads, worker configuration and data loaders, see
[PyTorch Data Loader](/training/data-loading).
The Function runs only on the sampled rows, not the whole table -- a quick
way to check a Function's output, cost or latency before committing to a
full [column refresh](/feature-engineering/refresh-column).
## Related guides {#reference}
Count the sampled rows and [inspect their distribution](/curation/aggregate)
before using them. Preserve the selected data when the exact membership matters.
See [SQL sampling](/sql/dql/sampling) for syntax and restrictions.
See [SQL sampling](/sql/dql/sampling) for the complete syntax and restrictions,
and [Permutation](/training/permutation) for a random subset through the
Python SDK.

Some files were not shown because too many files have changed in this diff Show More