mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
Merge branch 'main' of https://github.com/lancedb/lancedb into merge-insert-source-stats
# Conflicts: # rust/lancedb/src/table/computed_columns.rs # rust/lancedb/src/table/refresh.rs
This commit is contained in:
@@ -48,6 +48,23 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r
|
||||
|
||||
This updates the Rust workspace Lance dependencies through `ci/set_lance_version.py`, updates `java/pom.xml`, refreshes Cargo metadata, and prints JSON metadata containing `branch_name`, `commit_message`, and `pr_title`.
|
||||
|
||||
Also synchronize the Python requirements in `python/pyproject.toml`: set the
|
||||
`tests` extra's exact `pylance` pin to the matching published Python release,
|
||||
and update the `pylance` extra's minimum when needed to exclude older bundled
|
||||
Lance majors. The minimum must still accept the test pin. Python prerelease
|
||||
spelling differs from Rust (for example, `15.0.0-beta.1` becomes `15.0.0b1`).
|
||||
Confirm the matching Python release is published before changing the pin.
|
||||
|
||||
Refresh and check `python/uv.lock` from the repository root:
|
||||
|
||||
```bash
|
||||
uv lock --project python --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match
|
||||
uv lock --project python --check --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match
|
||||
```
|
||||
|
||||
This strategy considers versions across indexes; use it only with trusted
|
||||
indexes. Commit the Python requirements and lockfile together with the bump.
|
||||
|
||||
5. Run validation:
|
||||
|
||||
```bash
|
||||
@@ -57,6 +74,16 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r
|
||||
|
||||
Fix real diagnostics and rerun clippy until it succeeds. Do not skip warnings.
|
||||
|
||||
Run the Python dependency guards with Python 3.11+ and `packaging` installed:
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s ci/tests -p test_python_dependencies.py -v
|
||||
```
|
||||
|
||||
These checks reject older Lance majors and ensure the `pylance` and `tests`
|
||||
extras remain compatible. The full CI-script suite uses
|
||||
`python3 -m unittest discover -s ci/tests -v`.
|
||||
|
||||
6. Inspect `git status --short` and `git diff` to ensure only the Lance dependency update and required compatibility fixes are present.
|
||||
|
||||
7. If the task only asks to prepare local changes, stop here and report the changed files and validation result.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
[tool.bumpversion]
|
||||
current_version = "0.41.0-beta.9"
|
||||
current_version = "0.41.0-beta.17"
|
||||
parse = """(?x)
|
||||
(?P<major>0|[1-9]\\d*)\\.
|
||||
(?P<minor>0|[1-9]\\d*)\\.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
{
|
||||
"name": "lancedb",
|
||||
"source": "./plugins/lancedb",
|
||||
"description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables.",
|
||||
"description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work with both LanceDB Embedded and LanceDB Enterprise.",
|
||||
"version": "0.1.0",
|
||||
"author": {
|
||||
"name": "LanceDB"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# LanceDB prose rules
|
||||
|
||||
`Dashes`, `PlainLanguage`, `ProductNames`, `VagueHeadings` and `VaguePhrases`
|
||||
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".
|
||||
|
||||
The product-terminology rules were added here: `EmbeddedName`,
|
||||
`RemoteExecution`, `OSSProduct`, `DistributedEnterprise`, `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`.
|
||||
|
||||
Keeping the rules here lets contributors and CI run Vale without access to the
|
||||
source repository. The root `.vale.ini` preserves the release's MDX settings
|
||||
and built-in repeated-word check. No `vale sync` is needed.
|
||||
|
||||
The rules check product names, dashes, plain language, vague headings and vague
|
||||
phrases. Findings are suggestions and do not fail the CI check.
|
||||
|
||||
To update, a maintainer downloads the next published package, verifies its
|
||||
checksum and replaces `styles/LanceDB` with the release's files. Check the
|
||||
package's `.vale.ini` for configuration changes, and update the version and
|
||||
checksum here in the same PR.
|
||||
@@ -0,0 +1,40 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s' in prose. Use a comma, a colon, parentheses or two sentences."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#punctuation
|
||||
level: warning
|
||||
nonword: true
|
||||
# An em dash in prose, and a double hyphen or en dash used as one, with a
|
||||
# space on each side. A table cell holding only an em dash, meaning "none",
|
||||
# ranges such as 1–3 and flags such as --force are left alone, and code is
|
||||
# never prose.
|
||||
raw:
|
||||
- '(?<!^\s*)—|—(?!\s*$)|(?<=\s)(?:--|–)(?=\s|$)'
|
||||
tests:
|
||||
- name: flags an em dash
|
||||
input: Indexes are optional—queries work without them.
|
||||
want: |
|
||||
1:21:LanceDB.Dashes:Avoid '—' in prose. Use a comma, a colon, parentheses or two sentences.
|
||||
- name: flags a double hyphen used as a dash
|
||||
input: It has one page per statement, syntax first -- and every SDK operation has a SQL form.
|
||||
want: |
|
||||
1:45:LanceDB.Dashes:Avoid '--' in prose. Use a comma, a colon, parentheses or two sentences.
|
||||
- name: flags a spaced en dash
|
||||
input: Compaction is cheap – it rewrites only small fragments.
|
||||
want: |
|
||||
1:21:LanceDB.Dashes:Avoid '–' in prose. Use a comma, a colon, parentheses or two sentences.
|
||||
- name: leaves an empty table cell alone
|
||||
input: |
|
||||
| Provider | Text | Images |
|
||||
| --- | --- | --- |
|
||||
| OpenAI | ✓ | — |
|
||||
| Gemini | ✓ | per request — batched |
|
||||
want: |
|
||||
4:28:LanceDB.Dashes:Avoid '—' in prose. Use a comma, a colon, parentheses or two sentences.
|
||||
- name: leaves ranges, flags and code alone
|
||||
input: |
|
||||
Use 1–3 replicas and pass --force to overwrite. Run `lancedb --version`.
|
||||
|
||||
```bash
|
||||
uv run pytest -- -k search
|
||||
```
|
||||
want: ''
|
||||
@@ -0,0 +1,19 @@
|
||||
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: ''
|
||||
@@ -0,0 +1,22 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# The in-process execution model is LanceDB Embedded, whether the data is on
|
||||
# local disk or in object storage. Identifiers such as the `oss` product key
|
||||
# are code, and code is never prose.
|
||||
swap:
|
||||
'LanceDB\s+(?:OSS|Oss|oss|Local|local)': LanceDB Embedded
|
||||
'[Ll]ocal\s+mode': LanceDB Embedded
|
||||
tests:
|
||||
- name: replaces the old names of the execution model
|
||||
input: Start with LanceDB OSS, also called LanceDB Local, and move off local mode later.
|
||||
want: |
|
||||
1:12:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'LanceDB OSS'.
|
||||
1:37:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'LanceDB Local'.
|
||||
1:65:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'local mode'.
|
||||
- name: leaves the current name, other uses of local, and code alone
|
||||
input: |
|
||||
LanceDB Embedded reads local disk or object storage. Run LanceDB locally, set `availability.oss`, or call `LanceDB OSS` in a literal.
|
||||
want: ''
|
||||
@@ -0,0 +1,25 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of the internal name '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Internal component names stay out of public text. Environment variables such
|
||||
# as `PHALANX_*` and Helm keys such as `planExecutorNodes` are code. Geneva is
|
||||
# a product name and is not listed.
|
||||
swap:
|
||||
Phalanx: query node
|
||||
'[Pp]lan\s+[Ee]xecutor': executor
|
||||
'[Pp]lan\s+[Ee]xecutors': executors
|
||||
Sophon: LanceDB Enterprise
|
||||
tests:
|
||||
- name: replaces internal component names
|
||||
input: Phalanx sends work to a Plan Executor. Plan executors cache data in Sophon.
|
||||
want: |
|
||||
1:1:LanceDB.InternalNames:Use 'query node' instead of the internal name 'Phalanx'.
|
||||
1:25:LanceDB.InternalNames:Use 'executor' instead of the internal name 'Plan Executor'.
|
||||
1:40:LanceDB.InternalNames:Use 'executors' instead of the internal name 'Plan executors'.
|
||||
1:69:LanceDB.InternalNames:Use 'LanceDB Enterprise' instead of the internal name 'Sophon'.
|
||||
- name: leaves Geneva, configuration keys and code alone
|
||||
input: |
|
||||
Geneva runs on the executor + cache fleet. Set `PHALANX_REMOTE_FTS_SCORER` and `planExecutorNodes`.
|
||||
want: ''
|
||||
@@ -0,0 +1,21 @@
|
||||
extends: existence
|
||||
message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: suggestion
|
||||
ignorecase: false
|
||||
# A suggestion, because `db://` URIs, `api_key` and `region` for the hosted
|
||||
# service are still documented as LanceDB Cloud.
|
||||
tokens:
|
||||
- 'LanceDB\s+Cloud'
|
||||
- 'Cloud\s*/\s*Enterprise'
|
||||
- 'Enterprise\s*/\s*Cloud'
|
||||
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'.
|
||||
- name: leaves other clouds and code alone
|
||||
input: |
|
||||
Deploy into your own cloud account on Google Cloud. Pass `LanceDB Cloud` as a literal.
|
||||
want: ''
|
||||
@@ -0,0 +1,28 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Bare OSS used as a product, as in "OSS and Enterprise" or "in OSS". "LanceDB
|
||||
# OSS" is reported by LanceDB.EmbeddedName.
|
||||
tokens:
|
||||
- 'OSS(?:\s+(?:and|or|vs\.?|versus)\s+|\s*/\s*)(?:LanceDB\s+)?Enterprise'
|
||||
- 'Enterprise(?:\s+(?:and|or|vs\.?|versus)\s+|\s*/\s*)OSS'
|
||||
- '(?:in|on|from|using|than)\s+OSS'
|
||||
tests:
|
||||
- name: flags OSS presented as a product
|
||||
input: Compare OSS vs Enterprise. It works in OSS and on OSS, unlike OSS/Enterprise.
|
||||
want: |
|
||||
1:9:LanceDB.OSSProduct:Avoid 'OSS vs Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
1:37:LanceDB.OSSProduct:Avoid 'in OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
1:48:LanceDB.OSSProduct:Avoid 'on OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
1:63:LanceDB.OSSProduct:Avoid 'OSS/Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
- name: flags the pair in either order
|
||||
input: Both OSS and LanceDB Enterprise ship it, as do Enterprise or OSS.
|
||||
want: |
|
||||
1:6:LanceDB.OSSProduct:Avoid 'OSS and LanceDB Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
1:48:LanceDB.OSSProduct:Avoid 'Enterprise or OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property.
|
||||
- name: leaves open source, identifiers and code alone
|
||||
input: |
|
||||
LanceDB Embedded (open source) and LanceDB Enterprise share the format. Set `oss: available` or read `in OSS` literally.
|
||||
want: ''
|
||||
@@ -0,0 +1,32 @@
|
||||
extends: substitution
|
||||
message: "Consider '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly
|
||||
level: suggestion
|
||||
ignorecase: true
|
||||
# Keep this list small. Technical nouns such as GPU utilization stay intact.
|
||||
swap:
|
||||
utilize: use
|
||||
utilizes: uses
|
||||
utilized: used
|
||||
utilizing: using
|
||||
in order to: to
|
||||
tests:
|
||||
- name: suggests familiar verbs
|
||||
input: Utilize the index. The query utilizes it. We utilized it. Try utilizing it.
|
||||
want: |
|
||||
1:1:LanceDB.PlainLanguage:Consider 'use' instead of 'Utilize'.
|
||||
1:30:LanceDB.PlainLanguage:Consider 'uses' instead of 'utilizes'.
|
||||
1:46:LanceDB.PlainLanguage:Consider 'used' instead of 'utilized'.
|
||||
1:63:LanceDB.PlainLanguage:Consider 'using' instead of 'utilizing'.
|
||||
- name: shortens an unnecessary phrase
|
||||
input: Create an index in order to search faster.
|
||||
want: |
|
||||
1:17:LanceDB.PlainLanguage:Consider 'to' instead of 'in order to'.
|
||||
- name: preserves technical terms and identifiers
|
||||
input: |
|
||||
Measure GPU utilization and resource underutilization. Keep the rows in order. Call `utilize()` and `in order to` only as literal examples.
|
||||
|
||||
```python
|
||||
utilized = "in order to"
|
||||
```
|
||||
want: ''
|
||||
@@ -0,0 +1,33 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Case-sensitive. A lowercase package, repository or domain name, such as
|
||||
# lancedb or github.com, is left alone; write identifiers in code font.
|
||||
swap:
|
||||
'(?:Lancedb|LanceDb|lanceDB|LANCEDB|Lance DB)': LanceDB
|
||||
'LanceDB (?:cloud|CLOUD)': LanceDB Cloud
|
||||
'LanceDB (?:enterprise|ENTERPRISE)': LanceDB Enterprise
|
||||
'(?:HuggingFace|Huggingface|Hugging face)': Hugging Face
|
||||
Langchain: LangChain
|
||||
Typescript: TypeScript
|
||||
VoyageAI: Voyage AI
|
||||
tests:
|
||||
- name: corrects the product name
|
||||
input: Install Lancedb and connect to LanceDB cloud or LanceDB enterprise.
|
||||
want: |
|
||||
1:9:LanceDB.ProductNames:Use 'LanceDB' instead of 'Lancedb'.
|
||||
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.
|
||||
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'.
|
||||
- name: leaves package names, identifiers and code alone
|
||||
input: |
|
||||
The lancedb package exposes `HuggingFaceEmbeddings` and LanceDBConnection; see `Typescript` in code.
|
||||
want: ''
|
||||
@@ -0,0 +1,33 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Remote storage, remote URLs and a git remote are other things and stay. Class
|
||||
# names such as `RemoteTable` are code, and code is never prose.
|
||||
tokens:
|
||||
- '[Rr]emote\s+(?:mode|tables?|connections?|databases?)'
|
||||
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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
```python
|
||||
remote_table = db.open_table("remote table")
|
||||
```
|
||||
want: ''
|
||||
@@ -0,0 +1,19 @@
|
||||
extends: existence
|
||||
message: "'%s' doesn't say what the section covers. Name the task or topic instead."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#headings
|
||||
level: suggestion
|
||||
scope: heading
|
||||
ignorecase: true
|
||||
tokens:
|
||||
- then what
|
||||
tests:
|
||||
- name: flags a heading that names no topic
|
||||
input: |
|
||||
## Then what {#next}
|
||||
|
||||
Choose the output according to how you will use it.
|
||||
want: |
|
||||
1:4:LanceDB.VagueHeadings:'Then what' doesn't say what the section covers. Name the task or topic instead.
|
||||
- name: leaves the phrase alone in body text
|
||||
input: Then what happens to the old fragments? Cleanup removes them.
|
||||
want: ''
|
||||
@@ -0,0 +1,31 @@
|
||||
extends: existence
|
||||
message: "'%s' talks about the writing, not the subject. State the point directly."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly
|
||||
level: suggestion
|
||||
ignorecase: false
|
||||
scope: sentence
|
||||
tokens:
|
||||
# The page's role instead of its content, as in "This page is the concept".
|
||||
- '^[Tt]his page is the concept'
|
||||
# A filler sentence opener, listed in skills/docs-writer/SKILL.md.
|
||||
- '^That matters'
|
||||
tests:
|
||||
- name: flags a page describing its own role
|
||||
input: This page is the concept; the SQL reference is the specification.
|
||||
want: |
|
||||
1:1:LanceDB.VaguePhrases:'This page is the concept' talks about the writing, not the subject. State the point directly.
|
||||
- name: flags the filler opener
|
||||
input: That matters for partner workloads because names repeat.
|
||||
want: |
|
||||
1:1:LanceDB.VaguePhrases:'That matters' talks about the writing, not the subject. State the point directly.
|
||||
- name: leaves ordinary uses alone
|
||||
input: This page describes compaction. It is the operation that matters for video.
|
||||
want: ''
|
||||
- name: leaves specific descriptions and embedded phrases alone
|
||||
input: |
|
||||
This page is the entry point for the Python API. This page is the conceptual overview of the table model. The heading "That matters" is quoted here. Only the setting That matters is highlighted.
|
||||
want: ''
|
||||
- name: catches a filler opener after another sentence
|
||||
input: Names repeat. That matters for partner workloads.
|
||||
want: |
|
||||
1:15:LanceDB.VaguePhrases:'That matters' talks about the writing, not the subject. State the point directly.
|
||||
@@ -5,6 +5,8 @@ on:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- Cargo.toml
|
||||
- python/pyproject.toml
|
||||
- ci/check_cargo_lock.py
|
||||
- ci/check_sdist.py
|
||||
- ci/set_lance_version.py
|
||||
@@ -12,6 +14,8 @@ on:
|
||||
- .github/workflows/ci-scripts.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- Cargo.toml
|
||||
- python/pyproject.toml
|
||||
- ci/check_cargo_lock.py
|
||||
- ci/check_sdist.py
|
||||
- ci/set_lance_version.py
|
||||
@@ -30,5 +34,7 @@ jobs:
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- name: Install test dependencies
|
||||
run: python -m pip install packaging
|
||||
- name: Run tests
|
||||
run: python -m unittest discover -s ci/tests -v
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
name: CLI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
paths:
|
||||
- 'rust/lancedb/**'
|
||||
- 'Cargo.toml'
|
||||
- 'Cargo.lock'
|
||||
- '.github/workflows/cli.yml'
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
test:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-24.04, macos-14]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
with:
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
|
||||
- name: Install Linux prerequisites
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y protobuf-compiler libssl-dev clang
|
||||
- name: Install macOS prerequisites
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install protobuf
|
||||
- name: Build standalone CLI binary
|
||||
run: cargo build --locked --profile ci -p lancedb-cli --bin lancedb
|
||||
- name: Test standalone CLI
|
||||
run: cargo test --locked --profile ci -p lancedb-cli
|
||||
- name: Test SDK SQL
|
||||
run: cargo test --locked --profile ci -p lancedb --features remote --lib remote::sql
|
||||
- name: Lint CLI
|
||||
run: cargo clippy --locked --profile ci -p lancedb-cli --all-targets --all-features -- -D warnings
|
||||
- name: Check SDK without remote support
|
||||
# Feature-disabled SDK code has existing unused-code warnings; this is a compile check.
|
||||
env:
|
||||
RUSTFLAGS: ""
|
||||
run: cargo check --locked --profile ci -p lancedb --no-default-features --tests
|
||||
@@ -1,23 +1,18 @@
|
||||
name: Docs prose style
|
||||
|
||||
# Vale checks the mechanical rules in the LanceDB style guide
|
||||
# (lancedb/docs, STYLE.md) with the package pinned in .vale.ini. Its findings
|
||||
# are advisory annotations on the lines a pull request adds or changes and
|
||||
# never fail the job; an install, sync or configuration error still does.
|
||||
# Style findings are advisory; installation and configuration errors fail.
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "docs/web/**/*.mdx"
|
||||
- ".vale.ini"
|
||||
- ".github/vale/**"
|
||||
- ".github/workflows/docs-style.yml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
env:
|
||||
VALE_VERSION: 3.24.0
|
||||
VALE_SHA256: 867534ddb678abca7f214bc4706ead0922bd5252ffe8035fc227013f66c8b214
|
||||
|
||||
jobs:
|
||||
prose:
|
||||
name: Lint changed prose
|
||||
@@ -27,19 +22,11 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Vale
|
||||
run: |
|
||||
archive="vale_${VALE_VERSION}_Linux_64-bit.tar.gz"
|
||||
curl --fail --location --silent --show-error --output "$RUNNER_TEMP/$archive" \
|
||||
"https://github.com/vale-cli/vale/releases/download/v${VALE_VERSION}/$archive"
|
||||
echo "${VALE_SHA256} $RUNNER_TEMP/$archive" | sha256sum --check
|
||||
tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" vale
|
||||
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Annotate changed lines
|
||||
uses: vale-cli/vale-action@518a9136acc6e6668ce7c00d367051e0941e87ff # v3.0.0
|
||||
with:
|
||||
version: none
|
||||
version: '3.24.0'
|
||||
sync: false
|
||||
files: docs/web
|
||||
reporter: github-pr-annotations
|
||||
filter_mode: added
|
||||
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
- name: Install dependencies needed for ubuntu
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y protobuf-compiler libssl-dev
|
||||
rustup update && rustup default
|
||||
- name: Set up Python
|
||||
|
||||
@@ -28,9 +28,9 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-java:
|
||||
style-check:
|
||||
runs-on: ubuntu-24.04
|
||||
name: Build
|
||||
name: Style Check
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./java
|
||||
@@ -45,5 +45,24 @@ jobs:
|
||||
cache: "maven"
|
||||
- name: Java Style Check
|
||||
run: ./mvnw checkstyle:check
|
||||
|
||||
build-java:
|
||||
runs-on: ubuntu-24.04
|
||||
name: Build (Java ${{ matrix.java-version }})
|
||||
strategy:
|
||||
matrix:
|
||||
java-version: [11, 17]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./java
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
- name: Set up Java ${{ matrix.java-version }}
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: ${{ matrix.java-version }}
|
||||
cache: "maven"
|
||||
- name: Build and install
|
||||
run: ./mvnw clean install
|
||||
run: ./mvnw clean install -Dcheckstyle.skip=true
|
||||
|
||||
@@ -79,11 +79,15 @@ jobs:
|
||||
# that dir is missing, so create an empty one for lint-only runs.
|
||||
run: mkdir -p ../dist && pnpm install --frozen-lockfile && pnpm lint-ci
|
||||
linux:
|
||||
name: Linux (NodeJS ${{ matrix.node-version }})
|
||||
name: Linux (NodeJS ${{ matrix.node-version }}, ${{ matrix.features }})
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [ "22", "24", "26" ]
|
||||
features: [ "default" ]
|
||||
include:
|
||||
- node-version: "24"
|
||||
features: "experimental-functions"
|
||||
runs-on: "ubuntu-22.04"
|
||||
defaults:
|
||||
run:
|
||||
@@ -121,7 +125,7 @@ jobs:
|
||||
pnpm install --frozen-lockfile
|
||||
# No `--` separator: pnpm forwards it literally, which would
|
||||
# make napi-rs treat `--profile ci` as a cargo passthrough arg.
|
||||
pnpm build:debug --profile ci
|
||||
pnpm build:debug --profile ci --features ${{ matrix.features }}
|
||||
pnpm tsc
|
||||
- name: Setup examples
|
||||
working-directory: nodejs/examples
|
||||
|
||||
@@ -71,9 +71,9 @@ jobs:
|
||||
# https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile
|
||||
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian
|
||||
pre_build: |-
|
||||
set -e &&
|
||||
apt-get update &&
|
||||
apt-get install -y protobuf-compiler pkg-config &&
|
||||
set -e
|
||||
apt-get update
|
||||
apt-get install -y protobuf-compiler pkg-config
|
||||
# The base image (manylinux2014-cross) sets TARGET_CC to the old
|
||||
# GCC 4.8 cross-compiler. aws-lc-sys checks TARGET_CC before CC,
|
||||
# so it picks up GCC even though the napi-rs image sets CC=clang.
|
||||
@@ -84,10 +84,10 @@ jobs:
|
||||
host: ubuntu-2404-8x-x64
|
||||
features: fp16kernels
|
||||
pre_build: |-
|
||||
set -e &&
|
||||
sudo apt-get update &&
|
||||
sudo apt-get install -y protobuf-compiler pkg-config &&
|
||||
rustup target add x86_64-unknown-linux-musl &&
|
||||
set -e
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler pkg-config
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
export EXTRA_ARGS="-x"
|
||||
- target: aarch64-unknown-linux-gnu
|
||||
host: ubuntu-2404-8x-x64
|
||||
@@ -103,13 +103,13 @@ jobs:
|
||||
# linker process 7.0 -> 4.0 GiB (lancedb/sophon#7313).
|
||||
linker: /tmp/aarch64-lld-clang
|
||||
pre_build: |-
|
||||
set -e &&
|
||||
apt-get update &&
|
||||
apt-get install -y protobuf-compiler pkg-config &&
|
||||
export TARGET_CC=clang TARGET_CXX=clang++ &&
|
||||
set -e
|
||||
apt-get update
|
||||
apt-get install -y protobuf-compiler pkg-config
|
||||
export TARGET_CC=clang TARGET_CXX=clang++
|
||||
# The manylinux2014 sysroot has glibc 2.17 headers which lack
|
||||
# AT_HWCAP2 (added in Linux 3.17). Define it for aws-lc-sys.
|
||||
export CFLAGS="$CFLAGS -DAT_HWCAP2=26" &&
|
||||
export CFLAGS="$CFLAGS -DAT_HWCAP2=26"
|
||||
rustup target add aarch64-unknown-linux-gnu
|
||||
# Not `&&`-chained: in dash, errexit does not fire for a
|
||||
# non-final command in an `&&` list, so failures were ignored.
|
||||
@@ -136,10 +136,10 @@ jobs:
|
||||
lto: thin
|
||||
codegen_units: 16
|
||||
pre_build: |-
|
||||
set -e &&
|
||||
sudo apt-get update &&
|
||||
sudo apt-get install -y protobuf-compiler &&
|
||||
rustup target add aarch64-unknown-linux-musl &&
|
||||
set -e
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler
|
||||
rustup target add aarch64-unknown-linux-musl
|
||||
export EXTRA_ARGS="-x"
|
||||
name: build - ${{ matrix.settings.target }}
|
||||
runs-on: ${{ matrix.settings.host }}
|
||||
|
||||
@@ -15,6 +15,9 @@ on:
|
||||
- ci/check_cargo_lock.py
|
||||
- ci/check_sdist.py
|
||||
- python/pyproject.toml
|
||||
- python/Cargo.toml
|
||||
- python/vendor/**
|
||||
- rust/lancedb/Cargo.toml
|
||||
- Cargo.toml # Change in dependency frequently breaks builds
|
||||
- Cargo.lock
|
||||
|
||||
@@ -184,12 +187,14 @@ jobs:
|
||||
command: sdist
|
||||
working-directory: python
|
||||
args: --out dist
|
||||
# maturin ships the nodejs-only pins in Cargo.lock. Remove this step when
|
||||
# the pinned maturin fixes https://github.com/PyO3/maturin/issues/2609.
|
||||
# maturin ships pins used only by other workspace members in Cargo.lock.
|
||||
# Remove this step when the pinned maturin fixes
|
||||
# https://github.com/PyO3/maturin/issues/2609.
|
||||
- name: Sync Cargo.lock to the packaged workspace
|
||||
shell: bash
|
||||
run: |
|
||||
# A repo lock in sync with every manifest means the prune only drops pins.
|
||||
# A synced repo lock lets the prune drop packages and optional edges
|
||||
# without changing the remaining pins or adding dependency edges.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
mkdir "$RUNNER_TEMP/sdist-src"
|
||||
tar -xzf python/dist/lancedb-*.tar.gz -C "$RUNNER_TEMP/sdist-src"
|
||||
|
||||
@@ -122,6 +122,10 @@ jobs:
|
||||
run: |
|
||||
pip install --extra-index-url https://pypi.fury.io/lance-format/ --extra-index-url https://pypi.fury.io/lancedb/ -e .[tests,dev,embeddings]
|
||||
pip install mlx
|
||||
- name: Test remote torch data loader
|
||||
run: |
|
||||
python -c "import torch"
|
||||
pytest python/tests/test_torch.py::test_remote_permutation_dataloader_multiprocessing -q -rs
|
||||
- name: Doctest
|
||||
run: pytest --doctest-modules python/lancedb
|
||||
linux:
|
||||
@@ -162,7 +166,10 @@ jobs:
|
||||
- name: Delete wheels
|
||||
run: rm -rf target/wheels
|
||||
platform:
|
||||
name: "Mac"
|
||||
name: "Mac: ${{ matrix.features }}"
|
||||
strategy:
|
||||
matrix:
|
||||
features: ["default", "experimental-functions"]
|
||||
timeout-minutes: 30
|
||||
runs-on: macos-14
|
||||
defaults:
|
||||
@@ -188,7 +195,7 @@ jobs:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- uses: ./.github/workflows/build_mac_wheel
|
||||
with:
|
||||
args: --profile ci
|
||||
args: --profile ci --features ${{ matrix.features }}
|
||||
- uses: ./.github/workflows/run_tests
|
||||
# Make sure wheels are not included in the Rust cache
|
||||
- name: Delete wheels
|
||||
|
||||
+115
-11
@@ -11,6 +11,7 @@ on:
|
||||
- rust-toolchain.toml
|
||||
- deny.toml
|
||||
- rust/**
|
||||
- docs/web-tests/blob-v2/rs/**
|
||||
- nodejs/Cargo.toml
|
||||
- python/Cargo.toml
|
||||
- .github/workflows/rust.yml
|
||||
@@ -29,6 +30,63 @@ env:
|
||||
RUST_BACKTRACE: "1"
|
||||
|
||||
jobs:
|
||||
dependency-overrides:
|
||||
name: Downstream Lance override
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- name: Read the pinned Lance tag
|
||||
id: lance
|
||||
run: |
|
||||
python3 - <<'PYTHON'
|
||||
import os
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
manifest = tomllib.loads(Path("Cargo.toml").read_text())
|
||||
tag = manifest["workspace"]["dependencies"]["lance"]["tag"]
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
|
||||
output.write(f"tag={tag}\n")
|
||||
PYTHON
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: lance-format/lance
|
||||
ref: ${{ steps.lance.outputs.tag }}
|
||||
path: local-lance
|
||||
- name: Resolve a downstream workspace with a local Lance override
|
||||
run: |
|
||||
mkdir -p downstream/src
|
||||
touch downstream/src/lib.rs
|
||||
cat > downstream/Cargo.toml <<'TOML'
|
||||
[package]
|
||||
name = "lancedb-local-lance-consumer"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
lancedb = { path = "../rust/lancedb", default-features = false }
|
||||
lance-arrow = { path = "../local-lance/rust/lance-arrow" }
|
||||
|
||||
[patch."https://github.com/lance-format/lance.git"]
|
||||
lance-arrow = { path = "../local-lance/rust/lance-arrow" }
|
||||
TOML
|
||||
cargo metadata --manifest-path downstream/Cargo.toml --format-version 1 > downstream/graph.json
|
||||
python3 - <<'PYTHON'
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
graph = json.loads(Path("downstream/graph.json").read_text())
|
||||
packages = [p for p in graph["packages"] if p["name"] == "lance-arrow"]
|
||||
assert len(packages) == 1, [p["id"] for p in packages]
|
||||
assert Path(packages[0]["manifest_path"]).resolve() == Path(
|
||||
"local-lance/rust/lance-arrow/Cargo.toml"
|
||||
).resolve()
|
||||
PYTHON
|
||||
|
||||
lint:
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
@@ -165,6 +223,11 @@ jobs:
|
||||
run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests
|
||||
- name: Run examples
|
||||
run: cargo run --profile ci --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
|
||||
|
||||
remote:
|
||||
timeout-minutes: 30
|
||||
@@ -198,6 +261,8 @@ jobs:
|
||||
sudo apt update
|
||||
sudo apt install -y protobuf-compiler libssl-dev
|
||||
- uses: rui314/setup-mold@v1
|
||||
- name: Test the default local Functions gate
|
||||
run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked
|
||||
- name: Run remote tests
|
||||
run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests
|
||||
|
||||
@@ -245,12 +310,6 @@ jobs:
|
||||
include:
|
||||
- target: x86_64-pc-windows-msvc
|
||||
runner: windows-2022
|
||||
# windows-11-arm is a standard runner, so it is free on public repos.
|
||||
# Running natively lets the aarch64 tests actually execute -- this
|
||||
# job used to cross-compile them and then skip the test step, paying
|
||||
# full codegen and link cost for a compile check.
|
||||
- target: aarch64-pc-windows-msvc
|
||||
runner: windows-11-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
defaults:
|
||||
run:
|
||||
@@ -279,13 +338,50 @@ jobs:
|
||||
# dependency graph a second time.
|
||||
cargo test --profile ci --features aws,remote --locked --target ${{ matrix.target }}
|
||||
|
||||
# Run the aarch64 Windows tests only on main so PRs wait for a single
|
||||
# Windows platform. windows-11-arm is a standard runner, so it is free on
|
||||
# public repos. Running natively lets the aarch64 tests actually execute --
|
||||
# this job used to cross-compile them and then skip the test step, paying
|
||||
# full codegen and link cost for a compile check.
|
||||
windows-arm:
|
||||
# Keep the historical name so the check shows up as before on main.
|
||||
name: windows (aarch64-pc-windows-msvc, windows-11-arm)
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: windows-11-arm
|
||||
defaults:
|
||||
run:
|
||||
working-directory: rust/lancedb
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Set target
|
||||
run: rustup target add aarch64-pc-windows-msvc
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Restore everywhere, but only save from main. Per-PR saves are
|
||||
# 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: Build
|
||||
run: |
|
||||
$env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT
|
||||
cargo build --profile ci --features aws,remote --tests --locked --target aarch64-pc-windows-msvc
|
||||
- name: Run tests
|
||||
run: |
|
||||
$env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT
|
||||
# `--target` has to match the build step above. Without it cargo uses
|
||||
# target/ci/ rather than target/<triple>/ci/ and rebuilds the entire
|
||||
# dependency graph a second time.
|
||||
cargo test --profile ci --features aws,remote --locked --target aarch64-pc-windows-msvc
|
||||
|
||||
msrv:
|
||||
# Check the minimum supported Rust version
|
||||
name: MSRV Check - Rust v${{ matrix.msrv }}
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
msrv: ["1.94.0"] # This should match up with rust-version in Cargo.toml
|
||||
msrv: ["1.95.0"] # This should match up with rust-version in Cargo.toml
|
||||
env:
|
||||
# Need up-to-date compilers for kernels
|
||||
CC: clang-18
|
||||
@@ -308,10 +404,18 @@ jobs:
|
||||
# unreadable outside their own branch anyway, since GitHub scopes
|
||||
# caches to the creating ref.
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Downgrade dependencies
|
||||
# aws-smithy-types 1.6.1+ requires rustc 1.94.1
|
||||
run: cargo update -p aws-smithy-types --precise 1.5.0
|
||||
- name: Resolve MSRV-compatible dependencies
|
||||
# Resolve the AWS SDK and Smithy crates together: newer SDK releases
|
||||
# require newer Smithy versions, so downgrading only Smithy can fail.
|
||||
run: cargo +${{ matrix.msrv }} update --config 'resolver.incompatible-rust-versions="fallback"'
|
||||
- name: Keep Xet dependencies compatible with the MSRV
|
||||
# Xet 1.7 does not declare its MSRV, but requires sysinfo 0.39 (Rust 1.95).
|
||||
# Downgrade parents before their dependencies to satisfy their constraints.
|
||||
run: |
|
||||
for crate in hf-xet xet-data xet-client xet-core-structures xet-runtime; do
|
||||
cargo +${{ matrix.msrv }} update -p "$crate" --precise 1.6.0
|
||||
done
|
||||
- name: cargo +${{ matrix.msrv }} check
|
||||
env:
|
||||
RUSTUP_TOOLCHAIN: ${{ matrix.msrv }}
|
||||
run: cargo check --profile ci --workspace --tests --benches --all-features
|
||||
run: cargo check --locked --profile ci --workspace --tests --benches --all-features
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Prose style for the pages in docs/web: the shared LanceDB package, pinned by
|
||||
# release. The rules and guide live in lancedb/docs (STYLE.md and vale/).
|
||||
# Run `vale sync` once, then `vale docs/web/<page>.mdx`.
|
||||
StylesPath = .vale/styles
|
||||
Packages = https://github.com/lancedb/docs/releases/download/vale-lancedb-v0.1.0/LanceDB.zip
|
||||
StylesPath = .github/vale/styles
|
||||
MinAlertLevel = suggestion
|
||||
|
||||
[*.mdx]
|
||||
BasedOnStyles = LanceDB
|
||||
Vale.Repetition = warning
|
||||
|
||||
@@ -102,8 +102,8 @@ TypeScript bindings changes:
|
||||
|
||||
1. Add napi-rs method binding on `Table` in `nodejs/src/table.rs`.
|
||||
2. Run `pnpm build` to generate TypeScript definitions.
|
||||
3. Add typescript method on abstract class `Table` in `nodejs/src/table.ts`.
|
||||
4. Add concrete method on `LocalTable` class in `nodejs/src/native_table.ts`.
|
||||
3. Add typescript method on abstract class `Table` in `nodejs/lancedb/table.ts`.
|
||||
4. Add concrete method on `LocalTable` class in `nodejs/lancedb/table.ts`.
|
||||
* Note: despite the name, this class is also used for remote tables.
|
||||
5. Add test in `nodejs/__test__/table.test.ts`.
|
||||
6. Run `pnpm run docs` to generate TypeScript documentation.
|
||||
|
||||
+91
-59
@@ -72,96 +72,128 @@ 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`: the open-source pages of [docs.lancedb.com](https://docs.lancedb.com)
|
||||
* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Distributed
|
||||
* `docs/web-tests`: the tests the documentation's code examples are extracted from
|
||||
|
||||
## Documentation
|
||||
|
||||
The open-source pages of [docs.lancedb.com](https://docs.lancedb.com) live in
|
||||
`docs/web`, so a change to behaviour and the change to the page describing it
|
||||
belong in the same pull request.
|
||||
Update the docs in the same pull request as the behavior they describe. You can
|
||||
merge docs before a feature launches; keep the unfinished material hidden until
|
||||
it is ready for readers.
|
||||
|
||||
Preview them locally — this serves `docs/web` on its own, with no other checkout:
|
||||
### Choose the right place
|
||||
|
||||
- `docs/web/` holds website guides for LanceDB Embedded and the APIs used by both
|
||||
Embedded and Distributed.
|
||||
- `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.
|
||||
Put Enterprise-specific deployment and operating instructions in the Enterprise
|
||||
documentation.
|
||||
|
||||
Some pages are placeholders that the website build replaces with an Enterprise
|
||||
page. Changes to a placeholder won't appear on the combined site. Put
|
||||
instructions that both products need on a separate page and link to it.
|
||||
|
||||
### Preview and check your change
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
npm i -g mint # https://mintlify.com/docs/installation
|
||||
cd docs/web && mint dev
|
||||
npm i -g mint@4.2.888
|
||||
(cd docs/web && mint dev)
|
||||
```
|
||||
|
||||
Wording, names and punctuation follow the
|
||||
[LanceDB style guide](https://github.com/lancedb/docs/blob/main/STYLE.md).
|
||||
[Vale](https://vale.sh) checks part of it, and pull requests show its
|
||||
suggestions on the lines they change. To check a page yourself:
|
||||
This previews this checkout, including your uncommitted changes. It doesn't
|
||||
include the other documentation sources or render the availability labels.
|
||||
Use the [combined preview](https://github.com/lancedb/docs#development) when
|
||||
checking Enterprise replacements or links to pages from another source.
|
||||
Staging shows saved release editions, so it won't show a new source change
|
||||
just because that change merged.
|
||||
|
||||
Follow the [style guide](https://github.com/lancedb/docs/blob/main/STYLE.md).
|
||||
[Vale](https://vale.sh) checks wording, names and punctuation using the
|
||||
[bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions
|
||||
on the lines they change. With Vale 3.24.0 installed, check a page locally with:
|
||||
|
||||
```bash
|
||||
vale sync && vale docs/web/indexing/vector-index.mdx
|
||||
vale docs/web/indexing/vector-index.mdx
|
||||
```
|
||||
|
||||
This repository holds a page at every path the site publishes, so the whole
|
||||
navigation resolves locally. Enterprise pages exist here as open-source pages --
|
||||
what the capability is, and what the embedded form does instead. A separate
|
||||
private repository supplies the fuller version of each, which replaces the page
|
||||
at the same path when the published site is assembled.
|
||||
Keep existing `{#anchor}` values when changing headings, so links to those
|
||||
sections keep working. Give new headings stable anchors. For links in rendered
|
||||
components, write the path directly, such as `href="/quickstart"`, and spell out
|
||||
attributes rather than using property spreads. That lets versioned docs keep
|
||||
links inside the selected edition. Code examples aren't subject to this rule.
|
||||
|
||||
Four things to know before editing:
|
||||
### Code examples
|
||||
|
||||
**Code examples are not written into the pages.** They live in real tests under
|
||||
`docs/web-tests/{py,ts,rs}`, are extracted into `docs/web/snippets/`, and are
|
||||
imported by the pages. Edit the test, then regenerate from the repository root:
|
||||
Edit the test that produces an example, then regenerate its snippet. The
|
||||
sources are `docs/web-tests/{py,ts,rs}`, `docs/web-tests/blob-v2/{py,ts,rs}` and
|
||||
`rust/lancedb/tests`. Run this from the repository root:
|
||||
|
||||
```bash
|
||||
uv run docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs -o docs/web/snippets
|
||||
uv run docs/web-tests/mdx_snippets_gen.py \
|
||||
-s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \
|
||||
-s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \
|
||||
-s rust/lancedb/tests -o docs/web/snippets
|
||||
```
|
||||
|
||||
Review the diff before committing: a few modules currently regenerate with
|
||||
unrelated changes, so commit only the snippets for the examples you changed.
|
||||
Run the tests for the examples you changed; generating a snippet doesn't run
|
||||
its example. Review the generated diff and commit only the relevant snippets
|
||||
with their tests. Don't assume the PR checks execute every documentation
|
||||
example.
|
||||
|
||||
Run the Python, TypeScript and Rust examples in `docs/web-tests/{py,ts,rs}`
|
||||
locally before submitting the change. These examples are not yet wired into
|
||||
pull-request CI; that integration remains follow-up work.
|
||||
### Say where a feature works
|
||||
|
||||
**Every heading carries an explicit `{#anchor}`.** Those anchors are how the
|
||||
Enterprise pages attach their additions to the right section, so they are
|
||||
assigned once and never regenerated. Leave an existing anchor alone even when
|
||||
you reword the heading above it; only new headings need a new one.
|
||||
|
||||
**A page can declare where it applies.** Its frontmatter says whether LanceDB
|
||||
OSS and LanceDB Enterprise support the feature: use only `available` or
|
||||
`unavailable`, and one sentence that explains its scope. Availability describes
|
||||
product support, not whether a particular deployment has enabled or configured
|
||||
the feature. A supported feature stays `available` when it requires setup, a
|
||||
supported SDK or server version, or has differences between offerings. State
|
||||
those requirements in the summary or the relevant section, including unsupported
|
||||
subfeatures. Do not use `varies`, infer support from an unknown status, or mark an
|
||||
absent capability available. Narrow a page to the capability it actually covers
|
||||
when necessary. For example:
|
||||
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:
|
||||
|
||||
```yaml
|
||||
availability:
|
||||
oss: unavailable
|
||||
enterprise: available
|
||||
summary: >-
|
||||
Requests to a deployment carry an API key or an OAuth token. Embedded
|
||||
LanceDB has no server to sign in to.
|
||||
These sign-in instructions apply to LanceDB Enterprise. LanceDB
|
||||
Embedded has no server to sign in to.
|
||||
```
|
||||
|
||||
The assembled site renders this as a label above the page's content and as a
|
||||
sidebar tag when only one offering has the feature. Do not also open the page
|
||||
with a badge of its own, and keep a qualification that only one section needs
|
||||
in that section's text. A `mint dev` preview of `docs/web` alone renders
|
||||
neither the labels nor the tags.
|
||||
Check these claims with the feature owner. Don't use `varies`, treat an API
|
||||
stub as working support, or mark a supported feature unavailable just because
|
||||
it needs configuration. If one label can't describe the whole page accurately,
|
||||
make the page's scope narrower and explain the differences.
|
||||
|
||||
**A feature can be documented before its release.** List a draft page in
|
||||
`docs/web/.mintignore`, keep it out of the navigation in `docs.json`, and do not
|
||||
link to it from published pages. Wrap a draft section in an MDX comment,
|
||||
`{/* ... */}`, whose first line names the release, such as
|
||||
`Draft for the Feature X release.` Keep draft table rows and list items in a
|
||||
comment below the table or list, since a comment between rows or items breaks
|
||||
it. Drafts are hidden from readers but stay in the source, and availability does
|
||||
not change what is published. At release, remove the comments and the
|
||||
`.mintignore` entries, and restore the navigation and links. See
|
||||
Assembly turns this declaration into a page label and, for a feature supported
|
||||
by only one product, a sidebar tag. Don't add those badges by hand. Availability
|
||||
labels do not hide unreleased content.
|
||||
|
||||
### Write docs before launch
|
||||
|
||||
You don't need to hold a documentation PR until launch. Use these controls:
|
||||
|
||||
- For a whole page, add its path to `docs/web/.mintignore`. Leave it out of
|
||||
`docs/web/docs.json`, redirects and links from published pages. Removing a
|
||||
sidebar entry alone doesn't hide a page.
|
||||
- For a section, wrap it in an MDX comment, `{/* ... */}`, with a note such as
|
||||
`Draft for the Feature X release.` Put draft table rows and list items in a
|
||||
comment below the table or list, not between entries.
|
||||
|
||||
Drafts remain in the source. Use them to avoid advertising an unfinished
|
||||
feature, not to keep information confidential. See
|
||||
[Writing docs before release](https://github.com/lancedb/docs#writing-docs-before-release)
|
||||
in the documentation repository's README for previews and release checks.
|
||||
for examples and how to preview a draft.
|
||||
|
||||
Before the intended release, remove the draft controls, restore the navigation
|
||||
and links, and check the result. Those changes must be in the source commit the
|
||||
edition uses. A later change to `main` doesn't update an edition already saved.
|
||||
For a mistake in an existing edition, fix the source and request a
|
||||
[recorded correction](https://github.com/lancedb/docs#correcting-a-saved-edition).
|
||||
|
||||
## Release process
|
||||
|
||||
|
||||
Generated
+965
-308
File diff suppressed because it is too large
Load Diff
+50
-35
@@ -1,5 +1,11 @@
|
||||
[workspace]
|
||||
members = ["rust/lancedb", "nodejs", "python"]
|
||||
members = [
|
||||
"rust/lancedb/cli",
|
||||
"rust/lancedb",
|
||||
"nodejs",
|
||||
"python",
|
||||
"docs/web-tests/blob-v2/rs",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
@@ -10,60 +16,66 @@ repository = "https://github.com/lancedb/lancedb"
|
||||
description = "Serverless, low-latency vector database for AI applications"
|
||||
keywords = ["lancedb", "lance", "database", "vector", "search"]
|
||||
categories = ["database-implementations"]
|
||||
rust-version = "1.94.0"
|
||||
rust-version = "1.95.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
lance = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-core = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datagen = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-file = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-io = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-index = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-linalg = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace-impls = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-table = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-testing = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datafusion = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-arrow = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
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" }
|
||||
lancedb = { path = "rust/lancedb", default-features = false }
|
||||
ahash = "0.8"
|
||||
anyhow = "1"
|
||||
# Note that this one does not include pyarrow
|
||||
arrow = { version = "58.0.0", optional = false }
|
||||
arrow-array = "58.0.0"
|
||||
arrow-buffer = "58.0.0"
|
||||
arrow-data = "58.0.0"
|
||||
arrow-ipc = "58.0.0"
|
||||
arrow-ord = "58.0.0"
|
||||
arrow-schema = "58.0.0"
|
||||
arrow-select = "58.0.0"
|
||||
arrow-cast = "58.0.0"
|
||||
arrow-flight = { version = "58.0.0", features = ["flight-sql-experimental"] }
|
||||
arrow = { version = "59.2.0", optional = false }
|
||||
arrow-array = "59.2.0"
|
||||
arrow-buffer = "59.2.0"
|
||||
arrow-data = "59.2.0"
|
||||
arrow-ipc = "59.2.0"
|
||||
arrow-ord = "59.2.0"
|
||||
arrow-schema = "59.2.0"
|
||||
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"
|
||||
base64 = "0.22"
|
||||
bytes = "1"
|
||||
datafusion = { version = "54.0.0", default-features = false }
|
||||
datafusion-catalog = "54.0.0"
|
||||
datafusion-common = { version = "54.0.0", default-features = false }
|
||||
datafusion-execution = "54.0.0"
|
||||
datafusion-expr = "54.0.0"
|
||||
datafusion-functions = "54.0.0"
|
||||
datafusion-physical-plan = "54.0.0"
|
||||
datafusion-physical-expr = "54.0.0"
|
||||
datafusion-sql = "54.0.0"
|
||||
datafusion = { version = "55.0.0", default-features = false }
|
||||
datafusion-catalog = "55.0.0"
|
||||
datafusion-common = { version = "55.0.0", default-features = false }
|
||||
datafusion-execution = "55.0.0"
|
||||
datafusion-expr = "55.0.0"
|
||||
datafusion-functions = "55.0.0"
|
||||
datafusion-physical-plan = "55.0.0"
|
||||
datafusion-physical-expr = "55.0.0"
|
||||
datafusion-sql = "55.0.0"
|
||||
env_logger = "0.11"
|
||||
half = { "version" = "2.7.1", default-features = false, features = [
|
||||
"num-traits",
|
||||
] }
|
||||
futures = "0.3"
|
||||
hf-hub = { version = "0.4.1", default-features = false }
|
||||
http = "1"
|
||||
log = "0.4"
|
||||
metrics = "0.24"
|
||||
metrics-util = "0.19"
|
||||
moka = { version = "0.12", features = ["future"] }
|
||||
object_store = "0.14.1"
|
||||
pin-project = "1.0.7"
|
||||
prost = "0.14"
|
||||
rand = "0.9"
|
||||
snafu = "0.8"
|
||||
url = "2"
|
||||
@@ -73,9 +85,12 @@ regex = "1.10"
|
||||
semver = "1.0.25"
|
||||
serde = "1"
|
||||
serde_json = { version = "1", features = ["preserve_order"] }
|
||||
serial_test = "3"
|
||||
sha2 = "0.10"
|
||||
tempfile = "3.5.0"
|
||||
tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] }
|
||||
tonic = { version = "0.14", features = ["tls-native-roots", "tls-aws-lc"] }
|
||||
tracing = "0.1"
|
||||
uuid = { version = "1.7.0", features = ["v4", "v7"] }
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||
|
||||
|
||||
@@ -45,8 +45,8 @@ LanceDB is a central location where developers can build, train and analyze thei
|
||||
- **Advanced Features**: Zero-copy, automatic versioning, manage versions of your data without needing extra infrastructure. GPU support in building vector index.
|
||||
|
||||
### **Products**:
|
||||
- **Open Source & Local**: 100% open source, runs locally or in your cloud. No vendor lock-in.
|
||||
- **Cloud and Enterprise**: Production-scale vector search with no servers to manage. Complete data sovereignty and security.
|
||||
- **LanceDB Embedded (open source)**: 100% open source, runs in your application's process; your data can live on local disk or in object storage. No vendor lock-in.
|
||||
- **LanceDB Enterprise**: Production-scale distributed search, indexing, and maintenance. Plus, complete data sovereignty and security.
|
||||
|
||||
### **Ecosystem**:
|
||||
- **Columnar Storage**: Built on the Lance columnar format for efficient storage and analytics.
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
"""Fail if pruning Cargo.lock did more than remove packages and the edges to them.
|
||||
"""Fail if pruning Cargo.lock changes pins or adds dependency edges.
|
||||
|
||||
Removing workspace members can disable optional dependency edges even when
|
||||
their target packages remain in use elsewhere in the packaged workspace.
|
||||
|
||||
Usage: python ci/check_cargo_lock.py <lock-before> <lock-after>
|
||||
"""
|
||||
@@ -45,7 +48,7 @@ def main() -> None:
|
||||
for package, deps in edges_after.items():
|
||||
if package not in edges_before:
|
||||
errors.append(f"added or changed {package}")
|
||||
elif deps != edges_before[package] - removed:
|
||||
elif not deps <= edges_before[package]:
|
||||
errors.append(f"dependencies of {package[:2]} changed")
|
||||
if errors:
|
||||
sys.exit("error: the prune changed Cargo.lock:\n" + "\n".join(errors))
|
||||
|
||||
@@ -2,6 +2,8 @@ import argparse
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
LANCE_GIT_URL = "https://github.com/lance-format/lance.git"
|
||||
|
||||
@@ -148,6 +150,18 @@ def update_cargo_toml(line_updater):
|
||||
with open("Cargo.toml", "w") as f:
|
||||
f.writelines(new_lines)
|
||||
|
||||
core_manifest = Path("rust/lancedb/Cargo.toml")
|
||||
if core_manifest.exists():
|
||||
lines = core_manifest.read_text().splitlines(keepends=True)
|
||||
for index, line in enumerate(lines):
|
||||
if line.startswith("lance-arrow ="):
|
||||
updated = tomllib.loads(line_updater(line))["lance-arrow"]
|
||||
config = {"version": updated} if isinstance(updated, str) else updated
|
||||
if "path" in config:
|
||||
config["path"] = "../../" + config["path"]
|
||||
lines[index] = dict_to_toml_line("lance-arrow", config)
|
||||
core_manifest.write_text("".join(lines))
|
||||
|
||||
|
||||
def set_stable_version(version: str):
|
||||
"""
|
||||
|
||||
@@ -37,14 +37,15 @@ APP = package("app", "1.0.0", ["libc", "untrusted"], source=None)
|
||||
|
||||
|
||||
class CheckCargoLockTest(unittest.TestCase):
|
||||
def run_check(self, after, header="version = 4\n\n"):
|
||||
def run_check(self, after, header="version = 4\n\n", before=BEFORE):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
before_path = Path(tmp, "before.lock")
|
||||
after_path = Path(tmp, "after.lock")
|
||||
before_path.write_text(BEFORE)
|
||||
before_path.write_text(before)
|
||||
after_path.write_text(header + after)
|
||||
return subprocess.run(
|
||||
[sys.executable, SCRIPT, before_path, after_path],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
@@ -81,9 +82,36 @@ class CheckCargoLockTest(unittest.TestCase):
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("dependencies of ('libc'", result.stderr)
|
||||
|
||||
def test_removed_dependency_fails(self):
|
||||
def test_removed_dependency_passes(self):
|
||||
app = package("app", "1.0.0", ["untrusted"], source=None)
|
||||
result = self.run_check(app + LIBC + UNTRUSTED)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_disabled_optional_dependency_still_used_elsewhere_passes(self):
|
||||
# Removing the CLI disables axum's tracing feature, but other SDK
|
||||
# dependencies still need tracing. Its package therefore stays pinned.
|
||||
app = package("app", "1.0.0", ["axum", "tracing"], source=None)
|
||||
tracing = package("tracing", "0.1.44")
|
||||
before = (
|
||||
"version = 4\n\n" + app + package("axum", "0.8.9", ["tracing"]) + tracing
|
||||
)
|
||||
after = app + package("axum", "0.8.9") + tracing
|
||||
result = self.run_check(after, before=before)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_dependency_redirected_to_an_existing_version_fails(self):
|
||||
before = (
|
||||
"version = 4\n\n"
|
||||
+ package("app", "1.0.0", ["untrusted 0.7.1"], source=None)
|
||||
+ package("untrusted", "0.7.1")
|
||||
+ UNTRUSTED
|
||||
)
|
||||
after = (
|
||||
package("app", "1.0.0", ["untrusted 0.9.0"], source=None)
|
||||
+ package("untrusted", "0.7.1")
|
||||
+ UNTRUSTED
|
||||
)
|
||||
result = self.run_check(after, before=before)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("dependencies of ('app'", result.stderr)
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import tomllib
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from packaging.requirements import Requirement
|
||||
from packaging.version import Version
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class PythonDependenciesTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
with (REPO_ROOT / "python/pyproject.toml").open("rb") as f:
|
||||
self.project = tomllib.load(f)["project"]
|
||||
self.pylance = Requirement(self.project["optional-dependencies"]["pylance"][0])
|
||||
|
||||
def test_pylance_extra_excludes_older_lance_majors(self):
|
||||
with (REPO_ROOT / "Cargo.toml").open("rb") as f:
|
||||
lance = tomllib.load(f)["workspace"]["dependencies"]["lance"]
|
||||
if "version" not in lance:
|
||||
self.skipTest("Local Lance checkout has no version requirement")
|
||||
major = Version(lance["version"].lstrip("=")).major
|
||||
for older_major in range(major):
|
||||
for suffix in (".0.0", ".0.0b6", ".999.999"):
|
||||
version = f"{older_major}{suffix}"
|
||||
with self.subTest(version=version):
|
||||
self.assertFalse(
|
||||
self.pylance.specifier.contains(version, prereleases=True),
|
||||
f"The pylance extra must exclude Lance {version}; "
|
||||
f"the bundled Lance is major {major}",
|
||||
)
|
||||
|
||||
def test_pylance_extra_accepts_tested_version(self):
|
||||
requirements = [
|
||||
Requirement(dep) for dep in self.project["optional-dependencies"]["tests"]
|
||||
]
|
||||
tested = next(dep for dep in requirements if dep.name == "pylance")
|
||||
pin = next(spec for spec in tested.specifier if spec.operator == "==")
|
||||
self.assertTrue(
|
||||
self.pylance.specifier.contains(pin.version, prereleases=True),
|
||||
f"The tests and pylance extras must be installable together: {tested}",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,6 +4,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import tomllib
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -83,6 +84,13 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], "
|
||||
with self.subTest(version=version), tempfile.TemporaryDirectory() as tmp:
|
||||
workdir = Path(tmp)
|
||||
(workdir / "Cargo.toml").write_text(CARGO_TOML)
|
||||
core_manifest = workdir / "rust/lancedb/Cargo.toml"
|
||||
core_manifest.parent.mkdir(parents=True)
|
||||
core_manifest.write_text(
|
||||
"[dependencies]\nlance-arrow = { "
|
||||
'version = "=1.0.0", git = "https://github.com/lance-format/lance.git", '
|
||||
'tag = "v1.0.0" }\narrow.workspace = true\n'
|
||||
)
|
||||
command_log = workdir / "commands.log"
|
||||
fake_bin = workdir / "bin"
|
||||
fake_bin.mkdir()
|
||||
@@ -111,6 +119,26 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], "
|
||||
+ updated_dependencies
|
||||
+ UNTOUCHED_DEPENDENCIES,
|
||||
)
|
||||
core = tomllib.loads(core_manifest.read_text())["dependencies"]
|
||||
dependency = core["lance-arrow"]
|
||||
if isinstance(dependency, str):
|
||||
dependency = {"version": dependency}
|
||||
if version == "local":
|
||||
self.assertEqual(
|
||||
dependency["path"], "../../../lance/rust/lance-arrow"
|
||||
)
|
||||
else:
|
||||
expected_version = {
|
||||
"stable": "9.9.9",
|
||||
"preview": "10.0.0-beta.3",
|
||||
}.get(version, version.removeprefix("v"))
|
||||
self.assertEqual(dependency["version"], f"={expected_version}")
|
||||
if "beta" in expected_version:
|
||||
self.assertEqual(dependency["git"], LANCE_GIT_URL)
|
||||
self.assertEqual(dependency["tag"], f"v{expected_version}")
|
||||
else:
|
||||
self.assertNotIn("git", dependency)
|
||||
self.assertEqual(core["arrow"], {"workspace": True})
|
||||
commands = command_log.read_text().splitlines()
|
||||
for command in expected_commands:
|
||||
self.assertTrue(
|
||||
|
||||
@@ -110,8 +110,30 @@ ignore = [
|
||||
# compact_str/smol_str, so clearing this requires polars to migrate.
|
||||
# https://rustsec.org/advisories/RUSTSEC-2026-0249
|
||||
{ id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" },
|
||||
# crypto-bigint < 0.7.6: timing side-channels in constant-time ops,
|
||||
# incl. subtraction, zero counting, division and Montgomery multiplication.
|
||||
# Reached only through aws-sdk-s3 sigv4a -> aws-sigv4 (p256/ecdsa); signed
|
||||
# requests carry the SigV4a credential-derived key. The patched 0.7.6 was
|
||||
# published 2026-10-23, but no published aws-sigv4 release uses it yet
|
||||
# (latest 1.6.3 pins crypto-bigint ^0.5), so clearing requires smithy-rs to
|
||||
# ship an updated aws-sigv4.
|
||||
# https://rustsec.org/advisories/RUSTSEC-2026-0387
|
||||
{ id = "RUSTSEC-2026-0387", reason = "crypto-bigint via aws-sigv4 (sigv4a); no fixed upstream aws-sigv4 release yet" },
|
||||
|
||||
# zstd: arrow-ipc 58.x pins zstd ^0.13, while the patches require zstd
|
||||
# >=0.14.3 and zstd-safe >=8.2.0. Arrow 59+ updates the dependency, but it
|
||||
# cannot be used until DataFusion and Lance move to the matching Arrow line.
|
||||
# LanceDB uses zstd::bulk through arrow-ipc and does not use the affected
|
||||
# with_context, seekable, or decompress_stream APIs.
|
||||
# https://rustsec.org/advisories/RUSTSEC-2026-0391
|
||||
# https://rustsec.org/advisories/RUSTSEC-2026-0398
|
||||
# https://rustsec.org/advisories/RUSTSEC-2026-0403
|
||||
{ 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" },
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Licenses: only allow licenses we've reviewed as compatible with Apache-2.0.
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -167,7 +189,9 @@ wildcards = "deny"
|
||||
# `[workspace.dependencies]` table: any crate used by more than one member must
|
||||
# go through `workspace = true`, and entries nothing uses are an error. This
|
||||
# keeps versions from drifting between the core crate and the bindings.
|
||||
workspace-dependencies = { duplicates = "deny", unused = "deny" }
|
||||
# Python bundles a patched path crate while the Rust SDK uses the overridable
|
||||
# upstream source. Check shared external declarations, not these path bindings.
|
||||
workspace-dependencies = { duplicates = "deny", unused = "deny", include-path-dependencies = false }
|
||||
# Internal workspace crates reference each other via `path = "..."`, which
|
||||
# cargo-deny sees as a wildcard version. That's fine for private workspace
|
||||
# members (not published to crates.io), so allow it specifically for paths.
|
||||
|
||||
+7
-4
@@ -1,10 +1,13 @@
|
||||
# LanceDB Documentation
|
||||
|
||||
LanceDB docs are available at [docs.lancedb.com](https://docs.lancedb.com).
|
||||
For website guides in `docs/web`, start with
|
||||
[Documentation in CONTRIBUTING.md](../CONTRIBUTING.md#documentation). That
|
||||
covers editing pages, generated examples, previews, availability and drafts.
|
||||
|
||||
The SDK docs are built and deployed automatically by [Github Actions](../.github/workflows/docs.yml)
|
||||
whenever a commit is pushed to the `main` branch. So it is possible for the docs to show
|
||||
unreleased features.
|
||||
This page covers the SDK reference in `docs/src`, built with MkDocs. Its
|
||||
[GitHub Actions workflow](../.github/workflows/docs.yml) builds and deploys on
|
||||
pushes to `main`, so it can include unreleased APIs. That is separate from the
|
||||
release editions of the Mintlify website.
|
||||
|
||||
## Building the docs
|
||||
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
version: 1.0.0
|
||||
title: LanceDB Cloud API
|
||||
title: LanceDB REST API
|
||||
description: |
|
||||
LanceDB Cloud API is a RESTful API that allows users to access and modify data stored in LanceDB Cloud.
|
||||
The LanceDB REST API is a RESTful API that allows users to access and modify data stored in LanceDB Enterprise or LanceDB Cloud (legacy).
|
||||
Table actions are considered temporary resource creations and all use POST method.
|
||||
contact:
|
||||
name: LanceDB support
|
||||
@@ -12,7 +12,7 @@ info:
|
||||
|
||||
servers:
|
||||
- url: https://{db}.{region}.api.lancedb.com
|
||||
description: LanceDB Cloud REST endpoint.
|
||||
description: LanceDB Cloud (legacy) REST endpoint. For LanceDB Enterprise, use your deployment's endpoint.
|
||||
variables:
|
||||
db:
|
||||
default: ""
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Java SDK
|
||||
|
||||
The LanceDB Java SDK provides a convenient way to interact with LanceDB Cloud and Enterprise deployments using the Lance REST Namespace API.
|
||||
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 for LanceDB remote database that connects to LanceDB Cloud and Enterprise.
|
||||
Local database support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress.
|
||||
The Java SDK currently only works with LanceDB Distributed, connecting 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,13 +14,13 @@ Add the following dependency to your `pom.xml`:
|
||||
<dependency>
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-core</artifactId>
|
||||
<version>0.41.0-beta.9</version>
|
||||
<version>0.41.0-beta.17</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Connecting to LanceDB Cloud
|
||||
### Connecting to LanceDB Cloud (legacy)
|
||||
|
||||
```java
|
||||
import com.lancedb.LanceDbNamespaceClientBuilder;
|
||||
@@ -51,8 +51,8 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder()
|
||||
|--------|-------------|----------|
|
||||
| `apiKey(String)` | LanceDB API key | Yes |
|
||||
| `database(String)` | Database name | Yes |
|
||||
| `endpoint(String)` | Custom endpoint URL for Enterprise deployments | No |
|
||||
| `region(String)` | AWS region (default: "us-east-1") | No |
|
||||
| `endpoint(String)` | Custom endpoint URL for LanceDB Enterprise deployments | No |
|
||||
| `region(String)` | LanceDB Cloud (legacy) region (default: "us-east-1") | No |
|
||||
| `config(String, String)` | Additional configuration parameters | No |
|
||||
|
||||
### Opening a Table with Vended Credentials
|
||||
|
||||
@@ -50,6 +50,19 @@ pnpm install
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Local SQL computed columns and materialized-view creation/refresh are experimental
|
||||
and disabled in published packages. To opt in when building from this directory:
|
||||
|
||||
```shell
|
||||
pnpm build:debug --features experimental-functions
|
||||
pnpm tsc
|
||||
pnpm test --runInBand table.test.ts materialized_view.test.ts
|
||||
```
|
||||
|
||||
Rebuild without `--features experimental-functions` to test the default package.
|
||||
The tests detect the compiled feature; remote operations, metadata protections,
|
||||
and ordinary eager `addColumns` transforms remain available in both builds.
|
||||
|
||||
Lint:
|
||||
|
||||
```shell
|
||||
|
||||
@@ -469,29 +469,34 @@ where(predicate): this
|
||||
|
||||
A filter statement to be applied to this query.
|
||||
|
||||
The filter should be supplied as an SQL query string. For example:
|
||||
The filter may be an SQL query string or an expression built with `col`,
|
||||
which preserves case-sensitive column names. For example:
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **predicate**: `string`
|
||||
* **predicate**: `string` \| [`Expr`](Expr.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`this`
|
||||
|
||||
#### Example
|
||||
#### Examples
|
||||
|
||||
```ts
|
||||
x > 10
|
||||
y > 0 AND y < 100
|
||||
x > 5 OR y = 'test'
|
||||
```
|
||||
|
||||
```ts
|
||||
table.query().where(col("firstName").eq("Alice"));
|
||||
```
|
||||
|
||||
Filtering performance can often be improved by creating a scalar index
|
||||
on the filter column(s).
|
||||
|
||||
Calling this multiple times combines the filters with a logical AND rather
|
||||
than replacing the previous filter.
|
||||
```
|
||||
|
||||
#### Inherited from
|
||||
|
||||
|
||||
@@ -70,7 +70,9 @@ Create a database, or open an existing database when existOk is true.
|
||||
dropDatabase(name, options): Promise<void>
|
||||
```
|
||||
|
||||
Drop an empty database. The server rejects nonempty databases.
|
||||
Drop a database. A nonempty database is an error unless `cascade` is set,
|
||||
which drops everything in it first; the name stays taken until the server
|
||||
finishes cleaning up their storage.
|
||||
|
||||
#### Parameters
|
||||
|
||||
@@ -78,6 +80,8 @@ Drop an empty database. The server rejects nonempty databases.
|
||||
|
||||
* **options** = `{}`
|
||||
|
||||
* **options.cascade?**: `boolean`
|
||||
|
||||
* **options.ignoreMissing?**: `boolean`
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -180,6 +180,10 @@ abstract createMaterializedView(
|
||||
|
||||
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.
|
||||
|
||||
The view is populated before creation returns. Set `withNoData` to create
|
||||
only its definition and empty backing table. The view is a normal table:
|
||||
it can be queried, indexed and searched, and it appears in `tableNames`.
|
||||
@@ -432,8 +436,8 @@ abstract dropMaterializedView(name, namespacePath?): Promise<void>
|
||||
|
||||
Drop the materialized view named `name`.
|
||||
|
||||
The view may become unavailable before physical cleanup finishes. Use
|
||||
[dropMaterializedViewAsync](Connection.md#dropmaterializedviewasync) to retain and wait for the cleanup job.
|
||||
Remote drops wait for the SQL command to remove the catalog binding.
|
||||
Physical cleanup continues in the background.
|
||||
|
||||
Rejects a table that exists but is not a materialized view.
|
||||
|
||||
@@ -455,8 +459,9 @@ Rejects a table that exists but is not a materialized view.
|
||||
abstract dropMaterializedViewAsync(name, namespacePath?): Promise<Job>
|
||||
```
|
||||
|
||||
Start dropping the materialized view named `name` and return its cleanup
|
||||
job without waiting for completion.
|
||||
Start dropping the materialized view named `name` and return its job.
|
||||
Remote jobs have type `query` and use the SQL query ID as `id`. Waiting
|
||||
confirms catalog removal; physical cleanup continues in the background.
|
||||
|
||||
Rejects a table that exists but is not a materialized view.
|
||||
|
||||
@@ -653,94 +658,48 @@ See [Listing](Listing.md) for pagination state and error behavior.
|
||||
### listNamespaces()
|
||||
|
||||
```ts
|
||||
abstract listNamespaces(namespacePath?, options?): Promise<ListNamespacesResponse>
|
||||
abstract listNamespaces(namespacePath?, options?): Listing<string>
|
||||
```
|
||||
|
||||
List the immediate child namespaces under the given parent.
|
||||
|
||||
Results may be paginated. To retrieve subsequent pages, pass the
|
||||
`pageToken` returned by a previous call.
|
||||
Lazily list immediate child namespaces, 100 per page by default.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **namespacePath?**: `string`[]
|
||||
The parent namespace path. Defaults
|
||||
to the root namespace if omitted.
|
||||
|
||||
* **options?**: `Partial`<[`ListNamespacesOptions`](../interfaces/ListNamespacesOptions.md)>
|
||||
Pagination options
|
||||
(`pageToken`, `limit`).
|
||||
* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`ListNamespacesResponse`](../interfaces/ListNamespacesResponse.md)>
|
||||
|
||||
Child namespace names and
|
||||
an optional token for fetching the next page.
|
||||
[`Listing`](Listing.md)<`string`>
|
||||
|
||||
***
|
||||
|
||||
### listTables()
|
||||
|
||||
#### listTables(options)
|
||||
|
||||
```ts
|
||||
abstract listTables(options?): Promise<ListTablesResponse>
|
||||
abstract listTables(namespacePath?, options?): Listing<string>
|
||||
```
|
||||
|
||||
List a page of the tables in this database.
|
||||
Lazily list tables in a namespace, requesting 100 per page by default.
|
||||
|
||||
To retrieve the tables after the page, pass the `pageToken` the response
|
||||
carries back in. A page can be shorter than `limit` without being the last
|
||||
one, so walk until a response carries no page token:
|
||||
|
||||
```ts
|
||||
const names = [];
|
||||
let pageToken = undefined;
|
||||
do {
|
||||
const page = await conn.listTables({ pageToken, limit: 100 });
|
||||
names.push(...page.tables);
|
||||
pageToken = page.pageToken;
|
||||
} while (pageToken);
|
||||
```
|
||||
|
||||
##### Parameters
|
||||
|
||||
* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)>
|
||||
Pagination options
|
||||
(`pageToken`, `limit`).
|
||||
|
||||
##### Returns
|
||||
|
||||
`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)>
|
||||
|
||||
A page of table names and an
|
||||
optional token for the tables after it.
|
||||
|
||||
#### listTables(namespacePath, options)
|
||||
|
||||
```ts
|
||||
abstract listTables(namespacePath?, options?): Promise<ListTablesResponse>
|
||||
```
|
||||
|
||||
List a page of the tables in this database.
|
||||
|
||||
##### Parameters
|
||||
#### Parameters
|
||||
|
||||
* **namespacePath?**: `string`[]
|
||||
The namespace path to list tables from
|
||||
(defaults to root namespace)
|
||||
|
||||
* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)>
|
||||
Pagination options
|
||||
(`pageToken`, `limit`).
|
||||
* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md)
|
||||
|
||||
##### Returns
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)>
|
||||
[`Listing`](Listing.md)<`string`>
|
||||
|
||||
A page of table names and an
|
||||
optional token for the tables after it.
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
for await (const name of conn.listTables([], { pageLimit: 20 })) {
|
||||
console.log(name);
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
@@ -868,7 +827,7 @@ abstract renameTable(
|
||||
|
||||
Rename a table.
|
||||
|
||||
Currently only supported by LanceDB Cloud. Local OSS connections and
|
||||
Currently only supported in LanceDB Distributed. LanceDB Embedded connections and
|
||||
namespace-backed connections (via [connectNamespace](../functions/connectNamespace.md)) reject with
|
||||
a "not supported" error.
|
||||
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / Expr
|
||||
|
||||
# Class: Expr
|
||||
|
||||
A SQL expression backed by the shared LanceDB expression builder.
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
table.query().where(col("firstName").eq("Alice")).toArray();
|
||||
```
|
||||
|
||||
## Constructors
|
||||
|
||||
### new Expr()
|
||||
|
||||
```ts
|
||||
new Expr(inner): Expr
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **inner**: `Expr`
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
## Properties
|
||||
|
||||
### inner
|
||||
|
||||
```ts
|
||||
inner: Expr;
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
### add()
|
||||
|
||||
```ts
|
||||
add(other): Expr
|
||||
```
|
||||
|
||||
Add a value.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### and()
|
||||
|
||||
```ts
|
||||
and(other): Expr
|
||||
```
|
||||
|
||||
Combine two predicates with AND.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`Expr`](Expr.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### cast()
|
||||
|
||||
```ts
|
||||
cast(dataType): Expr
|
||||
```
|
||||
|
||||
Cast to an Arrow data type, such as "Int64".
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **dataType**: `string`
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### contains()
|
||||
|
||||
```ts
|
||||
contains(substr): Expr
|
||||
```
|
||||
|
||||
Test whether a string contains a substring.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **substr**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### div()
|
||||
|
||||
```ts
|
||||
div(other): Expr
|
||||
```
|
||||
|
||||
Divide by a value.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### eq()
|
||||
|
||||
```ts
|
||||
eq(other): Expr
|
||||
```
|
||||
|
||||
Compare for equality.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### gt()
|
||||
|
||||
```ts
|
||||
gt(other): Expr
|
||||
```
|
||||
|
||||
Compare for greater than.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### gte()
|
||||
|
||||
```ts
|
||||
gte(other): Expr
|
||||
```
|
||||
|
||||
Compare for greater than or equal to.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### isIn()
|
||||
|
||||
```ts
|
||||
isIn(values): Expr
|
||||
```
|
||||
|
||||
Test membership in a list of values.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **values**: [`ExprLike`](../type-aliases/ExprLike.md)[]
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### lower()
|
||||
|
||||
```ts
|
||||
lower(): Expr
|
||||
```
|
||||
|
||||
Convert a string to lowercase.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### lt()
|
||||
|
||||
```ts
|
||||
lt(other): Expr
|
||||
```
|
||||
|
||||
Compare for less than.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### lte()
|
||||
|
||||
```ts
|
||||
lte(other): Expr
|
||||
```
|
||||
|
||||
Compare for less than or equal to.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### mul()
|
||||
|
||||
```ts
|
||||
mul(other): Expr
|
||||
```
|
||||
|
||||
Multiply by a value.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### ne()
|
||||
|
||||
```ts
|
||||
ne(other): Expr
|
||||
```
|
||||
|
||||
Compare for inequality.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### not()
|
||||
|
||||
```ts
|
||||
not(): Expr
|
||||
```
|
||||
|
||||
Negate this predicate.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### or()
|
||||
|
||||
```ts
|
||||
or(other): Expr
|
||||
```
|
||||
|
||||
Combine two predicates with OR.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`Expr`](Expr.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### sub()
|
||||
|
||||
```ts
|
||||
sub(other): Expr
|
||||
```
|
||||
|
||||
Subtract a value.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **other**: [`ExprLike`](../type-aliases/ExprLike.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
|
||||
***
|
||||
|
||||
### toSql()
|
||||
|
||||
```ts
|
||||
toSql(): string
|
||||
```
|
||||
|
||||
Serialize with the LanceDB SQL dialect, preserving column case.
|
||||
|
||||
#### Returns
|
||||
|
||||
`string`
|
||||
|
||||
***
|
||||
|
||||
### upper()
|
||||
|
||||
```ts
|
||||
upper(): Expr
|
||||
```
|
||||
|
||||
Convert a string to uppercase.
|
||||
|
||||
#### Returns
|
||||
|
||||
[`Expr`](Expr.md)
|
||||
@@ -17,7 +17,8 @@ extra round trip on every call:
|
||||
- [Job.refresh](Job.md#refresh) and [Job.status](Job.md#status) fetch the whole record.
|
||||
- [Job.wait](Job.md#wait) records the terminal state it establishes, but not the
|
||||
rest of the record.
|
||||
- Everything is null until one of those runs.
|
||||
- Registry details are null until one of those runs. Query handles report
|
||||
jobType "query" immediately.
|
||||
|
||||
## Accessors
|
||||
|
||||
@@ -57,8 +58,10 @@ get id(): null | string
|
||||
|
||||
Identifies the operation on the server that is running it.
|
||||
|
||||
Operations that run in this process have no server id. The value is
|
||||
opaque: parsing it or storing it to resume the job later is not supported.
|
||||
Registry handles expose a registry job ID; query handles expose a
|
||||
connection-scoped SQL query UUID string. Local handles have no ID.
|
||||
Query handles report jobType "query". Their IDs are not registry IDs or
|
||||
durable resume tokens.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -72,8 +75,8 @@ opaque: parsing it or storing it to resume the job later is not supported.
|
||||
get jobType(): null | string
|
||||
```
|
||||
|
||||
The job's type, as the server names it. Null for an in-process job, which
|
||||
has no server-side record.
|
||||
"query" immediately for SQL-backed handles; otherwise the cached
|
||||
server-reported job type. Null for in-process handles.
|
||||
|
||||
#### Returns
|
||||
|
||||
|
||||
@@ -64,15 +64,20 @@ refresh(options?): Promise<RefreshMaterializedViewResult>
|
||||
```
|
||||
|
||||
Recompute the view from its source.
|
||||
Local refresh requires a source build with `experimental-functions`.
|
||||
|
||||
Every refresh rebuilds the complete view. For local views,
|
||||
`sourceVersion` refreshes to that source version instead of the latest;
|
||||
remote SQL refreshes do not support source-version pinning.
|
||||
`full: true` forces a remote rebuild; otherwise the server chooses the
|
||||
refresh mode. Local views always rebuild, and `sourceVersion` selects a
|
||||
source version instead of the latest. Remote SQL refreshes do not support
|
||||
source-version pinning. Their results leave `mode`, `rowsWritten`, and
|
||||
`sourceVersion` absent because the SQL job adapter does not expose these metrics.
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **options?**
|
||||
|
||||
* **options.full?**: `boolean`
|
||||
|
||||
* **options.sourceVersion?**: `number`
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -543,29 +543,34 @@ where(predicate): this
|
||||
|
||||
A filter statement to be applied to this query.
|
||||
|
||||
The filter should be supplied as an SQL query string. For example:
|
||||
The filter may be an SQL query string or an expression built with `col`,
|
||||
which preserves case-sensitive column names. For example:
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **predicate**: `string`
|
||||
* **predicate**: `string` \| [`Expr`](Expr.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`this`
|
||||
|
||||
#### Example
|
||||
#### Examples
|
||||
|
||||
```ts
|
||||
x > 10
|
||||
y > 0 AND y < 100
|
||||
x > 5 OR y = 'test'
|
||||
```
|
||||
|
||||
```ts
|
||||
table.query().where(col("firstName").eq("Alice"));
|
||||
```
|
||||
|
||||
Filtering performance can often be improved by creating a scalar index
|
||||
on the filter column(s).
|
||||
|
||||
Calling this multiple times combines the filters with a logical AND rather
|
||||
than replacing the previous filter.
|
||||
```
|
||||
|
||||
#### Inherited from
|
||||
|
||||
|
||||
@@ -69,6 +69,10 @@ abstract addColumns(newColumnTransforms): Promise<AddColumnsResult>
|
||||
|
||||
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.
|
||||
|
||||
The `{ computed }` form stores the expression rather than evaluating it
|
||||
now: the column is committed with no values, and rows get them from
|
||||
[Table#refreshColumn](Table.md#refreshcolumn). Declaring one therefore costs the same on a
|
||||
@@ -79,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.
|
||||
|
||||
On LanceDB Cloud and Enterprise the expression is planned by the
|
||||
In LanceDB Distributed the expression is planned by the
|
||||
server, and the refresh runs as a server job -- see
|
||||
[Table#refreshColumnAsync](Table.md#refreshcolumnasync).
|
||||
|
||||
@@ -381,6 +385,13 @@ await table.createIndex("vector", {
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Or size the partitions by row count instead of choosing how many.
|
||||
await table.createIndex("vector", {
|
||||
config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }),
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Or create a Scalar index
|
||||
await table.createIndex("my_float_col");
|
||||
@@ -675,7 +686,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 Cloud and Enterprise only; reading errors needs read
|
||||
capped. LanceDB Distributed only; reading errors needs read
|
||||
access to the table, since a message carries the value that failed.
|
||||
|
||||
#### Parameters
|
||||
@@ -928,7 +939,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 on remote tables.
|
||||
This feature is currently only supported in LanceDB Distributed.
|
||||
|
||||
#### Returns
|
||||
|
||||
@@ -1035,11 +1046,12 @@ abstract refreshColumn(column): Promise<RefreshColumnResult>
|
||||
```
|
||||
|
||||
Fill the rows of a computed column that hold no value yet.
|
||||
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. Local tables only: a remote refresh
|
||||
runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync).
|
||||
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).
|
||||
|
||||
#### Parameters
|
||||
|
||||
@@ -1063,12 +1075,15 @@ abstract refreshColumnAsync(column): 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
|
||||
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. On local tables the job runs in-process; on
|
||||
LanceDB Cloud and Enterprise it is the server's backfill job.
|
||||
than failing the job. In LanceDB Embedded the job runs in-process; in
|
||||
LanceDB Distributed it is the server's backfill job.
|
||||
|
||||
#### Parameters
|
||||
|
||||
@@ -1297,8 +1312,12 @@ 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. For remote tables, this means the
|
||||
same tokenizer model files must also exist locally.
|
||||
the client process from index metadata. In LanceDB Distributed, 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
|
||||
server's index produces. If the model files are missing, an error naming
|
||||
the tokenizer is raised.
|
||||
|
||||
#### Parameters
|
||||
|
||||
@@ -1423,8 +1442,6 @@ used when appropriate:
|
||||
- `lancedb:description`: for a human-readable description of a field.
|
||||
- `lancedb:tag:<name>`: for a user-defined key-value tag, where the suffix
|
||||
names the tag category; e.g. `lancedb:tag:model: "clip"`.
|
||||
- `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and
|
||||
`feature_v2` might be in the same logical column.
|
||||
- `lancedb:status`: for status options (`production`, `candidate`,
|
||||
`deprecated`, `archived`) to designate the current life cycle state of
|
||||
this column.
|
||||
|
||||
@@ -825,29 +825,34 @@ where(predicate): this
|
||||
|
||||
A filter statement to be applied to this query.
|
||||
|
||||
The filter should be supplied as an SQL query string. For example:
|
||||
The filter may be an SQL query string or an expression built with `col`,
|
||||
which preserves case-sensitive column names. For example:
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **predicate**: `string`
|
||||
* **predicate**: `string` \| [`Expr`](Expr.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`this`
|
||||
|
||||
#### Example
|
||||
#### Examples
|
||||
|
||||
```ts
|
||||
x > 10
|
||||
y > 0 AND y < 100
|
||||
x > 5 OR y = 'test'
|
||||
```
|
||||
|
||||
```ts
|
||||
table.query().where(col("firstName").eq("Alice"));
|
||||
```
|
||||
|
||||
Filtering performance can often be improved by creating a scalar index
|
||||
on the filter column(s).
|
||||
|
||||
Calling this multiple times combines the filters with a logical AND rather
|
||||
than replacing the previous filter.
|
||||
```
|
||||
|
||||
#### Inherited from
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / col
|
||||
|
||||
# Function: col()
|
||||
|
||||
```ts
|
||||
function col(name): Expr
|
||||
```
|
||||
|
||||
Reference a column by its exact, case-sensitive name.
|
||||
|
||||
## Parameters
|
||||
|
||||
* **name**: `string`
|
||||
|
||||
## Returns
|
||||
|
||||
[`Expr`](../classes/Expr.md)
|
||||
@@ -20,15 +20,15 @@ Connect to a LanceDB instance at the given URI.
|
||||
|
||||
Accepted formats:
|
||||
|
||||
- `/path/to/database` - local database
|
||||
- `/path/to/database` - database on the local file system
|
||||
- `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
|
||||
- `db://host:port` - remote database (LanceDB cloud)
|
||||
- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
|
||||
|
||||
### Parameters
|
||||
|
||||
* **uri**: `string`
|
||||
The uri of the database. If the database uri starts
|
||||
with `db://` then it connects to a remote database.
|
||||
with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy).
|
||||
|
||||
* **options?**: `Partial`<[`ConnectionOptions`](../interfaces/ConnectionOptions.md)>
|
||||
The options to use when connecting to the database
|
||||
@@ -80,9 +80,9 @@ Connect to a LanceDB instance at the given URI.
|
||||
|
||||
Accepted formats:
|
||||
|
||||
- `/path/to/database` - local database
|
||||
- `/path/to/database` - database on the local file system
|
||||
- `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage
|
||||
- `db://host:port` - remote database (LanceDB cloud)
|
||||
- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ function connectNamespace(
|
||||
Connect to a LanceDB database through a namespace.
|
||||
|
||||
Unlike [connect](connect.md), which routes by URI scheme (local path vs.
|
||||
`db://` cloud), `connectNamespace` always returns a namespace-backed
|
||||
`db://`), `connectNamespace` always returns a namespace-backed
|
||||
connection. The `implName` selects the namespace implementation:
|
||||
|
||||
- `"dir"` — directory namespace, configured with [DirNamespaceConfig](../interfaces/DirNamespaceConfig.md).
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / func
|
||||
|
||||
# Function: func()
|
||||
|
||||
```ts
|
||||
function func(name, ...args): Expr
|
||||
```
|
||||
|
||||
Call a registered SQL function, such as `func("lower", col("firstName"))`.
|
||||
|
||||
## Parameters
|
||||
|
||||
* **name**: `string`
|
||||
|
||||
* ...**args**: [`ExprLike`](../type-aliases/ExprLike.md)[]
|
||||
|
||||
## Returns
|
||||
|
||||
[`Expr`](../classes/Expr.md)
|
||||
@@ -0,0 +1,21 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / lit
|
||||
|
||||
# Function: lit()
|
||||
|
||||
```ts
|
||||
function lit(value): Expr
|
||||
```
|
||||
|
||||
Create a string or numeric literal. Unsafe integers are represented as Float64.
|
||||
|
||||
## Parameters
|
||||
|
||||
* **value**: `string` \| `number`
|
||||
|
||||
## Returns
|
||||
|
||||
[`Expr`](../classes/Expr.md)
|
||||
@@ -0,0 +1,21 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / litBool
|
||||
|
||||
# Function: litBool()
|
||||
|
||||
```ts
|
||||
function litBool(value): Expr
|
||||
```
|
||||
|
||||
Create a boolean literal.
|
||||
|
||||
## Parameters
|
||||
|
||||
* **value**: `boolean`
|
||||
|
||||
## Returns
|
||||
|
||||
[`Expr`](../classes/Expr.md)
|
||||
@@ -0,0 +1,21 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / litInt
|
||||
|
||||
# Function: litInt()
|
||||
|
||||
```ts
|
||||
function litInt(value): Expr
|
||||
```
|
||||
|
||||
Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError.
|
||||
|
||||
## Parameters
|
||||
|
||||
* **value**: `number`
|
||||
|
||||
## Returns
|
||||
|
||||
[`Expr`](../classes/Expr.md)
|
||||
@@ -28,6 +28,7 @@
|
||||
- [Catalog](classes/Catalog.md)
|
||||
- [Connection](classes/Connection.md)
|
||||
- [DatabaseNames](classes/DatabaseNames.md)
|
||||
- [Expr](classes/Expr.md)
|
||||
- [HeaderProvider](classes/HeaderProvider.md)
|
||||
- [Index](classes/Index.md)
|
||||
- [Job](classes/Job.md)
|
||||
@@ -108,10 +109,6 @@
|
||||
- [JobEventsOptions](interfaces/JobEventsOptions.md)
|
||||
- [JobFailureInfo](interfaces/JobFailureInfo.md)
|
||||
- [JobInfo](interfaces/JobInfo.md)
|
||||
- [ListNamespacesOptions](interfaces/ListNamespacesOptions.md)
|
||||
- [ListNamespacesResponse](interfaces/ListNamespacesResponse.md)
|
||||
- [ListTablesOptions](interfaces/ListTablesOptions.md)
|
||||
- [ListTablesResponse](interfaces/ListTablesResponse.md)
|
||||
- [ListingOptions](interfaces/ListingOptions.md)
|
||||
- [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md)
|
||||
- [MemtableStats](interfaces/MemtableStats.md)
|
||||
@@ -169,6 +166,7 @@
|
||||
- [Data](type-aliases/Data.md)
|
||||
- [DataLike](type-aliases/DataLike.md)
|
||||
- [DataTypeLike](type-aliases/DataTypeLike.md)
|
||||
- [ExprLike](type-aliases/ExprLike.md)
|
||||
- [FieldLike](type-aliases/FieldLike.md)
|
||||
- [IntoSql](type-aliases/IntoSql.md)
|
||||
- [IntoVector](type-aliases/IntoVector.md)
|
||||
@@ -183,11 +181,16 @@
|
||||
|
||||
- [RecordBatchIterator](functions/RecordBatchIterator.md)
|
||||
- [blob](functions/blob.md)
|
||||
- [col](functions/col.md)
|
||||
- [connect](functions/connect.md)
|
||||
- [connectCatalog](functions/connectCatalog.md)
|
||||
- [connectNamespace](functions/connectNamespace.md)
|
||||
- [func](functions/func.md)
|
||||
- [instrumentLanceDbMetrics](functions/instrumentLanceDbMetrics.md)
|
||||
- [isBlobField](functions/isBlobField.md)
|
||||
- [lit](functions/lit.md)
|
||||
- [litBool](functions/litBool.md)
|
||||
- [litInt](functions/litInt.md)
|
||||
- [makeArrowTable](functions/makeArrowTable.md)
|
||||
- [makeJsonField](functions/makeJsonField.md)
|
||||
- [packBits](functions/packBits.md)
|
||||
|
||||
@@ -18,8 +18,8 @@ optional allowExternalBlobOutsideBases: boolean;
|
||||
|
||||
Whether blob URIs outside registered external bases may be written.
|
||||
|
||||
Defaults to `false`. This option is supported only for local/native
|
||||
tables; remote tables return an error when it is enabled. An enabled write
|
||||
Defaults to `false`. This option is supported only in LanceDB Embedded;
|
||||
LanceDB Distributed 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.
|
||||
|
||||
@@ -80,7 +80,7 @@ optional userId: string;
|
||||
|
||||
User identifier for tracking purposes.
|
||||
|
||||
This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise.
|
||||
This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise.
|
||||
It can be set directly, or via the `LANCEDB_USER_ID` environment variable.
|
||||
Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment
|
||||
variable that contains the user ID value.
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
optional apiKey: string;
|
||||
```
|
||||
|
||||
(For LanceDB cloud only): the API key to use with LanceDB Cloud.
|
||||
(For LanceDB Enterprise or LanceDB Cloud only): the API key to use.
|
||||
|
||||
Can also be set via the environment variable `LANCEDB_API_KEY`.
|
||||
|
||||
@@ -26,7 +26,7 @@ Can also be set via the environment variable `LANCEDB_API_KEY`.
|
||||
optional clientConfig: ClientConfig;
|
||||
```
|
||||
|
||||
(For LanceDB cloud only): configuration for the remote HTTP client.
|
||||
(For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client.
|
||||
|
||||
***
|
||||
|
||||
@@ -36,8 +36,8 @@ optional clientConfig: ClientConfig;
|
||||
optional hostOverride: string;
|
||||
```
|
||||
|
||||
(For LanceDB cloud only): the host to use for LanceDB cloud. Used
|
||||
for testing purposes.
|
||||
(For LanceDB Enterprise only): the host of the LanceDB Enterprise
|
||||
deployment to connect to.
|
||||
|
||||
***
|
||||
|
||||
@@ -47,7 +47,7 @@ for testing purposes.
|
||||
optional manifestEnabled: boolean;
|
||||
```
|
||||
|
||||
(For LanceDB OSS only): use directory namespace manifests as the source
|
||||
(For LanceDB Embedded only): use directory namespace manifests as the source
|
||||
of truth for table metadata. Existing directory-listed root tables are
|
||||
migrated into the manifest on access.
|
||||
|
||||
@@ -59,7 +59,7 @@ migrated into the manifest on access.
|
||||
optional namespaceClientProperties: Record<string, string>;
|
||||
```
|
||||
|
||||
(For LanceDB OSS only): extra properties for the backing namespace
|
||||
(For LanceDB Embedded only): extra properties for the backing namespace
|
||||
client used by manifest-enabled native connections.
|
||||
|
||||
***
|
||||
@@ -70,7 +70,7 @@ client used by manifest-enabled native connections.
|
||||
optional oauthConfig: NativeOAuthConfig;
|
||||
```
|
||||
|
||||
(For LanceDB cloud only): OAuth configuration for IdP-based
|
||||
(For LanceDB Enterprise only): OAuth configuration for IdP-based
|
||||
authentication (e.g., Azure Entra ID). When set, token acquisition
|
||||
and refresh are handled entirely in Rust. TypeScript users should pass
|
||||
the public `OAuthConfig` type exported from `@lancedb/lancedb`.
|
||||
@@ -105,7 +105,7 @@ storage, raising per-read latency and cost.
|
||||
optional region: string;
|
||||
```
|
||||
|
||||
(For LanceDB cloud only): the region to use for LanceDB cloud.
|
||||
(For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy).
|
||||
Defaults to 'us-east-1'.
|
||||
|
||||
***
|
||||
@@ -116,7 +116,7 @@ Defaults to 'us-east-1'.
|
||||
optional session: Session;
|
||||
```
|
||||
|
||||
(For LanceDB OSS only): the session to use for this connection. Holds
|
||||
(For LanceDB Embedded only): the session to use for this connection. Holds
|
||||
shared caches and other session-specific state.
|
||||
|
||||
***
|
||||
@@ -127,6 +127,6 @@ shared caches and other session-specific state.
|
||||
optional storageOptions: Record<string, string>;
|
||||
```
|
||||
|
||||
(For LanceDB OSS only): configuration for object storage.
|
||||
(For LanceDB Embedded only): configuration for object storage.
|
||||
|
||||
The available options are described at https://docs.lancedb.com/storage/
|
||||
|
||||
@@ -65,7 +65,7 @@ then no error will be raised.
|
||||
### mode
|
||||
|
||||
```ts
|
||||
mode: "overwrite" | "create";
|
||||
mode: "overwrite" | "create" | "exist_ok";
|
||||
```
|
||||
|
||||
The mode to use when creating the table.
|
||||
@@ -76,6 +76,9 @@ happen. Any provided data will be ignored.
|
||||
|
||||
If this is set to "overwrite" then any existing table will be replaced.
|
||||
|
||||
If this is set to "exist_ok" then an existing table is opened and any
|
||||
provided data is ignored.
|
||||
|
||||
***
|
||||
|
||||
### schema?
|
||||
|
||||
@@ -100,6 +100,8 @@ optional numPartitions: number;
|
||||
|
||||
The number of IVF partitions to create.
|
||||
|
||||
When set, this takes precedence over `targetPartitionSize`.
|
||||
|
||||
For HNSW, we recommend a small number of partitions. Setting this to 1 works
|
||||
well for most tables. For very large tables, training just one HNSW graph
|
||||
will require too much memory. Each partition becomes its own HNSW graph, so
|
||||
@@ -147,3 +149,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`.
|
||||
|
||||
Increasing this value might improve the quality of the index but in most cases the
|
||||
default should be sufficient.
|
||||
|
||||
***
|
||||
|
||||
### targetPartitionSize?
|
||||
|
||||
```ts
|
||||
optional targetPartitionSize: number;
|
||||
```
|
||||
|
||||
The target number of rows in each IVF partition.
|
||||
|
||||
This is an alternative to `numPartitions`. When it is set and
|
||||
`numPartitions` is not, the number of partitions is derived by dividing
|
||||
the number of rows by this value. When both are set, `numPartitions` is
|
||||
used and this value is ignored. When neither is set, the target is
|
||||
1,048,576 rows.
|
||||
|
||||
Larger partitions mean fewer of them, which makes the first part of the
|
||||
search (picking the right partitions) faster and the second part
|
||||
(searching within a partition) slower.
|
||||
|
||||
@@ -100,6 +100,8 @@ optional numPartitions: number;
|
||||
|
||||
The number of IVF partitions to create.
|
||||
|
||||
When set, this takes precedence over `targetPartitionSize`.
|
||||
|
||||
For HNSW, we recommend a small number of partitions. Setting this to 1 works
|
||||
well for most tables. For very large tables, training just one HNSW graph
|
||||
will require too much memory. Each partition becomes its own HNSW graph, so
|
||||
@@ -126,3 +128,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`.
|
||||
|
||||
Increasing this value might improve the quality of the index but in most cases the
|
||||
default should be sufficient.
|
||||
|
||||
***
|
||||
|
||||
### targetPartitionSize?
|
||||
|
||||
```ts
|
||||
optional targetPartitionSize: number;
|
||||
```
|
||||
|
||||
The target number of rows in each IVF partition.
|
||||
|
||||
This is an alternative to `numPartitions`. When it is set and
|
||||
`numPartitions` is not, the number of partitions is derived by dividing
|
||||
the number of rows by this value. When both are set, `numPartitions` is
|
||||
used and this value is ignored. When neither is set, the target is
|
||||
1,048,576 rows.
|
||||
|
||||
Larger partitions mean fewer of them, which makes the first part of the
|
||||
search (picking the right partitions) faster and the second part
|
||||
(searching within a partition) slower.
|
||||
|
||||
@@ -31,7 +31,7 @@ optional createdAt: Date;
|
||||
|
||||
When the index was created.
|
||||
|
||||
`undefined` for remote tables or indices created before timestamps were tracked.
|
||||
`undefined` in LanceDB Distributed or indices created before timestamps were tracked.
|
||||
|
||||
***
|
||||
|
||||
@@ -43,8 +43,8 @@ optional indexDetails: any;
|
||||
|
||||
Index-type-specific details parsed as a JavaScript object.
|
||||
|
||||
Falls back to a raw string if JSON parsing fails. `undefined` for
|
||||
remote tables or when details are unavailable.
|
||||
Falls back to a raw string if JSON parsing fails. `undefined` in
|
||||
LanceDB Distributed or when details are unavailable.
|
||||
|
||||
***
|
||||
|
||||
@@ -66,7 +66,7 @@ optional indexUuid: string;
|
||||
|
||||
The UUID of the first segment of the index.
|
||||
|
||||
`undefined` for remote tables, which do not yet surface this.
|
||||
`undefined` in LanceDB Distributed, which does not yet surface this.
|
||||
|
||||
***
|
||||
|
||||
@@ -78,7 +78,7 @@ optional indexVersion: number;
|
||||
|
||||
The on-disk index format version.
|
||||
|
||||
`undefined` for remote tables.
|
||||
`undefined` in LanceDB Distributed.
|
||||
|
||||
***
|
||||
|
||||
@@ -100,7 +100,7 @@ optional numIndexedRows: number;
|
||||
|
||||
The number of rows indexed, across all segments.
|
||||
|
||||
`undefined` for remote tables.
|
||||
May be `undefined` in LanceDB Distributed if the server does not report it.
|
||||
|
||||
***
|
||||
|
||||
@@ -112,7 +112,7 @@ optional numSegments: number;
|
||||
|
||||
The number of segments that make up the index.
|
||||
|
||||
`undefined` for remote tables.
|
||||
`undefined` in LanceDB Distributed.
|
||||
|
||||
***
|
||||
|
||||
@@ -124,7 +124,7 @@ optional numUnindexedRows: number;
|
||||
|
||||
The number of rows not yet covered by this index.
|
||||
|
||||
`undefined` for remote tables.
|
||||
May be `undefined` in LanceDB Distributed 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` for remote tables or indices without size tracking.
|
||||
`undefined` in LanceDB Distributed or indices without size tracking.
|
||||
|
||||
***
|
||||
|
||||
@@ -148,4 +148,4 @@ optional typeUrl: string;
|
||||
|
||||
The protobuf type URL, a precise type identifier for the index.
|
||||
|
||||
`undefined` for remote tables.
|
||||
`undefined` in LanceDB Distributed.
|
||||
|
||||
@@ -82,8 +82,9 @@ optional numPartitions: number;
|
||||
The number of IVF partitions to create.
|
||||
|
||||
This value should generally scale with the number of rows in the dataset.
|
||||
By default the number of partitions is the square root of the number of
|
||||
rows.
|
||||
When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
the partition count is derived from `targetPartitionSize`, which defaults
|
||||
to 4096 rows for this index type.
|
||||
|
||||
If this value is too large then the first part of the search (picking the
|
||||
right partition) will be slow. If this value is too small then the second
|
||||
@@ -110,3 +111,23 @@ Increasing this value might improve the quality of the index but in most cases t
|
||||
default should be sufficient.
|
||||
|
||||
The default value is 256.
|
||||
|
||||
***
|
||||
|
||||
### targetPartitionSize?
|
||||
|
||||
```ts
|
||||
optional targetPartitionSize: number;
|
||||
```
|
||||
|
||||
The target number of rows in each IVF partition.
|
||||
|
||||
This is an alternative to `numPartitions`. When it is set and
|
||||
`numPartitions` is not, the number of partitions is derived by dividing
|
||||
the number of rows by this value. When both are set, `numPartitions` is
|
||||
used and this value is ignored. When neither is set, the target is
|
||||
4096 rows.
|
||||
|
||||
Larger partitions mean fewer of them, which makes the first part of the
|
||||
search (picking the right partitions) faster and the second part
|
||||
(searching within a partition) slower.
|
||||
|
||||
@@ -92,8 +92,9 @@ optional numPartitions: number;
|
||||
The number of IVF partitions to create.
|
||||
|
||||
This value should generally scale with the number of rows in the dataset.
|
||||
By default the number of partitions is the square root of the number of
|
||||
rows.
|
||||
When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
the partition count is derived from `targetPartitionSize`, which defaults
|
||||
to 8192 rows for this index type.
|
||||
|
||||
If this value is too large then the first part of the search (picking the
|
||||
right partition) will be slow. If this value is too small then the second
|
||||
@@ -141,3 +142,23 @@ Increasing this value might improve the quality of the index but in most cases t
|
||||
default should be sufficient.
|
||||
|
||||
The default value is 256.
|
||||
|
||||
***
|
||||
|
||||
### targetPartitionSize?
|
||||
|
||||
```ts
|
||||
optional targetPartitionSize: number;
|
||||
```
|
||||
|
||||
The target number of rows in each IVF partition.
|
||||
|
||||
This is an alternative to `numPartitions`. When it is set and
|
||||
`numPartitions` is not, the number of partitions is derived by dividing
|
||||
the number of rows by this value. When both are set, `numPartitions` is
|
||||
used and this value is ignored. When neither is set, the target is
|
||||
8192 rows.
|
||||
|
||||
Larger partitions mean fewer of them, which makes the first part of the
|
||||
search (picking the right partitions) faster and the second part
|
||||
(searching within a partition) slower.
|
||||
|
||||
@@ -58,7 +58,8 @@ Number of bits per dimension for residual quantization.
|
||||
|
||||
This value controls how much each residual component is compressed. The more
|
||||
bits, the more accurate the index will be but the slower search. Typical values
|
||||
are small integers; the default is 1 bit per dimension.
|
||||
are small integers. If unset, uses Lance's default (currently 5 bits per
|
||||
dimension). Set to 1 for maximum compression.
|
||||
|
||||
***
|
||||
|
||||
@@ -71,8 +72,9 @@ optional numPartitions: number;
|
||||
The number of IVF partitions to create.
|
||||
|
||||
This value should generally scale with the number of rows in the dataset.
|
||||
By default the number of partitions is the square root of the number of
|
||||
rows.
|
||||
When set, this takes precedence over `targetPartitionSize`. When omitted,
|
||||
the partition count is derived from `targetPartitionSize`, which defaults
|
||||
to 4096 rows for this index type.
|
||||
|
||||
If this value is too large then the first part of the search (picking the
|
||||
right partition) will be slow. If this value is too small then the second
|
||||
@@ -99,3 +101,23 @@ Increasing this value might improve the quality of the index but in most cases t
|
||||
default should be sufficient.
|
||||
|
||||
The default value is 256.
|
||||
|
||||
***
|
||||
|
||||
### targetPartitionSize?
|
||||
|
||||
```ts
|
||||
optional targetPartitionSize: number;
|
||||
```
|
||||
|
||||
The target number of rows in each IVF partition.
|
||||
|
||||
This is an alternative to `numPartitions`. When it is set and
|
||||
`numPartitions` is not, the number of partitions is derived by dividing
|
||||
the number of rows by this value. When both are set, `numPartitions` is
|
||||
used and this value is ignored. When neither is set, the target is
|
||||
4096 rows.
|
||||
|
||||
Larger partitions mean fewer of them, which makes the first part of the
|
||||
search (picking the right partitions) faster and the second part
|
||||
(searching within a partition) slower.
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / ListNamespacesOptions
|
||||
|
||||
# Interface: ListNamespacesOptions
|
||||
|
||||
## Properties
|
||||
|
||||
### limit?
|
||||
|
||||
```ts
|
||||
optional limit: number;
|
||||
```
|
||||
|
||||
An optional limit to the number of results to return.
|
||||
|
||||
***
|
||||
|
||||
### pageToken?
|
||||
|
||||
```ts
|
||||
optional pageToken: string;
|
||||
```
|
||||
|
||||
Token from a previous response for pagination.
|
||||
@@ -1,23 +0,0 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / ListNamespacesResponse
|
||||
|
||||
# Interface: ListNamespacesResponse
|
||||
|
||||
## Properties
|
||||
|
||||
### namespaces
|
||||
|
||||
```ts
|
||||
namespaces: string[];
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### pageToken?
|
||||
|
||||
```ts
|
||||
optional pageToken: string;
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / ListTablesOptions
|
||||
|
||||
# Interface: ListTablesOptions
|
||||
|
||||
## Properties
|
||||
|
||||
### limit?
|
||||
|
||||
```ts
|
||||
optional limit: number;
|
||||
```
|
||||
|
||||
An upper bound on how many tables to return.
|
||||
Defaults to 100. Zero returns an empty page without a continuation token.
|
||||
|
||||
A page may hold fewer than this and still not be the last one, so keep
|
||||
going while the response carries a page token rather than while pages are
|
||||
full.
|
||||
|
||||
***
|
||||
|
||||
### pageToken?
|
||||
|
||||
```ts
|
||||
optional pageToken: string;
|
||||
```
|
||||
|
||||
Token from a previous response, to resume listing where it left off.
|
||||
|
||||
The token is opaque: it carries whatever the database needs to resume, and
|
||||
callers should not construct or interpret one.
|
||||
@@ -1,23 +0,0 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / ListTablesResponse
|
||||
|
||||
# Interface: ListTablesResponse
|
||||
|
||||
## Properties
|
||||
|
||||
### pageToken?
|
||||
|
||||
```ts
|
||||
optional pageToken: string;
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
### tables
|
||||
|
||||
```ts
|
||||
tables: string[];
|
||||
```
|
||||
@@ -20,12 +20,14 @@ How to return blob v2 columns. Applies to `toArrow()` and `toArray()`.
|
||||
|
||||
- `"descriptions"` (default): each blob is a descriptor. Read the bytes
|
||||
with [Table.fetchBlobs](../classes/Table.md#fetchblobs) or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles).
|
||||
- `"bytes"`: each top-level blob column holds the blob bytes as
|
||||
`LargeBinary`. The query also reads `_rowid` to fetch the bytes, and
|
||||
- `"bytes"`: each blob column, including blobs nested in structs, holds
|
||||
the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and
|
||||
leaves it out of the result unless [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was
|
||||
called. All the bytes are held in memory.
|
||||
|
||||
Blobs nested in a struct or a list keep their descriptors.
|
||||
Selecting a parent struct or directly aliasing a blob or struct also returns
|
||||
bytes. Blobs inside lists keep their descriptors. Arbitrary projection
|
||||
expressions are not materialized as bytes.
|
||||
|
||||
The rows and the bytes come from the same table version. If the table
|
||||
changes while the query runs, the query runs again, up to three times.
|
||||
|
||||
@@ -8,30 +8,34 @@
|
||||
|
||||
## Properties
|
||||
|
||||
### mode
|
||||
### mode?
|
||||
|
||||
```ts
|
||||
mode: string;
|
||||
optional mode: string;
|
||||
```
|
||||
|
||||
How the view was brought up to date: "rebuild".
|
||||
How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes.
|
||||
|
||||
***
|
||||
|
||||
### rowsWritten
|
||||
### rowsWritten?
|
||||
|
||||
```ts
|
||||
rowsWritten: number;
|
||||
optional rowsWritten: number;
|
||||
```
|
||||
|
||||
Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes.
|
||||
|
||||
***
|
||||
|
||||
### sourceVersion
|
||||
### sourceVersion?
|
||||
|
||||
```ts
|
||||
sourceVersion: number;
|
||||
optional sourceVersion: number;
|
||||
```
|
||||
|
||||
Source version refreshed to, or absent for LanceDB Distributed SQL refreshes.
|
||||
|
||||
***
|
||||
|
||||
### version
|
||||
|
||||
@@ -84,7 +84,7 @@ optional statuses: number[];
|
||||
```
|
||||
|
||||
The HTTP status codes for which to retry the request. Default is
|
||||
[429, 500, 502, 503].
|
||||
[409, 429, 500, 502, 503, 504].
|
||||
|
||||
You can also set this via the environment variable
|
||||
`LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
## Deprecated
|
||||
|
||||
Use [ListTablesOptions](ListTablesOptions.md) with [Connection.listTables](../classes/Connection.md#listtables)
|
||||
Use [ListingOptions](ListingOptions.md) with [Connection.listTables](../classes/Connection.md#listtables)
|
||||
instead.
|
||||
|
||||
## Properties
|
||||
|
||||
@@ -45,6 +45,10 @@ The timeout for reading data from the server in seconds. Default is 300
|
||||
seconds (5 minutes). This can also be set via the environment variable
|
||||
`LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds.
|
||||
|
||||
This also applies while waiting for response headers during an upload.
|
||||
A large or slowly produced request body (for example, when creating a
|
||||
table) may need a longer timeout even if data is still being uploaded.
|
||||
|
||||
***
|
||||
|
||||
### timeout?
|
||||
|
||||
@@ -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 remote table.
|
||||
read stops, including in-flight requests to a LanceDB Distributed table.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / ExprLike
|
||||
|
||||
# Type Alias: ExprLike
|
||||
|
||||
```ts
|
||||
type ExprLike: Expr | string | number | boolean;
|
||||
```
|
||||
|
||||
Values accepted by expression operators.
|
||||
+183
-10
@@ -20,20 +20,34 @@ pip install lancedb
|
||||
The following methods describe the synchronous API client. There
|
||||
is also an [asynchronous API client](#connections-asynchronous).
|
||||
|
||||
Connections to `db://` databases reject local-only options with
|
||||
`NotImplementedError`. These include `session` and `manifest_enabled=True` on
|
||||
connect, per-table storage and write options on create, and `index_cache_size`,
|
||||
`storage_options`, or `location` on open (where the method accepts them).
|
||||
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
|
||||
LanceDB Embedded API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value,
|
||||
embedding_functions`. Prefer keyword arguments for optional parameters.
|
||||
|
||||
## Connections (Synchronous)
|
||||
|
||||
::: lancedb.connect
|
||||
|
||||
::: lancedb.db.DBConnection
|
||||
|
||||
Resource listings (`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.
|
||||
Resource listings return iterators. Use `list(db.list_tables())` to collect all
|
||||
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`.
|
||||
|
||||
::: lancedb.listing.Listing
|
||||
|
||||
::: lancedb.listing.TableListing
|
||||
|
||||
::: lancedb.listing.NamespaceListing
|
||||
|
||||
::: lancedb.Session
|
||||
|
||||
## Catalogs (Synchronous)
|
||||
@@ -213,15 +227,24 @@ async for entry in catalog.authz.list_acls(subject=Subject.role("reader")):
|
||||
|
||||
## Remote SQL
|
||||
|
||||
Submit SQL against a remote LanceDB database through the connection.
|
||||
Submit SQL against a LanceDB Distributed 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
|
||||
reader as soon as its initial result stream is available. `execute_query_async`
|
||||
returns a query handle immediately; use it to inspect progress, open a reader,
|
||||
returns a query handle once submission is accepted; use it to inspect progress, open a reader,
|
||||
or cancel the query. The SQL client is initialized by the first query and
|
||||
retained for the lifetime of the remote connection. Query ids are random,
|
||||
connection-scoped references rather than encoded SQL or durable resume tokens:
|
||||
retained for the lifetime of the connection. Query ids are random,
|
||||
connection-scoped references rather than encoded SQL or durable resume tokens.
|
||||
|
||||
Both APIs start with one Flight call. The server can stream results on that
|
||||
call or return a polling continuation that the SDK follows automatically.
|
||||
This behavior is the same with and without parameters. Open the reader directly;
|
||||
a directly streamed query needs its reader to make progress. Dropping an unread
|
||||
handle or its reader stops direct streaming. Deferred execution continues until
|
||||
explicitly cancelled.
|
||||
|
||||
For example:
|
||||
|
||||
```python
|
||||
import lancedb
|
||||
@@ -285,8 +308,29 @@ listing a storage directory.
|
||||
|
||||
## Tables (Synchronous)
|
||||
|
||||
LanceDB Embedded and LanceDB Distributed 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.
|
||||
|
||||
The old LanceDB Distributed 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.
|
||||
|
||||
::: lancedb.table.Table
|
||||
|
||||
::: lancedb.table.CompactionOptions
|
||||
|
||||
::: lancedb.table.FragmentStatistics
|
||||
|
||||
::: lancedb.table.FragmentSummaryStats
|
||||
@@ -301,6 +345,14 @@ listing a storage directory.
|
||||
|
||||
## Functions and Jobs
|
||||
|
||||
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`.
|
||||
|
||||
::: lancedb.BlobReader
|
||||
|
||||
::: lancedb.functions.FunctionArtifact
|
||||
|
||||
::: lancedb.functions.FunctionParameter
|
||||
@@ -377,6 +429,30 @@ listing a storage directory.
|
||||
|
||||
## Materialized Views (Synchronous)
|
||||
|
||||
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
|
||||
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
|
||||
`auto_refresh_interval_seconds`:
|
||||
|
||||
```python
|
||||
view = db.create_materialized_view(
|
||||
"recent_orders",
|
||||
"orders",
|
||||
auto_refresh_enabled=True,
|
||||
auto_refresh_interval_seconds=300,
|
||||
)
|
||||
```
|
||||
|
||||
Omit `auto_refresh_interval_seconds` to let the server determine when to refresh.
|
||||
These options also apply to asynchronous creation and creation jobs. Embedded
|
||||
connections built with `experimental-functions` support manual refresh and reject
|
||||
automatic scheduling requests.
|
||||
|
||||
::: lancedb.materialized_view.MaterializedView
|
||||
|
||||
::: lancedb.materialized_view.MaterializedViewDefinition
|
||||
@@ -432,6 +508,8 @@ and combined with [BooleanQuery][lancedb.query.BooleanQuery].
|
||||
|
||||
::: lancedb.query.MultiMatchQuery
|
||||
|
||||
::: lancedb.query.CombinedFieldsQuery
|
||||
|
||||
::: lancedb.query.BooleanQuery
|
||||
|
||||
::: lancedb.query.FullTextOperator
|
||||
@@ -502,18 +580,103 @@ instead of being materialized with the rest of the row.
|
||||
|
||||
`lancedb.BlobType` is `lance.blob.BlobType` when pylance is installed. Without
|
||||
pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns
|
||||
still work. Queries return descriptors. Call
|
||||
still work. Native table queries return descriptors. Call
|
||||
[`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or
|
||||
[`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes.
|
||||
LanceDB Embedded supports these fetch APIs for both legacy blob v1 columns
|
||||
(`lance-encoding:blob`) and blob v2 columns. For legacy columns, obtain row IDs
|
||||
with `search().with_row_id(True).to_arrow()` and pass the result to the fetch API.
|
||||
One missing or deleted row ID rejects the entire blob-read batch; the APIs do
|
||||
not return partial results.
|
||||
|
||||
To construct inline Blob V2 arrays for ingestion in record batches, use
|
||||
[blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving
|
||||
the distinction between an empty blob (`b""`) and a null blob:
|
||||
|
||||
```python
|
||||
import pyarrow as pa
|
||||
from lancedb.schema import blob, blob_array
|
||||
|
||||
schema = pa.schema([pa.field("video_id", pa.string()), blob("video")])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array(["a", "b", "c"]), blob_array([b"abc", None, b""])],
|
||||
schema=schema,
|
||||
)
|
||||
table = db.create_table("videos", data=iter([batch]), schema=schema)
|
||||
table.add(iter([batch]))
|
||||
```
|
||||
|
||||
`create_table(..., schema=...)` also casts plain binary values into blob columns
|
||||
declared in the schema. `table.add(...)` casts them using the table's schema.
|
||||
These conversions apply to Python rows and plain binary Arrow columns.
|
||||
PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes
|
||||
into the blob extension type; use `blob_array` and `RecordBatch.from_arrays`
|
||||
when constructing batches explicitly.
|
||||
|
||||
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
|
||||
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]:
|
||||
|
||||
```python
|
||||
rows = db.execute_query("""
|
||||
SELECT f.timestamp, blob_descriptor(v.video) AS video
|
||||
FROM videos v JOIN frames f ON v.id = f.video_id
|
||||
""").read_all()
|
||||
videos = db.open_table("videos")
|
||||
for row in rows.to_pylist():
|
||||
if row["video"] is not None:
|
||||
with videos.open_blob_file(row["video"]) as video:
|
||||
frame = extract_frame(video, row["timestamp"])
|
||||
```
|
||||
|
||||
This example uses a LanceDB Distributed 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
|
||||
the source table and commit and reads the captured version without changing
|
||||
the table handle's checkout. Raw native storage descriptors omit `source`;
|
||||
use `fetch_blob_files(column, row_ids)` for those query results.
|
||||
|
||||
The singular API accepts a dictionary or Arrow struct scalar. The iterable
|
||||
accepts Arrow arrays/chunked arrays or another iterable, opens handles as
|
||||
iteration advances, and preserves order, duplicates, and nulls as `None`.
|
||||
Close each non-null handle after use. Async tables provide
|
||||
`await table.open_blob_file(...)` and
|
||||
`async for file in table.open_blob_files(...)`.
|
||||
|
||||
```python
|
||||
for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])):
|
||||
if video is not None:
|
||||
with video:
|
||||
frame = extract_frame(video, row["timestamp"])
|
||||
```
|
||||
|
||||
For an async table, the iterable is consumed with `async for`:
|
||||
|
||||
```python
|
||||
async for video in async_videos.open_blob_files(rows["video"]):
|
||||
if video is not None:
|
||||
with video:
|
||||
payload = await video.aread()
|
||||
```
|
||||
|
||||
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
|
||||
requests that validate the captured URI and commit timestamp.
|
||||
|
||||
Blobs inside lists can be written and queried as descriptors. They are omitted
|
||||
from `blob_columns()` because row ids do not identify individual list elements,
|
||||
so the fetch APIs cannot read their bytes yet.
|
||||
|
||||
::: lancedb.blob
|
||||
|
||||
::: lancedb.schema.blob_array
|
||||
|
||||
::: lancedb._blob.BlobFile
|
||||
options:
|
||||
show_root_full_path: false
|
||||
@@ -615,6 +778,16 @@ can be used to create, list, or open tables.
|
||||
|
||||
::: lancedb.listing.AsyncListing
|
||||
|
||||
`async for name in db.list_tables()` loads pages as needed. To inspect the
|
||||
first page, use `page = await db.list_tables()` and then `page.tables`. Reading
|
||||
the page list does not consume the iterator. `page.page_token` is the token for
|
||||
the next request; drain cached results before using it to resume in a new
|
||||
listing. The same behavior applies to namespaces.
|
||||
|
||||
::: lancedb.listing.AsyncTableListing
|
||||
|
||||
::: lancedb.listing.AsyncNamespaceListing
|
||||
|
||||
## Namespaces (Asynchronous)
|
||||
|
||||
::: lancedb.connect_namespace_async
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Blob v2 documentation tests
|
||||
|
||||
`docs/web-tests/ts` pins `@lancedb/lancedb` 0.31.0 and `docs/web-tests/rs` pins `lancedb` 0.31.0. Those releases do not include `blob()`. Run the Blob v2 examples here.
|
||||
|
||||
## Python
|
||||
|
||||
`lancedb==0.41.0b10` from the LanceDB package index, without pylance. PyPI `lancedb` 0.40.0 does not provide `lancedb.blob()`.
|
||||
|
||||
```shell
|
||||
python3.13 -m venv .venv
|
||||
.venv/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt
|
||||
.venv/bin/python -m pytest docs/web-tests/blob-v2/py/test_multimodal.py
|
||||
```
|
||||
|
||||
`test_blob_pylance.py` checks custom thresholds and `to_pandas()` in `lazy` and `bytes` mode. Those calls import pylance. Use a second virtualenv. `test_multimodal.py` fails if `lance` can be imported. Snippets from this file are written to `docs/web/snippets/blob_pylance.mdx`.
|
||||
|
||||
This install is for the optional tests only. The public guide does not tell users to bypass the dependency resolver. PyPI `pylance` 13.0.0 requires `lance-namespace<0.12`, and `lancedb==0.41.0b10` requires `lance-namespace>=0.13`, so `lancedb[pylance]` does not resolve. The three tests passed with pylance installed after the base requirements, without its own dependency pin.
|
||||
|
||||
```shell
|
||||
python3.13 -m venv .venv-pylance
|
||||
.venv-pylance/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt
|
||||
.venv-pylance/bin/pip install --no-deps pylance==13.0.0
|
||||
.venv-pylance/bin/python -m pytest docs/web-tests/blob-v2/py/test_blob_pylance.py
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
`@lancedb/lancedb@0.41.0-beta.8`. Node.js 22.6 or newer. `npm test` passes `--experimental-strip-types`, which Node added in 22.6.0.
|
||||
|
||||
```shell
|
||||
cd docs/web-tests/blob-v2/ts
|
||||
npm ci
|
||||
npm test
|
||||
```
|
||||
|
||||
## Rust
|
||||
|
||||
crates.io `lancedb` 0.40.0 does not include `blob()`. This example builds the workspace crate, `lancedb` 0.41.0-beta.10. Pass `--features remote` so this checkout compiles. The example uses a local database. The Rust workflow runs this example. It is not a default feature, so a workspace build without `remote` does not turn that feature on for the rest of the workspace.
|
||||
|
||||
```shell
|
||||
cargo run -p lancedb-blob-v2-docs --features remote --example multimodal
|
||||
```
|
||||
|
||||
## CI
|
||||
|
||||
Python and TypeScript above install preview packages. Pre-release builds are not guaranteed to stay available for more than 6 months, so those runs are not required PR checks. Run them when the guide's pins change. The Rust example is the in-repo check.
|
||||
|
||||
Regenerate snippets from the repository root:
|
||||
|
||||
```shell
|
||||
python3 docs/web-tests/mdx_snippets_gen.py \
|
||||
-s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \
|
||||
-s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \
|
||||
-o docs/web/snippets
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
asyncio_mode = auto
|
||||
testpaths = test_multimodal.py
|
||||
@@ -0,0 +1,8 @@
|
||||
--extra-index-url https://pypi.fury.io/lancedb/
|
||||
|
||||
lancedb==0.41.0b10
|
||||
numpy==2.2.6
|
||||
pandas==2.3.3
|
||||
pillow==12.1.1
|
||||
pytest==8.4.2
|
||||
pytest-asyncio==1.2.0
|
||||
@@ -0,0 +1,154 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Blob reads that import pylance.
|
||||
|
||||
Install pylance==13.0.0 with --no-deps after lancedb==0.41.0b10.
|
||||
See docs/web-tests/blob-v2/README.md.
|
||||
"""
|
||||
|
||||
import lance
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
|
||||
def test_blob_api_to_pandas(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
lancedb.blob("video"),
|
||||
]
|
||||
)
|
||||
tbl = db.create_table(
|
||||
"videos",
|
||||
data=[
|
||||
{"id": 1, "video": b"fake_video_bytes_1"},
|
||||
{"id": 2, "video": b"fake_video_bytes_2"},
|
||||
],
|
||||
schema=schema,
|
||||
mode="overwrite",
|
||||
)
|
||||
|
||||
# --8<-- [start:blob_api_to_pandas]
|
||||
df_lazy = tbl.to_pandas()
|
||||
|
||||
df_bytes = tbl.to_pandas(blob_mode="bytes")
|
||||
|
||||
df_desc = tbl.to_pandas(blob_mode="descriptions")
|
||||
|
||||
arrow_bytes = tbl.to_arrow(blob_mode="bytes")
|
||||
|
||||
df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)
|
||||
# --8<-- [end:blob_api_to_pandas]
|
||||
|
||||
assert len(df_lazy) == 2
|
||||
assert all(isinstance(value, lance.BlobFile) for value in df_lazy["video"])
|
||||
assert isinstance(df_bytes["video"].iloc[0], bytes)
|
||||
assert df_bytes["video"].tolist() == [
|
||||
b"fake_video_bytes_1",
|
||||
b"fake_video_bytes_2",
|
||||
]
|
||||
assert arrow_bytes["video"].to_pylist() == [
|
||||
b"fake_video_bytes_1",
|
||||
b"fake_video_bytes_2",
|
||||
]
|
||||
assert "_rowid" not in df_bytes.columns
|
||||
assert len(df_desc) == 2
|
||||
assert set(df_desc["video"].iloc[0]) == {
|
||||
"kind",
|
||||
"position",
|
||||
"size",
|
||||
"blob_id",
|
||||
"blob_uri",
|
||||
}
|
||||
assert len(df_typed) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_to_pandas_kwargs(tmp_path):
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 128)),
|
||||
lancedb.blob("video"),
|
||||
]
|
||||
)
|
||||
data = [
|
||||
{
|
||||
"id": i,
|
||||
"vector": np.random.rand(128).astype(np.float32),
|
||||
"video": f"fake_video_bytes_{i}".encode(),
|
||||
}
|
||||
for i in range(10)
|
||||
]
|
||||
|
||||
db = lancedb.connect(tmp_path / "sync")
|
||||
tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite")
|
||||
|
||||
async_db = await lancedb.connect_async(str(tmp_path / "async"))
|
||||
tbl_async = await async_db.create_table(
|
||||
"search_demo", data=data, schema=schema, mode="overwrite"
|
||||
)
|
||||
|
||||
query_vector = np.random.rand(128).astype(np.float32)
|
||||
|
||||
# --8<-- [start:query_to_pandas_kwargs]
|
||||
df_lazy = (
|
||||
tbl.search().where("id = 1").select(["id", "video"]).to_pandas(blob_mode="lazy")
|
||||
)
|
||||
|
||||
df_bytes = await (
|
||||
tbl_async.query()
|
||||
.where("id = 1")
|
||||
.select(["id", "video"])
|
||||
.to_pandas(blob_mode="bytes")
|
||||
)
|
||||
|
||||
df_vec = (
|
||||
tbl.search(query_vector)
|
||||
.limit(2)
|
||||
.select(["id", "video"])
|
||||
.to_pandas(blob_mode="bytes", split_blocks=True, self_destruct=True)
|
||||
)
|
||||
# --8<-- [end:query_to_pandas_kwargs]
|
||||
|
||||
assert len(df_lazy) == 1
|
||||
assert "_rowid" not in df_bytes.columns
|
||||
assert len(df_bytes) == 1
|
||||
assert df_bytes["video"].iloc[0] == b"fake_video_bytes_1"
|
||||
assert len(df_vec) == 2
|
||||
assert isinstance(df_vec["video"].iloc[0], bytes)
|
||||
|
||||
|
||||
def test_append_keeps_table_blob_thresholds(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
lancedb.blob("video", inline_size_threshold=64 * 1024),
|
||||
]
|
||||
)
|
||||
tbl = db.create_table("videos", schema=schema)
|
||||
other = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
lancedb.blob("video", inline_size_threshold=8 * 1024),
|
||||
]
|
||||
)
|
||||
payload = b"x" * (20 * 1024)
|
||||
tbl.add(
|
||||
pa.table(
|
||||
[pa.array([1], type=pa.int64()), lance.blob_array([payload])],
|
||||
schema=other,
|
||||
)
|
||||
)
|
||||
|
||||
stored = tbl.schema.field("video").metadata[
|
||||
b"lance-encoding:blob-inline-size-threshold"
|
||||
]
|
||||
assert stored == b"65536"
|
||||
descriptor = tbl.search().select(["video"]).to_arrow(blob_mode="descriptions")
|
||||
assert descriptor.column("video")[0].as_py()["kind"] == 0
|
||||
@@ -0,0 +1,204 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import importlib.util
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
|
||||
if importlib.util.find_spec("lance") is not None:
|
||||
raise RuntimeError(
|
||||
"Blob v2 documentation tests must run without pylance. "
|
||||
"Install docs/web-tests/blob-v2/py/requirements.txt into a fresh virtualenv."
|
||||
)
|
||||
|
||||
INLINE_MAX = 64 * 1024
|
||||
DEDICATED_MIN = 4 * 1024 * 1024
|
||||
|
||||
|
||||
def test_blob_api_definition(tmp_path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
# --8<-- [start:blob_api_setup]
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("./blob_db")
|
||||
# --8<-- [end:blob_api_setup]
|
||||
assert db.list_tables().tables == []
|
||||
|
||||
# --8<-- [start:blob_api_schema]
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("label", pa.string()),
|
||||
lancedb.blob("image"),
|
||||
]
|
||||
)
|
||||
# --8<-- [end:blob_api_schema]
|
||||
image = schema.field("image").type
|
||||
assert image.extension_name == "lance.blob.v2"
|
||||
assert type(image).__module__ == "lancedb.schema"
|
||||
|
||||
# --8<-- [start:blob_api_ingest]
|
||||
import io
|
||||
from PIL import Image
|
||||
|
||||
def jpeg_with_make(color, make):
|
||||
image = Image.new("RGB", (8, 8), color=color)
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = make
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="JPEG", exif=exif)
|
||||
return buf.getvalue()
|
||||
|
||||
tbl = db.create_table(
|
||||
"photos",
|
||||
data=[
|
||||
{"id": 1, "label": "red", "image": jpeg_with_make("red", "TestCam")},
|
||||
{"id": 2, "label": "blue", "image": jpeg_with_make("blue", "OtherCam")},
|
||||
],
|
||||
schema=schema,
|
||||
mode="overwrite",
|
||||
)
|
||||
# --8<-- [end:blob_api_ingest]
|
||||
assert len(tbl) == 2
|
||||
|
||||
# --8<-- [start:blob_api_bytes]
|
||||
rows = (
|
||||
tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes")
|
||||
)
|
||||
# --8<-- [end:blob_api_bytes]
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["id"] == 1
|
||||
assert "_rowid" not in rows[0]
|
||||
assert rows[0]["image"].startswith(b"\xff\xd8")
|
||||
|
||||
# --8<-- [start:blob_api_files]
|
||||
from PIL import ExifTags
|
||||
|
||||
rows = tbl.search().where("id = 1").select(["label"]).with_row_id(True).to_list()
|
||||
with tbl.fetch_blob_files("image", [rows[0]["_rowid"]])[0] as image_file:
|
||||
make = Image.open(image_file).getexif().get(ExifTags.Base.Make)
|
||||
print(rows[0]["label"], make)
|
||||
# --8<-- [end:blob_api_files]
|
||||
assert rows[0]["label"] == "red"
|
||||
assert make == "TestCam"
|
||||
|
||||
# --8<-- [start:blob_api_fetch]
|
||||
rows = tbl.search().select(["id"]).with_row_id(True).to_list()
|
||||
row_ids = [row["_rowid"] for row in rows]
|
||||
payloads = tbl.fetch_blobs("image", row_ids)
|
||||
# --8<-- [end:blob_api_fetch]
|
||||
assert all(payload.startswith(b"\xff\xd8") for payload in payloads.to_pylist())
|
||||
|
||||
# --8<-- [start:blob_api_ranges]
|
||||
slices = tbl.fetch_blob_ranges("image", [(row_ids[0], 0, 2)])
|
||||
|
||||
with tbl.fetch_blob_files("image", [row_ids[0]])[0] as image_file:
|
||||
parts = image_file.read_ranges([(0, 2)])
|
||||
# --8<-- [end:blob_api_ranges]
|
||||
assert slices.to_pylist() == [b"\xff\xd8"]
|
||||
assert parts == [b"\xff\xd8"]
|
||||
|
||||
|
||||
def test_eager_query_returns_blob_bytes_without_row_id(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
payload = b"inline-bytes"
|
||||
tbl = db.create_table(
|
||||
"photos",
|
||||
data=[{"id": 1, "image": payload}],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
rows = (
|
||||
tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes")
|
||||
)
|
||||
arrow_bytes = (
|
||||
tbl.search().where("id = 1").select(["id", "image"]).to_arrow(blob_mode="bytes")
|
||||
)
|
||||
described = tbl.to_pandas(blob_mode="descriptions")
|
||||
|
||||
assert rows == [{"id": 1, "image": payload}]
|
||||
assert "_rowid" not in rows[0]
|
||||
assert arrow_bytes.column("image").to_pylist() == [payload]
|
||||
assert "_rowid" not in arrow_bytes.column_names
|
||||
assert described["image"].iloc[0]["kind"] == 0
|
||||
|
||||
|
||||
def test_deferred_fetch_reads_blob_by_row_id(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
payload = b"deferred-bytes"
|
||||
tbl = db.create_table(
|
||||
"photos",
|
||||
data=[{"id": 1, "image": payload}],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
described = (
|
||||
tbl.search()
|
||||
.where("id = 1")
|
||||
.select(["id", "image"])
|
||||
.to_list(blob_mode="descriptions")
|
||||
)
|
||||
assert described[0]["image"]["kind"] == 0
|
||||
assert "_rowid" not in described[0]
|
||||
|
||||
found = tbl.search().where("id = 1").select(["id"]).with_row_id(True).to_list()
|
||||
row_id = found[0]["_rowid"]
|
||||
fetched = tbl.fetch_blobs("image", [row_id]).to_pylist()
|
||||
with tbl.fetch_blob_files("image", [row_id])[0] as handle:
|
||||
streamed = handle.read()
|
||||
|
||||
assert fetched == [payload]
|
||||
assert streamed == payload
|
||||
|
||||
|
||||
def _marked(size, marker):
|
||||
payload = bytearray(size)
|
||||
payload[0] = marker
|
||||
payload[-1] = marker
|
||||
return bytes(payload)
|
||||
|
||||
|
||||
def test_storage_tiers_round_trip(tmp_path):
|
||||
cases = [
|
||||
(1, _marked(INLINE_MAX, 11), 0),
|
||||
(2, _marked(INLINE_MAX + 1, 22), 1),
|
||||
(3, _marked(DEDICATED_MIN, 33), 1),
|
||||
(4, _marked(DEDICATED_MIN + 1, 44), 2),
|
||||
]
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
tbl = db.create_table(
|
||||
"tiers",
|
||||
data=[{"id": row_id, "image": payload} for row_id, payload, _kind in cases],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
described = {
|
||||
row["id"]: row["image"]
|
||||
for row in tbl.search()
|
||||
.select(["id", "image"])
|
||||
.to_list(blob_mode="descriptions")
|
||||
}
|
||||
located = {
|
||||
row["id"]: row["_rowid"]
|
||||
for row in tbl.search().select(["id"]).with_row_id(True).to_list()
|
||||
}
|
||||
fetched = {
|
||||
row_id: tbl.fetch_blobs("image", [located[row_id]]).to_pylist()[0]
|
||||
for row_id, _payload, _kind in cases
|
||||
}
|
||||
|
||||
for row_id, payload, kind in cases:
|
||||
descriptor = described[row_id]
|
||||
assert descriptor["kind"] == kind
|
||||
assert descriptor["size"] == len(payload)
|
||||
assert fetched[row_id] == payload
|
||||
with tbl.fetch_blob_files("image", [located[row_id]])[0] as handle:
|
||||
assert handle.read_range(0, 1) == payload[:1]
|
||||
assert handle.read_range(len(payload) - 1, 1) == payload[-1:]
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "lancedb-blob-v2-docs"
|
||||
version = "0.0.0"
|
||||
edition.workspace = true
|
||||
publish = false
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
remote = ["lancedb/remote"]
|
||||
|
||||
[dependencies]
|
||||
arrow-array = { workspace = true }
|
||||
arrow-schema = { workspace = true }
|
||||
futures-util = "0.3"
|
||||
lancedb = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
[[example]]
|
||||
name = "multimodal"
|
||||
path = "multimodal.rs"
|
||||
@@ -0,0 +1,344 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
// --8<-- [start:blob_api_imports]
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_array::{
|
||||
Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use futures_util::TryStreamExt;
|
||||
use lancedb::blob::{BlobRangeRequest, blob};
|
||||
use lancedb::connect;
|
||||
use lancedb::database::CreateTableMode;
|
||||
use lancedb::query::{ExecutableQuery, QueryBase};
|
||||
// --8<-- [end:blob_api_imports]
|
||||
|
||||
use arrow_array::{StructArray, UInt8Array};
|
||||
|
||||
const INLINE_MAX: usize = 64 * 1024;
|
||||
const DEDICATED_MIN: usize = 4 * 1024 * 1024;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tutorial().await;
|
||||
deferred_fetch().await;
|
||||
storage_tiers().await;
|
||||
}
|
||||
|
||||
async fn tutorial() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let original_dir = std::env::current_dir().unwrap();
|
||||
std::env::set_current_dir(temp_dir.path()).unwrap();
|
||||
|
||||
// --8<-- [start:blob_api_setup]
|
||||
let db = connect("./blob_db").execute().await.unwrap();
|
||||
// --8<-- [end:blob_api_setup]
|
||||
|
||||
// --8<-- [start:blob_api_schema]
|
||||
let blob_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
Field::new("label", DataType::Utf8, true),
|
||||
blob("image", true),
|
||||
]));
|
||||
// --8<-- [end:blob_api_schema]
|
||||
|
||||
// --8<-- [start:blob_api_ingest]
|
||||
let blob_table = db
|
||||
.create_empty_table("photos", blob_schema)
|
||||
.mode(CreateTableMode::Overwrite)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let input_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
Field::new("label", DataType::Utf8, true),
|
||||
Field::new("image", DataType::LargeBinary, true),
|
||||
]));
|
||||
let input_batch = RecordBatch::try_new(
|
||||
input_schema.clone(),
|
||||
vec![
|
||||
Arc::new(Int64Array::from(vec![1_i64, 2_i64])),
|
||||
Arc::new(StringArray::from(vec![Some("door"), Some("window")])),
|
||||
Arc::new(LargeBinaryArray::from_iter_values([
|
||||
b"inline_image_bytes".as_slice(),
|
||||
b"second_image_bytes".as_slice(),
|
||||
])),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let input_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(
|
||||
RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema),
|
||||
);
|
||||
blob_table.add(input_reader).execute().await.unwrap();
|
||||
// --8<-- [end:blob_api_ingest]
|
||||
assert_eq!(blob_table.count_rows(None).await.unwrap(), 2);
|
||||
|
||||
// --8<-- [start:blob_api_files]
|
||||
let batches = blob_table
|
||||
.query()
|
||||
.with_row_id()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let row_ids = batches[0]
|
||||
.column_by_name("_rowid")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap()
|
||||
.values()
|
||||
.to_vec();
|
||||
|
||||
let handles = blob_table
|
||||
.fetch_blob_files("image", &row_ids[..1])
|
||||
.await
|
||||
.unwrap();
|
||||
let header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap();
|
||||
handles[0].as_ref().unwrap().close().await.unwrap();
|
||||
// --8<-- [end:blob_api_files]
|
||||
assert_eq!(header.as_ref(), b"inline");
|
||||
|
||||
// --8<-- [start:blob_api_fetch]
|
||||
let payloads = blob_table.fetch_blobs("image", &row_ids).await.unwrap();
|
||||
// --8<-- [end:blob_api_fetch]
|
||||
assert_eq!(payloads.len(), 2);
|
||||
|
||||
// --8<-- [start:blob_api_ranges]
|
||||
let slices = blob_table
|
||||
.fetch_blob_ranges(
|
||||
"image",
|
||||
[
|
||||
BlobRangeRequest::new(row_ids[0], 0, 6),
|
||||
BlobRangeRequest::new(row_ids[1], 0, 6),
|
||||
BlobRangeRequest::new(row_ids[1], 7, 5),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let second_handles = blob_table
|
||||
.fetch_blob_files("image", &row_ids[1..2])
|
||||
.await
|
||||
.unwrap();
|
||||
let second_image = second_handles[0].as_ref().unwrap();
|
||||
let parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap();
|
||||
second_image.close().await.unwrap();
|
||||
// --8<-- [end:blob_api_ranges]
|
||||
assert_eq!(slices.value(0), b"inline");
|
||||
assert_eq!(slices.value(1), b"second");
|
||||
assert_eq!(slices.value(2), b"image");
|
||||
assert_eq!(parts[0].as_ref(), b"second");
|
||||
assert_eq!(parts[1].as_ref(), b"image");
|
||||
|
||||
std::env::set_current_dir(original_dir).unwrap();
|
||||
}
|
||||
|
||||
async fn deferred_fetch() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(temp_dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
blob("image", true),
|
||||
]));
|
||||
let table = db
|
||||
.create_empty_table("photos", schema)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let input_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
Field::new("image", DataType::LargeBinary, true),
|
||||
]));
|
||||
let batch = RecordBatch::try_new(
|
||||
input_schema.clone(),
|
||||
vec![
|
||||
Arc::new(Int64Array::from(vec![1_i64])),
|
||||
Arc::new(LargeBinaryArray::from_iter_values([
|
||||
b"deferred-bytes".as_slice()
|
||||
])),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(
|
||||
RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema),
|
||||
);
|
||||
table.add(reader).execute().await.unwrap();
|
||||
|
||||
let described = table
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(descriptor_kind(&described[0], 0), 0);
|
||||
assert!(described[0].column_by_name("_rowid").is_none());
|
||||
|
||||
let located = table
|
||||
.query()
|
||||
.with_row_id()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let row_id = located[0]
|
||||
.column_by_name("_rowid")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap()
|
||||
.value(0);
|
||||
let payloads = table.fetch_blobs("image", &[row_id]).await.unwrap();
|
||||
let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap();
|
||||
let streamed = handles[0]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.read_range(0..payloads.value(0).len() as u64)
|
||||
.await
|
||||
.unwrap();
|
||||
handles[0].as_ref().unwrap().close().await.unwrap();
|
||||
|
||||
assert_eq!(payloads.value(0), b"deferred-bytes");
|
||||
assert_eq!(streamed.as_ref(), b"deferred-bytes");
|
||||
}
|
||||
|
||||
async fn storage_tiers() {
|
||||
let cases = [
|
||||
(1_i64, marked(INLINE_MAX, 11), 0_u8),
|
||||
(2_i64, marked(INLINE_MAX + 1, 22), 1_u8),
|
||||
(3_i64, marked(DEDICATED_MIN, 33), 1_u8),
|
||||
(4_i64, marked(DEDICATED_MIN + 1, 44), 2_u8),
|
||||
];
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let db = connect(temp_dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
blob("image", true),
|
||||
]));
|
||||
let table = db
|
||||
.create_empty_table("tiers", schema)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let input_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
Field::new("image", DataType::LargeBinary, true),
|
||||
]));
|
||||
let batch = RecordBatch::try_new(
|
||||
input_schema.clone(),
|
||||
vec![
|
||||
Arc::new(Int64Array::from_iter_values(cases.iter().map(|row| row.0))),
|
||||
Arc::new(LargeBinaryArray::from_iter_values(
|
||||
cases.iter().map(|row| row.1.as_slice()),
|
||||
)),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(
|
||||
RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema),
|
||||
);
|
||||
table.add(reader).execute().await.unwrap();
|
||||
|
||||
let described = table
|
||||
.query()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let located = table
|
||||
.query()
|
||||
.with_row_id()
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut kind_by_id = std::collections::HashMap::new();
|
||||
for batch in &described {
|
||||
let ids = batch
|
||||
.column_by_name("id")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<Int64Array>()
|
||||
.unwrap();
|
||||
for row in 0..batch.num_rows() {
|
||||
kind_by_id.insert(ids.value(row), descriptor_kind(batch, row));
|
||||
}
|
||||
}
|
||||
let mut row_id_by_id = std::collections::HashMap::new();
|
||||
for batch in &located {
|
||||
let ids = batch
|
||||
.column_by_name("id")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<Int64Array>()
|
||||
.unwrap();
|
||||
let row_ids = batch
|
||||
.column_by_name("_rowid")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap();
|
||||
for row in 0..batch.num_rows() {
|
||||
row_id_by_id.insert(ids.value(row), row_ids.value(row));
|
||||
}
|
||||
}
|
||||
|
||||
for (id, payload, kind) in &cases {
|
||||
assert_eq!(kind_by_id[id], *kind);
|
||||
let row_id = row_id_by_id[id];
|
||||
let fetched = table.fetch_blobs("image", &[row_id]).await.unwrap();
|
||||
assert_eq!(fetched.value(0), payload.as_slice());
|
||||
let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap();
|
||||
let handle = handles[0].as_ref().unwrap();
|
||||
let head = handle.read_range(0..1).await.unwrap();
|
||||
let tail = handle
|
||||
.read_range((payload.len() - 1) as u64..payload.len() as u64)
|
||||
.await
|
||||
.unwrap();
|
||||
handle.close().await.unwrap();
|
||||
assert_eq!(head.as_ref(), &payload[..1]);
|
||||
assert_eq!(tail.as_ref(), &payload[payload.len() - 1..]);
|
||||
}
|
||||
}
|
||||
|
||||
fn marked(size: usize, marker: u8) -> Vec<u8> {
|
||||
let mut payload = vec![0_u8; size];
|
||||
payload[0] = marker;
|
||||
payload[size - 1] = marker;
|
||||
payload
|
||||
}
|
||||
|
||||
fn descriptor_kind(batch: &RecordBatch, row: usize) -> u8 {
|
||||
let image = batch
|
||||
.column_by_name("image")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<StructArray>()
|
||||
.unwrap_or_else(|| panic!("image column was {}", batch.schema()));
|
||||
image
|
||||
.column_by_name("kind")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<UInt8Array>()
|
||||
.unwrap()
|
||||
.value(row)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { chdir, cwd } from "node:process";
|
||||
import { test } from "node:test";
|
||||
import * as arrow from "apache-arrow";
|
||||
import { Buffer } from "node:buffer";
|
||||
import * as lancedb from "@lancedb/lancedb";
|
||||
|
||||
const INLINE_MAX = 64 * 1024;
|
||||
const DEDICATED_MIN = 4 * 1024 * 1024;
|
||||
|
||||
function marked(size: number, marker: number): Buffer {
|
||||
const payload = Buffer.alloc(size);
|
||||
payload[0] = marker;
|
||||
payload[payload.length - 1] = marker;
|
||||
return payload;
|
||||
}
|
||||
|
||||
function kindOf(value: unknown): number {
|
||||
assert.equal(typeof value, "object");
|
||||
assert.ok(value !== null);
|
||||
const kind = (value as { kind?: unknown }).kind;
|
||||
assert.equal(typeof kind, "number");
|
||||
return kind;
|
||||
}
|
||||
|
||||
test("blob column tutorial", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "blob-v2-"));
|
||||
const previous = cwd();
|
||||
chdir(directory);
|
||||
try {
|
||||
// --8<-- [start:blob_api_setup]
|
||||
const db = await lancedb.connect("./blob_db");
|
||||
// --8<-- [end:blob_api_setup]
|
||||
|
||||
// --8<-- [start:blob_api_schema]
|
||||
const blobSchema = new arrow.Schema([
|
||||
new arrow.Field("id", new arrow.Int64()),
|
||||
new arrow.Field("label", new arrow.Utf8()),
|
||||
lancedb.blob("image"),
|
||||
]);
|
||||
// --8<-- [end:blob_api_schema]
|
||||
|
||||
// --8<-- [start:blob_api_ingest]
|
||||
const blobTable = await db.createEmptyTable("photos", blobSchema, {
|
||||
mode: "overwrite",
|
||||
});
|
||||
|
||||
await blobTable.add([
|
||||
{ id: 1n, label: "door", image: Buffer.from("inline_image_bytes") },
|
||||
{ id: 2n, label: "window", image: Buffer.from("second_image_bytes") },
|
||||
]);
|
||||
// --8<-- [end:blob_api_ingest]
|
||||
assert.equal(await blobTable.countRows(), 2);
|
||||
|
||||
// --8<-- [start:blob_api_files]
|
||||
const rows = await blobTable
|
||||
.query()
|
||||
.select(["id", "label"])
|
||||
.withRowId()
|
||||
.toArray();
|
||||
const rowIds = rows.map((row) => row._rowid as bigint);
|
||||
|
||||
const [image] = await blobTable.fetchBlobFiles("image", [rowIds[0]!]);
|
||||
const header = await image!.readRange(0n, 6n);
|
||||
await image!.close();
|
||||
// --8<-- [end:blob_api_files]
|
||||
assert.equal(header.toString("utf8"), "inline");
|
||||
|
||||
// --8<-- [start:blob_api_fetch]
|
||||
const payloads = await blobTable.fetchBlobs("image", rowIds);
|
||||
// --8<-- [end:blob_api_fetch]
|
||||
assert.equal(payloads.length, 2);
|
||||
|
||||
// --8<-- [start:blob_api_ranges]
|
||||
const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]);
|
||||
const parts = await secondImage!.readRanges([
|
||||
{ start: 0n, end: 6n },
|
||||
{ start: 7n, end: 12n },
|
||||
]);
|
||||
await secondImage!.close();
|
||||
// --8<-- [end:blob_api_ranges]
|
||||
assert.deepEqual(
|
||||
parts.map((part) => part.toString("utf8")),
|
||||
["second", "image"],
|
||||
);
|
||||
|
||||
// --8<-- [start:blob_api_bytes_mode]
|
||||
const withBytes = await blobTable
|
||||
.query()
|
||||
.select(["id", "image"])
|
||||
.toArray({ blobMode: "bytes" });
|
||||
const firstImage: Uint8Array | null = withBytes[0].image;
|
||||
// --8<-- [end:blob_api_bytes_mode]
|
||||
assert.equal(Buffer.from(firstImage!).toString("utf8"), "inline_image_bytes");
|
||||
assert.equal(Object.hasOwn(withBytes[0], "_rowid"), false);
|
||||
} finally {
|
||||
chdir(previous);
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("eager query returns blob bytes without a row id", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "blob-v2-eager-"));
|
||||
try {
|
||||
const db = await lancedb.connect(directory);
|
||||
const schema = new arrow.Schema([
|
||||
new arrow.Field("id", new arrow.Int64()),
|
||||
lancedb.blob("image"),
|
||||
]);
|
||||
const table = await db.createEmptyTable("photos", schema);
|
||||
const payload = Buffer.from("inline-bytes");
|
||||
await table.add([{ id: 1n, image: payload }]);
|
||||
|
||||
const rows = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select(["id", "image"])
|
||||
.toArray({ blobMode: "bytes" });
|
||||
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(Object.hasOwn(rows[0], "_rowid"), false);
|
||||
assert.equal(Buffer.from(rows[0].image).toString("utf8"), "inline-bytes");
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("deferred fetch reads a blob by row id", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "blob-v2-deferred-"));
|
||||
try {
|
||||
const db = await lancedb.connect(directory);
|
||||
const schema = new arrow.Schema([
|
||||
new arrow.Field("id", new arrow.Int64()),
|
||||
lancedb.blob("image"),
|
||||
]);
|
||||
const table = await db.createEmptyTable("photos", schema);
|
||||
await table.add([{ id: 1n, image: Buffer.from("deferred-bytes") }]);
|
||||
|
||||
const described = await table
|
||||
.query()
|
||||
.where("id = 1")
|
||||
.select(["id", "image"])
|
||||
.toArray();
|
||||
assert.equal(kindOf(described[0].image), 0);
|
||||
assert.equal(Object.hasOwn(described[0], "_rowid"), false);
|
||||
|
||||
const found = await table.query().where("id = 1").select(["id"]).withRowId().toArray();
|
||||
const rowId = found[0]._rowid as bigint;
|
||||
const payloads = await table.fetchBlobs("image", [rowId]);
|
||||
const [handle] = await table.fetchBlobFiles("image", [rowId]);
|
||||
const streamed = await handle!.readRange(0n, handle!.size());
|
||||
await handle!.close();
|
||||
|
||||
assert.equal(Buffer.from(payloads[0]).toString("utf8"), "deferred-bytes");
|
||||
assert.equal(Buffer.from(streamed).toString("utf8"), "deferred-bytes");
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("storage tiers round-trip", async () => {
|
||||
const cases = [
|
||||
{ id: 1n, image: marked(INLINE_MAX, 11), kind: 0 },
|
||||
{ id: 2n, image: marked(INLINE_MAX + 1, 22), kind: 1 },
|
||||
{ id: 3n, image: marked(DEDICATED_MIN, 33), kind: 1 },
|
||||
{ id: 4n, image: marked(DEDICATED_MIN + 1, 44), kind: 2 },
|
||||
];
|
||||
const directory = mkdtempSync(join(tmpdir(), "blob-v2-tiers-"));
|
||||
try {
|
||||
const db = await lancedb.connect(directory);
|
||||
const schema = new arrow.Schema([
|
||||
new arrow.Field("id", new arrow.Int64()),
|
||||
lancedb.blob("image"),
|
||||
]);
|
||||
const table = await db.createEmptyTable("tiers", schema);
|
||||
await table.add(cases.map(({ id, image }) => ({ id, image })));
|
||||
|
||||
const described = await table.query().select(["id", "image"]).toArray();
|
||||
const located = await table.query().select(["id"]).withRowId().toArray();
|
||||
const rowIdByValue = new Map(located.map((row) => [row.id as bigint, row._rowid as bigint]));
|
||||
|
||||
for (const item of cases) {
|
||||
const descriptor = described.find((row) => row.id === item.id);
|
||||
assert.ok(descriptor);
|
||||
assert.equal(kindOf(descriptor.image), item.kind);
|
||||
const rowId = rowIdByValue.get(item.id);
|
||||
assert.ok(rowId !== undefined);
|
||||
const [payload] = await table.fetchBlobs("image", [rowId]);
|
||||
assert.deepEqual(Buffer.from(payload), item.image);
|
||||
const [handle] = await table.fetchBlobFiles("image", [rowId]);
|
||||
const streamed = await handle!.read();
|
||||
await handle!.close();
|
||||
assert.deepEqual(streamed, item.image);
|
||||
}
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
+1565
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "lancedb-blob-v2-docs",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --experimental-strip-types --test multimodal.test.ts"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lancedb/lancedb": "0.41.0-beta.8",
|
||||
"apache-arrow": "21.2.0"
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,36 @@ import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
|
||||
def test_compaction_tuning(mem_db):
|
||||
payload = b"x" * 1016
|
||||
table = mem_db.create_table(
|
||||
"compaction_tuning", [{"id": i, "payload": payload} for i in range(32)]
|
||||
)
|
||||
table.add([{"id": i, "payload": payload} for i in range(32, 64)])
|
||||
assert table.stats()["fragment_stats"]["num_fragments"] == 2
|
||||
|
||||
# --8<-- [start:storage_compaction_tuning]
|
||||
from lancedb import CompactionOptions
|
||||
|
||||
desired_fragment_bytes = 64 * 1024
|
||||
average_row_bytes = 1024 # Estimate from representative rows.
|
||||
options: CompactionOptions = {
|
||||
"target_rows_per_fragment": max(1, desired_fragment_bytes // average_row_bytes),
|
||||
"batch_size": 16,
|
||||
"num_threads": 1,
|
||||
}
|
||||
table.optimize(compaction_options=options)
|
||||
# --8<-- [end:storage_compaction_tuning]
|
||||
|
||||
assert table.stats()["fragment_stats"]["num_fragments"] == 1
|
||||
assert table.count_rows() == 64
|
||||
|
||||
table.add([{"id": 64, "payload": payload}])
|
||||
table.optimize(compaction_options=options)
|
||||
assert table.stats()["fragment_stats"]["num_fragments"] == 2
|
||||
assert sorted(table.to_arrow()["id"].to_pylist()) == list(range(65))
|
||||
|
||||
|
||||
def test_rebuild_vector_index(tmp_db):
|
||||
rng = np.random.default_rng(7)
|
||||
table = tmp_db.create_table(
|
||||
|
||||
@@ -50,6 +50,25 @@ def describe(value: float):
|
||||
return {"half": value / 2, "note": None}
|
||||
|
||||
|
||||
# --8<-- [start:function_class_define]
|
||||
@udf(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.
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
self.model = SentenceTransformer(model)
|
||||
|
||||
def __call__(self, text: str) -> list[float]:
|
||||
return self.model.encode(text).tolist()
|
||||
|
||||
def close(self):
|
||||
del self.model
|
||||
|
||||
|
||||
# --8<-- [end:function_class_define]
|
||||
|
||||
|
||||
# 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.
|
||||
SERVICE_REPLY = (
|
||||
@@ -166,6 +185,31 @@ def test_function_version_binds_a_column(tmp_path):
|
||||
table.add_columns({"doubled": application})
|
||||
|
||||
|
||||
def test_class_function_is_constructed_only_where_it_runs():
|
||||
# Registration reads __init__'s signature; it never constructs the class,
|
||||
# so the model's package need not be installed here.
|
||||
assert "sentence_transformers" not in sys.modules
|
||||
signature = embed.registration_request.signature
|
||||
assert [
|
||||
(field.name, field.arrow_type, field.nullable)
|
||||
for field in signature.initialization
|
||||
] == [("model", "utf8", True)]
|
||||
assert [(p.name, p.arrow_type) for p in signature.inputs] == [("text", "utf8")]
|
||||
assert "sentence_transformers" not in sys.modules
|
||||
|
||||
embedder = registered_version(embed)
|
||||
# --8<-- [start:function_class_apply]
|
||||
from lancedb import col
|
||||
|
||||
application = embedder(text=col("text"), model="all-mpnet-base-v2")
|
||||
# --8<-- [end:function_class_apply]
|
||||
assert application.initialization == {"model": "all-mpnet-base-v2"}
|
||||
# The default applies to an omitted field.
|
||||
assert embedder(text=col("text")).initialization == {}
|
||||
with pytest.raises(TypeError, match="unknown arguments"):
|
||||
embedder(text=col("text"), device="cuda")
|
||||
|
||||
|
||||
def test_function_enterprise(monkeypatch):
|
||||
require_deployment()
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ def test_embedding_cohere_usage() -> None:
|
||||
cohere = (
|
||||
EmbeddingFunctionRegistry.get_instance()
|
||||
.get("cohere")
|
||||
.create(name="embed-multilingual-v2.0")
|
||||
.create(name="embed-multilingual-v3.0")
|
||||
)
|
||||
|
||||
class TextModel(LanceModel):
|
||||
|
||||
@@ -1,137 +1,134 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import io
|
||||
import pytest
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
|
||||
try:
|
||||
# --8<-- [start:multimodal_imports]
|
||||
import io
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import io
|
||||
from PIL import Image
|
||||
# --8<-- [end:multimodal_imports]
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# --8<-- [start:multimodal_imports]
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import io
|
||||
from PIL import Image
|
||||
# --8<-- [end:multimodal_imports]
|
||||
|
||||
def test_multimodal_ingestion(db_path_factory):
|
||||
# Ensure dependencies are available
|
||||
pytest.importorskip("PIL")
|
||||
pytest.importorskip("lancedb")
|
||||
pytest.importorskip("numpy")
|
||||
|
||||
# --8<-- [start:create_dummy_data]
|
||||
# Create some dummy images
|
||||
def create_dummy_image(color):
|
||||
img = Image.new('RGB', (100, 100), color=color)
|
||||
img = Image.new("RGB", (100, 100), color=color)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format='PNG')
|
||||
img.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
# Create dataset with metadata, vectors, and image blobs
|
||||
data = [
|
||||
{
|
||||
"id": 1,
|
||||
"filename": "red_square.png",
|
||||
"vector": np.random.rand(128).astype(np.float32),
|
||||
"image_blob": create_dummy_image('red'),
|
||||
"label": "red"
|
||||
"image_blob": create_dummy_image("red"),
|
||||
"label": "red",
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"filename": "blue_square.png",
|
||||
"vector": np.random.rand(128).astype(np.float32),
|
||||
"image_blob": create_dummy_image('blue'),
|
||||
"label": "blue"
|
||||
}
|
||||
"image_blob": create_dummy_image("blue"),
|
||||
"label": "blue",
|
||||
},
|
||||
]
|
||||
# --8<-- [end:create_dummy_data]
|
||||
|
||||
# --8<-- [start:define_schema]
|
||||
# Define schema explicitly to ensure image_blob is treated as binary
|
||||
schema = pa.schema([
|
||||
pa.field("id", pa.int32()),
|
||||
pa.field("filename", pa.string()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 128)),
|
||||
pa.field("image_blob", pa.binary()), # Important: Use pa.binary() for blobs
|
||||
pa.field("label", pa.string())
|
||||
])
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int32()),
|
||||
pa.field("filename", pa.string()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 128)),
|
||||
pa.field("image_blob", pa.binary()),
|
||||
pa.field("label", pa.string()),
|
||||
]
|
||||
)
|
||||
# --8<-- [end:define_schema]
|
||||
|
||||
db_uri = db_path_factory("multimodal_db")
|
||||
db = lancedb.connect(db_uri)
|
||||
db = lancedb.connect(db_path_factory("multimodal_db"))
|
||||
|
||||
# --8<-- [start:ingest_data]
|
||||
tbl = db.create_table("images", data=data, schema=schema, mode="overwrite")
|
||||
# --8<-- [end:ingest_data]
|
||||
|
||||
|
||||
assert len(tbl) == 2
|
||||
|
||||
# --8<-- [start:search_data]
|
||||
# Search for similar images
|
||||
query_vector = np.random.rand(128).astype(np.float32)
|
||||
results = tbl.search(query_vector).limit(1).to_pandas()
|
||||
# --8<-- [end:search_data]
|
||||
|
||||
# --8<-- [start:process_results]
|
||||
# Convert back to PIL Image
|
||||
for _, row in results.iterrows():
|
||||
image_bytes = row['image_blob']
|
||||
image_bytes = row["image_blob"]
|
||||
image = Image.open(io.BytesIO(image_bytes))
|
||||
print(f"Retrieved image: {row['filename']}, Size: {image.size}")
|
||||
# You can now use 'image' with other libraries or display it
|
||||
# --8<-- [end:process_results]
|
||||
|
||||
|
||||
assert len(results) == 1
|
||||
|
||||
def test_blob_api_definition(db_path_factory):
|
||||
# --8<-- [start:blob_api_schema]
|
||||
|
||||
def test_legacy_blob_api_definition(tmp_path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
# --8<-- [start:legacy_blob_api_schema]
|
||||
import pyarrow as pa
|
||||
|
||||
# Define schema with Blob API metadata for lazy loading
|
||||
schema = pa.schema([
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"} # Enable Blob API
|
||||
),
|
||||
])
|
||||
# --8<-- [end:blob_api_schema]
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"}, # Enable Blob API
|
||||
),
|
||||
]
|
||||
)
|
||||
# --8<-- [end:legacy_blob_api_schema]
|
||||
|
||||
# --8<-- [start:blob_api_ingest]
|
||||
# --8<-- [start:legacy_blob_api_ingest]
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect(db_path_factory("blob_db"))
|
||||
|
||||
db = lancedb.connect("./blob_db")
|
||||
|
||||
# Create sample data
|
||||
data = [
|
||||
{"id": 1, "video": b"fake_video_bytes_1"},
|
||||
{"id": 2, "video": b"fake_video_bytes_2"}
|
||||
{"id": 2, "video": b"fake_video_bytes_2"},
|
||||
]
|
||||
|
||||
|
||||
# Create the table
|
||||
tbl = db.create_table("videos", data=data, schema=schema)
|
||||
# --8<-- [end:blob_api_ingest]
|
||||
# --8<-- [end:legacy_blob_api_ingest]
|
||||
assert len(tbl) == 2
|
||||
|
||||
|
||||
def test_blob_api_to_pandas(db_path_factory):
|
||||
db = lancedb.connect(db_path_factory("blob_to_pandas_db"))
|
||||
schema = pa.schema([
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
])
|
||||
def test_legacy_blob_api_to_pandas(db_path_factory):
|
||||
db = lancedb.connect(db_path_factory("legacy_blob_to_pandas_db"))
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
)
|
||||
tbl = db.create_table(
|
||||
"videos",
|
||||
data=[
|
||||
@@ -142,7 +139,7 @@ def test_blob_api_to_pandas(db_path_factory):
|
||||
mode="overwrite",
|
||||
)
|
||||
|
||||
# --8<-- [start:blob_api_to_pandas]
|
||||
# --8<-- [start:legacy_blob_api_to_pandas]
|
||||
# Default: blob columns come back lazily
|
||||
df_lazy = tbl.to_pandas()
|
||||
|
||||
@@ -154,7 +151,7 @@ def test_blob_api_to_pandas(db_path_factory):
|
||||
|
||||
# Forward extra kwargs to PyArrow's to_pandas
|
||||
df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)
|
||||
# --8<-- [end:blob_api_to_pandas]
|
||||
# --8<-- [end:legacy_blob_api_to_pandas]
|
||||
|
||||
assert len(df_lazy) == 2
|
||||
assert isinstance(df_bytes["video"].iloc[0], bytes)
|
||||
@@ -167,16 +164,18 @@ def test_blob_api_to_pandas(db_path_factory):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_to_pandas_kwargs(db_path_factory):
|
||||
schema = pa.schema([
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 128)),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
])
|
||||
async def test_legacy_query_to_pandas_kwargs(db_path_factory):
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 128)),
|
||||
pa.field(
|
||||
"video",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
)
|
||||
data = [
|
||||
{
|
||||
"id": i,
|
||||
@@ -186,11 +185,11 @@ async def test_query_to_pandas_kwargs(db_path_factory):
|
||||
for i in range(10)
|
||||
]
|
||||
|
||||
db = lancedb.connect(db_path_factory("query_to_pandas_db"))
|
||||
db = lancedb.connect(db_path_factory("legacy_query_to_pandas_db"))
|
||||
tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite")
|
||||
|
||||
async_db = await lancedb.connect_async(
|
||||
str(db_path_factory("query_to_pandas_async_db"))
|
||||
str(db_path_factory("legacy_query_to_pandas_async_db"))
|
||||
)
|
||||
tbl_async = await async_db.create_table(
|
||||
"search_demo", data=data, schema=schema, mode="overwrite"
|
||||
@@ -198,7 +197,8 @@ async def test_query_to_pandas_kwargs(db_path_factory):
|
||||
|
||||
query_vector = np.random.rand(128).astype(np.float32)
|
||||
|
||||
# --8<-- [start:query_to_pandas_kwargs]
|
||||
# fmt: off
|
||||
# --8<-- [start:legacy_query_to_pandas_kwargs]
|
||||
# Plain scan query: blob_mode is supported end to end
|
||||
df_lazy = (
|
||||
tbl.search()
|
||||
@@ -223,7 +223,8 @@ async def test_query_to_pandas_kwargs(db_path_factory):
|
||||
.select(["id", "vector"])
|
||||
.to_pandas(split_blocks=True, self_destruct=True)
|
||||
)
|
||||
# --8<-- [end:query_to_pandas_kwargs]
|
||||
# --8<-- [end:legacy_query_to_pandas_kwargs]
|
||||
# fmt: on
|
||||
|
||||
assert len(df_lazy) == 1
|
||||
assert len(df_bytes) == 1
|
||||
|
||||
@@ -119,38 +119,35 @@ async def async_db(request, db_path_factory):
|
||||
await owned.drop_claimed()
|
||||
|
||||
|
||||
def create_characters(db):
|
||||
def create_frames(db):
|
||||
# --8<-- [start:quickstart_data]
|
||||
data = [
|
||||
{
|
||||
"id": "1",
|
||||
"name": "King Arthur",
|
||||
"role": "King",
|
||||
"description": "Leader of Camelot and wielder of Excalibur.",
|
||||
"stats": {"strength": 4, "magic": 1, "leadership": 5, "wisdom": 4},
|
||||
"vector": [0.7, 0.1, 0.9, 0.7],
|
||||
"frame_id": "1",
|
||||
"video_id": "clip-1",
|
||||
"caption": "a robot arm reaching toward a cup",
|
||||
"stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3},
|
||||
"embedding": [0.7, 0.1, 0.9, 0.7],
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "Merlin",
|
||||
"role": "Wizard",
|
||||
"description": "Advisor and prophet with deep magical knowledge.",
|
||||
"stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5},
|
||||
"vector": [0.2, 0.9, 0.4, 0.9],
|
||||
"frame_id": "2",
|
||||
"video_id": "clip-1",
|
||||
"caption": "a two-finger gripper closing on a cup",
|
||||
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
|
||||
"embedding": [0.2, 0.9, 0.4, 0.9],
|
||||
},
|
||||
{
|
||||
"id": "3",
|
||||
"name": "Sir Lancelot",
|
||||
"role": "Knight",
|
||||
"description": "Legendary knight known for courage and combat skill.",
|
||||
"stats": {"strength": 5, "magic": 1, "leadership": 3, "wisdom": 3},
|
||||
"vector": [0.9, 0.1, 0.5, 0.4],
|
||||
"frame_id": "3",
|
||||
"video_id": "clip-2",
|
||||
"caption": "a robot arm holding a cup steady",
|
||||
"stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4},
|
||||
"embedding": [0.9, 0.1, 0.5, 0.4],
|
||||
},
|
||||
]
|
||||
# --8<-- [end:quickstart_data]
|
||||
|
||||
# --8<-- [start:quickstart_create_table]
|
||||
table = db.create_table("characters", data=data, mode="overwrite")
|
||||
table = db.create_table("frames", data=data, mode="overwrite")
|
||||
# --8<-- [end:quickstart_create_table]
|
||||
assert table.count_rows() == 3
|
||||
|
||||
@@ -158,12 +155,11 @@ def create_characters(db):
|
||||
table.add(
|
||||
[
|
||||
{
|
||||
"id": "4",
|
||||
"name": "Morgana",
|
||||
"role": "Sorceress",
|
||||
"description": "Powerful sorceress of Avalon.",
|
||||
"stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 4},
|
||||
"vector": [0.3, 0.9, 0.6, 0.8],
|
||||
"frame_id": "4",
|
||||
"video_id": "clip-2",
|
||||
"caption": "a gripper lowering a cup onto the table",
|
||||
"stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2},
|
||||
"embedding": [0.3, 0.9, 0.6, 0.8],
|
||||
}
|
||||
]
|
||||
)
|
||||
@@ -173,153 +169,152 @@ def create_characters(db):
|
||||
|
||||
|
||||
def test_quickstart(db):
|
||||
table = create_characters(db)
|
||||
table = create_frames(db)
|
||||
|
||||
# --8<-- [start:quickstart_vector_search_1]
|
||||
# Search for examples similar to a "wise magical advisor"
|
||||
# Search for frames similar to "a gripper closing on an object"
|
||||
query_vector = [0.2, 0.8, 0.4, 0.9]
|
||||
|
||||
# Ensure you run `pip install polars` beforehand
|
||||
result = (
|
||||
table.search(query_vector)
|
||||
.select(["name", "role", "description", "_distance"])
|
||||
.select(["frame_id", "video_id", "caption", "_distance"])
|
||||
.limit(2)
|
||||
.to_polars()
|
||||
)
|
||||
print(result)
|
||||
# --8<-- [end:quickstart_vector_search_1]
|
||||
assert result["name"].to_list() == ["Merlin", "Morgana"]
|
||||
assert result["frame_id"].to_list() == ["2", "4"]
|
||||
|
||||
# --8<-- [start:quickstart_output_pandas]
|
||||
# Ensure you run `pip install pandas` beforehand
|
||||
result = table.search(query_vector).limit(2).to_pandas()
|
||||
print(result)
|
||||
# --8<-- [end:quickstart_output_pandas]
|
||||
assert result["name"].to_list() == ["Merlin", "Morgana"]
|
||||
assert result["frame_id"].to_list() == ["2", "4"]
|
||||
|
||||
# --8<-- [start:quickstart_curate_with_metadata]
|
||||
curated = (
|
||||
table.search(query_vector)
|
||||
.where("stats.magic >= 4")
|
||||
.select(["name", "role", "description", "_distance"])
|
||||
.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["name"].to_list() == ["Merlin", "Morgana"]
|
||||
assert curated["frame_id"].to_list() == ["2", "4"]
|
||||
|
||||
curated = table.search(query_vector).where("stats.magic < 4").limit(2).to_list()
|
||||
assert [row["name"] for row in curated] == ["King Arthur", "Sir Lancelot"]
|
||||
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):
|
||||
data = [
|
||||
{
|
||||
"id": "2",
|
||||
"name": "Merlin",
|
||||
"role": "Wizard",
|
||||
"description": "Advisor and prophet with deep magical knowledge.",
|
||||
"stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5},
|
||||
"vector": [0.2, 0.9, 0.4, 0.9],
|
||||
"frame_id": "2",
|
||||
"video_id": "clip-1",
|
||||
"caption": "a two-finger gripper closing on a cup",
|
||||
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
|
||||
"embedding": [0.2, 0.9, 0.4, 0.9],
|
||||
}
|
||||
]
|
||||
|
||||
# --8<-- [start:quickstart_create_table_async]
|
||||
async_table = await async_db.create_table(
|
||||
"characters",
|
||||
"frames",
|
||||
data=data,
|
||||
mode="overwrite",
|
||||
)
|
||||
# --8<-- [end:quickstart_create_table_async]
|
||||
|
||||
# --8<-- [start:quickstart_vector_search_1_async]
|
||||
# Search for examples similar to a "wise magical advisor"
|
||||
# Search for frames similar to "a gripper closing on an object"
|
||||
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(["name", "role", "description", "_distance"]).limit(2).to_polars()
|
||||
).select(["frame_id", "video_id", "caption", "_distance"]).limit(2).to_polars()
|
||||
print(async_result)
|
||||
# --8<-- [end:quickstart_vector_search_1_async]
|
||||
assert async_result["name"].to_list() == ["Merlin"]
|
||||
assert async_result["frame_id"].to_list() == ["2"]
|
||||
|
||||
|
||||
def test_quickstart_derived_feature(db):
|
||||
table = create_characters(db)
|
||||
table = create_frames(db)
|
||||
|
||||
# --8<-- [start:quickstart_add_feature]
|
||||
table.add_columns(
|
||||
{
|
||||
"power_score": "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)"
|
||||
"quality_score": "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)"
|
||||
}
|
||||
)
|
||||
# --8<-- [end:quickstart_add_feature]
|
||||
|
||||
# --8<-- [start:quickstart_query_feature]
|
||||
features = table.search().select(["name", "role", "power_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["name"], features["power_score"])) == [
|
||||
("King Arthur", 3.5),
|
||||
("Merlin", 4.0),
|
||||
("Morgana", 3.75),
|
||||
("Sir Lancelot", 3.0),
|
||||
assert sorted(zip(features["frame_id"], features["quality_score"])) == [
|
||||
("1", 3.5),
|
||||
("2", 4.0),
|
||||
("3", 3.0),
|
||||
("4", 3.75),
|
||||
]
|
||||
|
||||
|
||||
def description_lengths(table):
|
||||
rows = table.search().select(["description", "description_length"]).to_list()
|
||||
return {row["description"]: row["description_length"] for row in rows}
|
||||
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_characters(lancedb.connect(db_path_factory("computed")))
|
||||
table = create_frames(lancedb.connect(db_path_factory("computed")))
|
||||
|
||||
# --8<-- [start:quickstart_computed_feature]
|
||||
table.add_columns(computed={"description_length": "length(description)"})
|
||||
table.refresh_column("description_length")
|
||||
table.add_columns(computed={"caption_length": "length(caption)"})
|
||||
table.refresh_column("caption_length")
|
||||
# --8<-- [end:quickstart_computed_feature]
|
||||
lengths = description_lengths(table)
|
||||
lengths = caption_lengths(table)
|
||||
assert lengths == {text: len(text) for text in lengths}
|
||||
|
||||
|
||||
def test_quickstart_computed_column_on_a_deployment(deployment):
|
||||
table = create_characters(deployment)
|
||||
table = create_frames(deployment)
|
||||
|
||||
# --8<-- [start:quickstart_computed_feature_enterprise]
|
||||
table.add_columns(computed={"description_length": "length(description)"})
|
||||
job = table.refresh_column_async("description_length")
|
||||
table.add_columns(computed={"caption_length": "length(caption)"})
|
||||
job = table.refresh_column_async("caption_length")
|
||||
job.wait()
|
||||
# --8<-- [end:quickstart_computed_feature_enterprise]
|
||||
lengths = description_lengths(table)
|
||||
lengths = caption_lengths(table)
|
||||
assert len(lengths) == 4
|
||||
assert lengths == {text: len(text) for text in lengths}
|
||||
with pytest.raises(Exception):
|
||||
table.refresh_column("description_length")
|
||||
table.refresh_column("caption_length")
|
||||
|
||||
|
||||
def test_quickstart_multimodal(db, tmp_path, monkeypatch):
|
||||
app = tmp_path / "app"
|
||||
(app / "data").mkdir(parents=True)
|
||||
shutil.copy(IMAGE, app / "data/sir-lancelot.jpg")
|
||||
shutil.copy(IMAGE, app / "data/sample-frame.jpg")
|
||||
monkeypatch.chdir(app)
|
||||
|
||||
# --8<-- [start:quickstart_multimodal_bytes]
|
||||
from pathlib import Path
|
||||
|
||||
image_bytes = Path("data/sir-lancelot.jpg").read_bytes()
|
||||
image_bytes = Path("data/sample-frame.jpg").read_bytes()
|
||||
|
||||
multimodal_table = db.create_table(
|
||||
"character_images",
|
||||
"frame_images",
|
||||
data=[
|
||||
{
|
||||
"id": "lancelot",
|
||||
"description": "Portrait of Sir Lancelot",
|
||||
"frame_id": "thumb-1",
|
||||
"caption": "Sample frame thumbnail",
|
||||
"image": image_bytes,
|
||||
"vector": [0.9, 0.1, 0.5, 0.4],
|
||||
"embedding": [0.9, 0.1, 0.5, 0.4],
|
||||
}
|
||||
],
|
||||
mode="overwrite",
|
||||
@@ -331,7 +326,7 @@ def test_quickstart_multimodal(db, tmp_path, monkeypatch):
|
||||
|
||||
|
||||
def test_quickstart_training(db):
|
||||
table = create_characters(db)
|
||||
table = create_frames(db)
|
||||
|
||||
# --8<-- [start:quickstart_training]
|
||||
import torch
|
||||
@@ -339,15 +334,15 @@ def test_quickstart_training(db):
|
||||
|
||||
table.add_columns(
|
||||
{
|
||||
"magic": "cast(stats.magic as float)",
|
||||
"strength": "cast(stats.strength as float)",
|
||||
"motion": "cast(stats.motion as float)",
|
||||
"sharpness": "cast(stats.sharpness as float)",
|
||||
}
|
||||
)
|
||||
dataset = Permutation.identity(table).select_columns(["magic", "strength"])
|
||||
dataset = Permutation.identity(table).select_columns(["motion", "sharpness"])
|
||||
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)
|
||||
# --8<-- [end:quickstart_training]
|
||||
batches = list(dataloader)
|
||||
assert len(batches) == 1
|
||||
assert set(batches[0]) == {"magic", "strength"}
|
||||
assert set(batches[0]) == {"motion", "sharpness"}
|
||||
assert all(isinstance(value, torch.Tensor) for value in batches[0].values())
|
||||
assert sorted(batches[0]["magic"].tolist()) == [1.0, 1.0, 5.0, 5.0]
|
||||
assert sorted(batches[0]["motion"].tolist()) == [2.0, 3.0, 5.0, 5.0]
|
||||
|
||||
Generated
+2
-2
@@ -5561,9 +5561,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.15"
|
||||
version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use arrow_array::types::Float32Type;
|
||||
use arrow_array::{
|
||||
BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,
|
||||
Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,
|
||||
RecordBatchIterator, StringArray,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
@@ -83,8 +83,9 @@ async fn main() {
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let image_reader: Box<dyn arrow_array::RecordBatchReader + Send> =
|
||||
Box::new(RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()));
|
||||
let image_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(
|
||||
RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()),
|
||||
);
|
||||
let table = db
|
||||
.create_table("images", image_reader)
|
||||
.mode(CreateTableMode::Overwrite)
|
||||
@@ -137,42 +138,45 @@ async fn main() {
|
||||
let search_rows: usize = results.iter().map(|batch| batch.num_rows()).sum();
|
||||
assert_eq!(search_rows, 1);
|
||||
|
||||
// --8<-- [start:blob_api_schema]
|
||||
let blob_metadata = HashMap::from([(
|
||||
// --8<-- [start:legacy_blob_api_schema]
|
||||
let legacy_blob_metadata = HashMap::from([(
|
||||
"lance-encoding:blob".to_string(),
|
||||
"true".to_string(),
|
||||
)]);
|
||||
let blob_schema = Schema::new(vec![
|
||||
let legacy_blob_schema = Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
Field::new("video", DataType::LargeBinary, true).with_metadata(blob_metadata),
|
||||
Field::new("video", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata),
|
||||
]);
|
||||
// --8<-- [end:blob_api_schema]
|
||||
// --8<-- [end:legacy_blob_api_schema]
|
||||
|
||||
// --8<-- [start:blob_api_ingest]
|
||||
let blob_rows = vec![
|
||||
// --8<-- [start:legacy_blob_api_ingest]
|
||||
let legacy_blob_rows = vec![
|
||||
(1_i64, b"fake_video_bytes_1".to_vec()),
|
||||
(2_i64, b"fake_video_bytes_2".to_vec()),
|
||||
];
|
||||
|
||||
let blob_schema = Arc::new(blob_schema);
|
||||
let blob_batch = RecordBatch::try_new(
|
||||
blob_schema.clone(),
|
||||
let legacy_blob_schema = Arc::new(legacy_blob_schema);
|
||||
let legacy_blob_batch = RecordBatch::try_new(
|
||||
legacy_blob_schema.clone(),
|
||||
vec![
|
||||
Arc::new(Int64Array::from_iter_values(blob_rows.iter().map(|row| row.0))),
|
||||
Arc::new(Int64Array::from_iter_values(
|
||||
legacy_blob_rows.iter().map(|row| row.0),
|
||||
)),
|
||||
Arc::new(LargeBinaryArray::from_iter_values(
|
||||
blob_rows.iter().map(|row| row.1.as_slice()),
|
||||
legacy_blob_rows.iter().map(|row| row.1.as_slice()),
|
||||
)),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let blob_reader: Box<dyn arrow_array::RecordBatchReader + Send> =
|
||||
Box::new(RecordBatchIterator::new(vec![Ok(blob_batch)].into_iter(), blob_schema));
|
||||
let blob_table = db
|
||||
.create_table("videos", blob_reader)
|
||||
let legacy_blob_reader: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(
|
||||
RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema),
|
||||
);
|
||||
let legacy_blob_table = db
|
||||
.create_table("legacy_videos", legacy_blob_reader)
|
||||
.mode(CreateTableMode::Overwrite)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
// --8<-- [end:blob_api_ingest]
|
||||
assert_eq!(blob_table.count_rows(None).await.unwrap(), 2);
|
||||
// --8<-- [end:legacy_blob_api_ingest]
|
||||
assert_eq!(legacy_blob_table.count_rows(None).await.unwrap(), 2);
|
||||
}
|
||||
|
||||
+116
-124
@@ -16,92 +16,88 @@ use lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema};
|
||||
// Define structs representing the data schema
|
||||
#[derive(Debug, Clone)]
|
||||
struct Stats {
|
||||
strength: i8,
|
||||
magic: i8,
|
||||
leadership: i8,
|
||||
wisdom: i8,
|
||||
motion: i8,
|
||||
sharpness: i8,
|
||||
exposure: i8,
|
||||
framing: i8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Character {
|
||||
id: String,
|
||||
name: String,
|
||||
role: String,
|
||||
description: String,
|
||||
struct Frame {
|
||||
frame_id: String,
|
||||
video_id: String,
|
||||
caption: String,
|
||||
stats: Stats,
|
||||
vector: [f32; 4],
|
||||
embedding: [f32; 4],
|
||||
}
|
||||
|
||||
fn characters_schema() -> Arc<Schema> {
|
||||
fn frames_schema() -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::LargeUtf8, false),
|
||||
Field::new("name", DataType::LargeUtf8, false),
|
||||
Field::new("role", DataType::LargeUtf8, false),
|
||||
Field::new("description", DataType::LargeUtf8, false),
|
||||
Field::new("frame_id", DataType::LargeUtf8, false),
|
||||
Field::new("video_id", DataType::LargeUtf8, false),
|
||||
Field::new("caption", DataType::LargeUtf8, false),
|
||||
Field::new(
|
||||
"stats",
|
||||
DataType::Struct(Fields::from(vec![
|
||||
Arc::new(Field::new("strength", DataType::Int8, false)),
|
||||
Arc::new(Field::new("magic", DataType::Int8, false)),
|
||||
Arc::new(Field::new("leadership", DataType::Int8, false)),
|
||||
Arc::new(Field::new("wisdom", DataType::Int8, false)),
|
||||
Arc::new(Field::new("motion", DataType::Int8, false)),
|
||||
Arc::new(Field::new("sharpness", DataType::Int8, false)),
|
||||
Arc::new(Field::new("exposure", DataType::Int8, false)),
|
||||
Arc::new(Field::new("framing", DataType::Int8, false)),
|
||||
])),
|
||||
false,
|
||||
),
|
||||
Field::new(
|
||||
"vector",
|
||||
"embedding",
|
||||
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4),
|
||||
false,
|
||||
),
|
||||
]))
|
||||
}
|
||||
|
||||
fn characters_to_reader(
|
||||
fn frames_to_reader(
|
||||
schema: Arc<Schema>,
|
||||
rows: &[Character],
|
||||
rows: &[Frame],
|
||||
) -> Box<dyn RecordBatchReader + Send> {
|
||||
let ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.id.as_str()));
|
||||
let names = LargeStringArray::from_iter_values(rows.iter().map(|row| row.name.as_str()));
|
||||
let roles = LargeStringArray::from_iter_values(rows.iter().map(|row| row.role.as_str()));
|
||||
let descriptions =
|
||||
LargeStringArray::from_iter_values(rows.iter().map(|row| row.description.as_str()));
|
||||
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 strength = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.strength));
|
||||
let magic = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.magic));
|
||||
let leadership = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.leadership));
|
||||
let wisdom = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.wisdom));
|
||||
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));
|
||||
let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure));
|
||||
let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing));
|
||||
let stats_fields: Vec<FieldRef> = vec![
|
||||
Arc::new(Field::new("strength", DataType::Int8, false)),
|
||||
Arc::new(Field::new("magic", DataType::Int8, false)),
|
||||
Arc::new(Field::new("leadership", DataType::Int8, false)),
|
||||
Arc::new(Field::new("wisdom", DataType::Int8, false)),
|
||||
Arc::new(Field::new("motion", DataType::Int8, false)),
|
||||
Arc::new(Field::new("sharpness", DataType::Int8, false)),
|
||||
Arc::new(Field::new("exposure", DataType::Int8, false)),
|
||||
Arc::new(Field::new("framing", DataType::Int8, false)),
|
||||
];
|
||||
let stats = StructArray::new(
|
||||
stats_fields.into(),
|
||||
vec![
|
||||
Arc::new(strength),
|
||||
Arc::new(magic),
|
||||
Arc::new(leadership),
|
||||
Arc::new(wisdom),
|
||||
Arc::new(motion),
|
||||
Arc::new(sharpness),
|
||||
Arc::new(exposure),
|
||||
Arc::new(framing),
|
||||
],
|
||||
None,
|
||||
);
|
||||
|
||||
let vectors = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
let embeddings = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
rows.iter()
|
||||
.map(|row| Some(row.vector.iter().copied().map(Some).collect::<Vec<_>>())),
|
||||
.map(|row| Some(row.embedding.iter().copied().map(Some).collect::<Vec<_>>())),
|
||||
4,
|
||||
);
|
||||
|
||||
let batch = RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![
|
||||
Arc::new(ids),
|
||||
Arc::new(names),
|
||||
Arc::new(roles),
|
||||
Arc::new(descriptions),
|
||||
Arc::new(frame_ids),
|
||||
Arc::new(video_ids),
|
||||
Arc::new(captions),
|
||||
Arc::new(stats),
|
||||
Arc::new(vectors),
|
||||
Arc::new(embeddings),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -121,44 +117,41 @@ async fn main() {
|
||||
|
||||
// --8<-- [start:quickstart_data]
|
||||
let data = vec![
|
||||
Character {
|
||||
id: "1".to_string(),
|
||||
name: "King Arthur".to_string(),
|
||||
role: "King".to_string(),
|
||||
description: "Leader of Camelot and wielder of Excalibur.".to_string(),
|
||||
Frame {
|
||||
frame_id: "1".to_string(),
|
||||
video_id: "clip-1".to_string(),
|
||||
caption: "a robot arm reaching toward a cup".to_string(),
|
||||
stats: Stats {
|
||||
strength: 4,
|
||||
magic: 1,
|
||||
leadership: 5,
|
||||
wisdom: 4,
|
||||
motion: 3,
|
||||
sharpness: 4,
|
||||
exposure: 4,
|
||||
framing: 3,
|
||||
},
|
||||
vector: [0.7, 0.1, 0.9, 0.7],
|
||||
embedding: [0.7, 0.1, 0.9, 0.7],
|
||||
},
|
||||
Character {
|
||||
id: "2".to_string(),
|
||||
name: "Merlin".to_string(),
|
||||
role: "Wizard".to_string(),
|
||||
description: "Advisor and prophet with deep magical knowledge.".to_string(),
|
||||
Frame {
|
||||
frame_id: "2".to_string(),
|
||||
video_id: "clip-1".to_string(),
|
||||
caption: "a two-finger gripper closing on a cup".to_string(),
|
||||
stats: Stats {
|
||||
strength: 2,
|
||||
magic: 5,
|
||||
leadership: 4,
|
||||
wisdom: 5,
|
||||
motion: 5,
|
||||
sharpness: 4,
|
||||
exposure: 5,
|
||||
framing: 2,
|
||||
},
|
||||
vector: [0.2, 0.9, 0.4, 0.9],
|
||||
embedding: [0.2, 0.9, 0.4, 0.9],
|
||||
},
|
||||
Character {
|
||||
id: "3".to_string(),
|
||||
name: "Sir Lancelot".to_string(),
|
||||
role: "Knight".to_string(),
|
||||
description: "Legendary knight known for courage and combat skill.".to_string(),
|
||||
Frame {
|
||||
frame_id: "3".to_string(),
|
||||
video_id: "clip-2".to_string(),
|
||||
caption: "a robot arm holding a cup steady".to_string(),
|
||||
stats: Stats {
|
||||
strength: 5,
|
||||
magic: 1,
|
||||
leadership: 3,
|
||||
wisdom: 3,
|
||||
motion: 2,
|
||||
sharpness: 3,
|
||||
exposure: 3,
|
||||
framing: 4,
|
||||
},
|
||||
vector: [0.9, 0.1, 0.5, 0.4],
|
||||
embedding: [0.9, 0.1, 0.5, 0.4],
|
||||
},
|
||||
];
|
||||
// --8<-- [end:quickstart_data]
|
||||
@@ -166,9 +159,9 @@ async fn main() {
|
||||
// --8<-- [start:quickstart_create_table]
|
||||
use lancedb::database::CreateTableMode;
|
||||
|
||||
let schema = characters_schema();
|
||||
let schema = frames_schema();
|
||||
let table = db
|
||||
.create_table("characters", characters_to_reader(schema.clone(), &data))
|
||||
.create_table("frames", frames_to_reader(schema.clone(), &data))
|
||||
.mode(CreateTableMode::Overwrite)
|
||||
.execute()
|
||||
.await
|
||||
@@ -177,21 +170,20 @@ async fn main() {
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 3);
|
||||
|
||||
// --8<-- [start:quickstart_add_data]
|
||||
let more_data = vec![Character {
|
||||
id: "4".to_string(),
|
||||
name: "Morgana".to_string(),
|
||||
role: "Sorceress".to_string(),
|
||||
description: "Powerful sorceress of Avalon.".to_string(),
|
||||
let more_data = vec![Frame {
|
||||
frame_id: "4".to_string(),
|
||||
video_id: "clip-2".to_string(),
|
||||
caption: "a gripper lowering a cup onto the table".to_string(),
|
||||
stats: Stats {
|
||||
strength: 2,
|
||||
magic: 5,
|
||||
leadership: 4,
|
||||
wisdom: 4,
|
||||
motion: 5,
|
||||
sharpness: 4,
|
||||
exposure: 4,
|
||||
framing: 2,
|
||||
},
|
||||
vector: [0.3, 0.9, 0.6, 0.8],
|
||||
embedding: [0.3, 0.9, 0.6, 0.8],
|
||||
}];
|
||||
table
|
||||
.add(characters_to_reader(schema.clone(), &more_data))
|
||||
.add(frames_to_reader(schema.clone(), &more_data))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -202,7 +194,7 @@ async fn main() {
|
||||
use lancedb::arrow::IntoPolars;
|
||||
use lancedb::query::{ExecutableQuery, QueryBase, Select};
|
||||
|
||||
// Search for examples similar to a "wise magical advisor"
|
||||
// Search for frames similar to "a gripper closing on an object"
|
||||
let query_vector = [0.2, 0.8, 0.4, 0.9];
|
||||
|
||||
let result = table
|
||||
@@ -210,9 +202,9 @@ async fn main() {
|
||||
.nearest_to(&query_vector)
|
||||
.unwrap()
|
||||
.select(Select::Columns(vec![
|
||||
"name".to_string(),
|
||||
"role".to_string(),
|
||||
"description".to_string(),
|
||||
"frame_id".to_string(),
|
||||
"video_id".to_string(),
|
||||
"caption".to_string(),
|
||||
"_distance".to_string(),
|
||||
]))
|
||||
.limit(2)
|
||||
@@ -224,20 +216,20 @@ async fn main() {
|
||||
.unwrap();
|
||||
println!("{result:?}");
|
||||
// --8<-- [end:quickstart_vector_search_1]
|
||||
let name_col = result.column("name").unwrap().str().unwrap();
|
||||
assert_eq!(name_col.get(0).unwrap(), "Merlin");
|
||||
assert_eq!(name_col.get(1).unwrap(), "Morgana");
|
||||
let frame_id_col = result.column("frame_id").unwrap().str().unwrap();
|
||||
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.magic >= 4")
|
||||
.only_if("stats.motion >= 4")
|
||||
.select(Select::Columns(vec![
|
||||
"name".to_string(),
|
||||
"role".to_string(),
|
||||
"description".to_string(),
|
||||
"frame_id".to_string(),
|
||||
"video_id".to_string(),
|
||||
"caption".to_string(),
|
||||
"_distance".to_string(),
|
||||
]))
|
||||
.limit(2)
|
||||
@@ -249,9 +241,9 @@ async fn main() {
|
||||
.unwrap();
|
||||
println!("{curated:?}");
|
||||
// --8<-- [end:quickstart_curate_with_metadata]
|
||||
let curated_name_col = curated.column("name").unwrap().str().unwrap();
|
||||
assert_eq!(curated_name_col.get(0).unwrap(), "Merlin");
|
||||
assert_eq!(curated_name_col.get(1).unwrap(), "Morgana");
|
||||
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
|
||||
@@ -259,9 +251,9 @@ async fn main() {
|
||||
.nearest_to(&query_vector)
|
||||
.unwrap()
|
||||
.select(Select::Columns(vec![
|
||||
"name".to_string(),
|
||||
"role".to_string(),
|
||||
"description".to_string(),
|
||||
"frame_id".to_string(),
|
||||
"video_id".to_string(),
|
||||
"caption".to_string(),
|
||||
"_distance".to_string(),
|
||||
]))
|
||||
.limit(2)
|
||||
@@ -273,15 +265,15 @@ async fn main() {
|
||||
.unwrap();
|
||||
println!("{result:?}");
|
||||
// --8<-- [end:quickstart_output_array]
|
||||
let name_col = result.column("name").unwrap().str().unwrap();
|
||||
assert_eq!(name_col.get(0).unwrap(), "Merlin");
|
||||
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![(
|
||||
"power_score".to_string(),
|
||||
"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)"
|
||||
"quality_score".to_string(),
|
||||
"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)"
|
||||
.to_string(),
|
||||
)]),
|
||||
None,
|
||||
@@ -294,9 +286,9 @@ async fn main() {
|
||||
let features = table
|
||||
.query()
|
||||
.select(Select::Columns(vec![
|
||||
"name".to_string(),
|
||||
"role".to_string(),
|
||||
"power_score".to_string(),
|
||||
"frame_id".to_string(),
|
||||
"video_id".to_string(),
|
||||
"quality_score".to_string(),
|
||||
]))
|
||||
.execute()
|
||||
.await
|
||||
@@ -306,7 +298,7 @@ async fn main() {
|
||||
.unwrap();
|
||||
println!("{features:?}");
|
||||
// --8<-- [end:quickstart_query_feature]
|
||||
assert_eq!(features.column("power_score").unwrap().len(), 4);
|
||||
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();
|
||||
@@ -314,7 +306,7 @@ async fn main() {
|
||||
std::fs::copy(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../web/static/assets/images/quickstart/sir-lancelot.jpg"),
|
||||
app.path().join("data/sir-lancelot.jpg"),
|
||||
app.path().join("data/sample-frame.jpg"),
|
||||
)
|
||||
.unwrap();
|
||||
std::env::set_current_dir(app.path()).unwrap();
|
||||
@@ -322,30 +314,30 @@ async fn main() {
|
||||
// --8<-- [start:quickstart_multimodal_bytes]
|
||||
use lancedb::arrow::arrow_array::BinaryArray;
|
||||
|
||||
let image_bytes = std::fs::read("data/sir-lancelot.jpg").unwrap();
|
||||
let image_bytes = std::fs::read("data/sample-frame.jpg").unwrap();
|
||||
|
||||
let image_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::LargeUtf8, false),
|
||||
Field::new("description", DataType::LargeUtf8, false),
|
||||
Field::new("frame_id", DataType::LargeUtf8, false),
|
||||
Field::new("caption", DataType::LargeUtf8, false),
|
||||
Field::new("image", DataType::Binary, false),
|
||||
Field::new(
|
||||
"vector",
|
||||
"embedding",
|
||||
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4),
|
||||
false,
|
||||
),
|
||||
]));
|
||||
let image_vectors = [[0.9_f32, 0.1, 0.5, 0.4]];
|
||||
let image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]];
|
||||
let image_batch = RecordBatch::try_new(
|
||||
image_schema.clone(),
|
||||
vec![
|
||||
Arc::new(LargeStringArray::from_iter_values(["lancelot"])),
|
||||
Arc::new(LargeStringArray::from_iter_values(["thumb-1"])),
|
||||
Arc::new(LargeStringArray::from_iter_values([
|
||||
"Portrait of Sir Lancelot",
|
||||
"Sample frame thumbnail",
|
||||
])),
|
||||
Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])),
|
||||
Arc::new(
|
||||
FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
image_vectors
|
||||
image_embeddings
|
||||
.iter()
|
||||
.map(|vector| Some(vector.iter().copied().map(Some).collect::<Vec<_>>())),
|
||||
4,
|
||||
@@ -359,7 +351,7 @@ async fn main() {
|
||||
image_schema,
|
||||
));
|
||||
let multimodal_table = db
|
||||
.create_table("character_images", image_reader)
|
||||
.create_table("frame_images", image_reader)
|
||||
.mode(CreateTableMode::Overwrite)
|
||||
.execute()
|
||||
.await
|
||||
|
||||
@@ -4,6 +4,12 @@ import { afterEach, describe, expect, jest, test } from "@jest/globals";
|
||||
import * as lancedb from "@lancedb/lancedb";
|
||||
import { withTempDirectory } from "./util.ts";
|
||||
|
||||
async function collectNames(items: AsyncIterable<string>): Promise<string[]> {
|
||||
const names: string[] = [];
|
||||
for await (const name of items) names.push(name);
|
||||
return names;
|
||||
}
|
||||
|
||||
test("connect to a local database", async () => {
|
||||
await withTempDirectory(async (tempDir) => {
|
||||
const cwd = process.cwd();
|
||||
@@ -13,12 +19,12 @@ test("connect to a local database", async () => {
|
||||
const db = await lancedb.connect("ex_lancedb");
|
||||
// --8<-- [end:connect]
|
||||
await db.createTable("probe", [{ id: 1 }]);
|
||||
expect((await db.listTables()).tables).toEqual(["probe"]);
|
||||
expect(await collectNames(db.listTables())).toEqual(["probe"]);
|
||||
} finally {
|
||||
process.chdir(cwd);
|
||||
}
|
||||
const reopened = await lancedb.connect(`${tempDir}/ex_lancedb`);
|
||||
expect((await reopened.listTables()).tables).toEqual(["probe"]);
|
||||
expect(await collectNames(reopened.listTables())).toEqual(["probe"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -109,8 +115,8 @@ async function namespaceTableOpsExample() {
|
||||
);
|
||||
|
||||
// Verify
|
||||
console.log((await db.listNamespaces()).namespaces); // ["prod"]
|
||||
console.log((await db.listNamespaces(["prod"])).namespaces); // ["recommendations", "search"]
|
||||
console.log(await collectNames(db.listNamespaces())); // ["prod"]
|
||||
console.log(await collectNames(db.listNamespaces(["prod"]))); // ["recommendations", "search"]
|
||||
console.log(await db.tableNames(["prod", "search"])); // ["user"]
|
||||
console.log(await db.tableNames(["prod", "recommendations"])); // ["user"]
|
||||
// --8<-- [end:namespace_table_ops]
|
||||
@@ -124,7 +130,7 @@ async function namespaceAdminOpsExample() {
|
||||
await db.createNamespace(["prod"]);
|
||||
await db.createNamespace(["prod", "search"]);
|
||||
|
||||
const childNamespaces = (await db.listNamespaces(["prod"])).namespaces;
|
||||
const childNamespaces = await collectNames(db.listNamespaces(["prod"]));
|
||||
console.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces);
|
||||
// Child namespaces under ["prod","search"]: [ 'search' ]
|
||||
|
||||
|
||||
@@ -75,8 +75,8 @@ test("multimodal snippets (async)", async () => {
|
||||
// --8<-- [end:process_results]
|
||||
expect(results).toHaveLength(1);
|
||||
|
||||
// --8<-- [start:blob_api_schema]
|
||||
const blobSchema = new arrow.Schema([
|
||||
// --8<-- [start:legacy_blob_api_schema]
|
||||
const legacyBlobSchema = new arrow.Schema([
|
||||
new arrow.Field("id", new arrow.Int64()),
|
||||
new arrow.Field(
|
||||
"video",
|
||||
@@ -85,20 +85,24 @@ test("multimodal snippets (async)", async () => {
|
||||
new Map([["lance-encoding:blob", "true"]]),
|
||||
),
|
||||
]);
|
||||
// --8<-- [end:blob_api_schema]
|
||||
// --8<-- [end:legacy_blob_api_schema]
|
||||
|
||||
// --8<-- [start:blob_api_ingest]
|
||||
const blobData = lancedb.makeArrowTable(
|
||||
// --8<-- [start:legacy_blob_api_ingest]
|
||||
const legacyBlobData = lancedb.makeArrowTable(
|
||||
[
|
||||
{ id: 1, video: Buffer.from("fake_video_bytes_1") },
|
||||
{ id: 2, video: Buffer.from("fake_video_bytes_2") },
|
||||
],
|
||||
{ schema: blobSchema },
|
||||
{ schema: legacyBlobSchema },
|
||||
);
|
||||
const blobTable = await db.createTable("videos", blobData, {
|
||||
mode: "overwrite",
|
||||
});
|
||||
// --8<-- [end:blob_api_ingest]
|
||||
expect(await blobTable.countRows()).toBe(2);
|
||||
const legacyBlobTable = await db.createTable(
|
||||
"legacy_videos",
|
||||
legacyBlobData,
|
||||
{
|
||||
mode: "overwrite",
|
||||
},
|
||||
);
|
||||
// --8<-- [end:legacy_blob_api_ingest]
|
||||
expect(await legacyBlobTable.countRows()).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user