mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
### Summary & Reasoning Embedded Python `to_pandas()` previously incurred three avoidable bottlenecks on tables without blob columns: 1. **Unconditional `output_schema()` re-planning**: Both sync and async `to_pandas()` invoked `output_schema()` before execution, running the full Rust/DataFusion physical query planner (`create_plan()` — dataset lookup, row count, SQL/subquery prep, index loading, plan construction) only to discard the plan and build it a second time. For sync queries, `_output_schema()` also hopped across `LOOP.run(...)`, bypassing the direct `execute_to_reader_sync` fast path. 2. **Async eager-collector bypass**: `AsyncQueryBase.to_pandas()` rewrote the default `blob_mode="lazy"` to `"descriptions"`, causing `to_arrow()` to skip `#5127`'s native eager collector (`execute_to_reader`) and fall back to per-batch `to_batches()` streaming (1,024-row slicing and one Python future per batch). Sync `LanceTakeQueryBuilder.to_pandas()` hit the same path via `BaseQueryBuilder`. 3. **Redundant `table.schema` fetches and `to_query_request()` vector FFI clones**: Blob row-id and source checks cloned query requests across FFI and fetched `table.schema` multiple times per execution (2x on non-hybrid, 4x-5x on hybrid / WAL-PK tables) even when the table schema contained no blob columns or `with_row_id()` was already set. ### Chosen Direction & Trade-Offs - **Schema-gated fast path**: `schema_has_blob_field(table_schema)` matches strictly schema-declared blob columns (including nested structs and lists), so a query over a non-blob table cannot produce blob output fields. Fetching `table_schema` once and gating `output_schema()` and `blob_mode` rewrites on it avoids double planning, keeps non-blob `to_pandas()` and `to_arrow(blob_mode="descriptions"|"bytes")` on the eager collector, and brings execution down to a single schema fetch (including across hybrid child legs and WAL-PK retries). - **Conservative on blob tables & unbound queries**: Tables containing blob columns still run `output_schema()` so projected/quoted/nested blob edge cases keep identical behavior (while reusing the pre-fetched schema to avoid extra schema fetches). Unbound `AsyncQueryBase` (`table=None`) keeps the conservative fallback. - **Preserving overrides & monkeypatches**: Internal schema-threaded helpers are only entered when built-in `to_arrow`/`to_batches` methods have not been overridden or monkeypatched (including hybrid child legs), so custom subclasses without `blob_mode` and test spies behave identically. - **Enterprise tables**: Early Enterprise execution paths are unchanged (preserving zero extra schema requests in `"lazy"` mode and existing `_blob_paths` / snapshot behavior). - **Out of scope**: Skipping `output_schema()` when a query on a blob table projects only non-blob columns, and Rust-side `create_plan()` optimizations. ### Benchmarks Measured on **AMD Ryzen 9 7950X3D**, runner and child processes pinned to **CCD0 (`ProcessorAffinity = 0xFFFF`, logical CPUs 0-15, verified via `GetProcessAffinityMask`)**, interleaved **`A -> B -> B -> A`** cells on shared datasets and the exact same compiled `_lancedb.pyd` extension (`A` = `c3f005f7`, `B` = patched): | Workload | Baseline `A` (med / p95) | Candidate `B` (med / p95) | Speedup | Per-cell medians (`A1, B1, B2, A2`) | | :--- | ---: | ---: | ---: | :--- | | Sync indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.541 ms` / `6.834 ms` | `5.196 ms` / `5.439 ms` | **1.26x (-20.6%)** | `6.627, 5.148, 5.249, 6.464 ms` | | Async indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.835 ms` / `8.063 ms` | `5.358 ms` / `5.632 ms` | **1.28x (-21.6%)** | `6.924, 5.323, 5.410, 6.790 ms` | | Sync scan `500k x 3` (`n=10`/cell) | `11.027 ms` / `11.901 ms` | `9.543 ms` / `10.253 ms` | **1.16x (-13.5%)** | `10.769, 9.452, 9.591, 11.134 ms` | | Async scan `500k x 3` (`n=10`/cell) | `152.783 ms` / `154.980 ms` | `9.447 ms` / `9.817 ms` | **16.17x (-93.8%)** | `151.034, 9.602, 9.431, 154.107 ms` | ### Verification - **Executed on Windows host**: - Targeted pytest suite (11 files covering sync direct, eager collector, query, blob, blob-without-pylance, hybrid, WAL hybrid, FTS wand factor, Enterprise `test_remote_db.py`, namespace, and table tests): **2,150 passed, 0 failed, 21 skipped** (0 missing-`pandas`/`pylance` skips; skips limited to Linux `sched_setaffinity`/`fork`, optional `av`/`torch`, and `experimental_functions`). - No-`pandas` / no-`pylance` parity check (blocking `pandas` and `lance` imports on `test_sync_query_direct.py`, `test_eager_collector.py`, `test_wal_hybrid.py`): **21 passed, 0 failed, 6 skipped**. - Doctests on `python/lancedb/query.py`: **23 passed, 0 failed**. - `ruff==0.9.9 format --check .` and `ruff==0.9.9 check .`: passed. - `pyright --pythonplatform Linux`: 0 errors; diff-scoped `pyright` on `python/lancedb/query.py`: 0 errors across all changed lines. - `typos` on all modified files: passed. - **Pending CI**: Full cross-platform Python matrix (Linux/macOS/Windows), Linux-only `sched_setaffinity`/`fork` tests, and CI commitlint/license-header workflows. --------- Co-authored-by: Xuanwo <github@xuanwo.io>
4549 lines
148 KiB
Python
4549 lines
148 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
from typing import List, Union
|
|
import unittest.mock as mock
|
|
from datetime import timedelta
|
|
from pathlib import Path
|
|
import random
|
|
|
|
import lancedb
|
|
from lancedb.arrow import AsyncRecordBatchReader
|
|
from lancedb.db import AsyncConnection
|
|
from lancedb.embeddings.base import TextEmbeddingFunction
|
|
from lancedb.embeddings.registry import get_registry, register
|
|
from lancedb.expr import col
|
|
from lancedb.index import FTS, IvfPq
|
|
from lancedb.rerankers import RRFReranker, Reranker
|
|
import lancedb.pydantic
|
|
import numpy as np
|
|
import pandas.testing as tm
|
|
import pyarrow as pa
|
|
import pyarrow.compute as pc
|
|
import pytest
|
|
import pytest_asyncio
|
|
from lancedb.pydantic import LanceModel, Vector
|
|
from lancedb.query import (
|
|
AsyncFTSQuery,
|
|
AsyncHybridQuery,
|
|
AsyncQuery,
|
|
AsyncQueryBase,
|
|
AsyncVectorQuery,
|
|
ColumnOrdering,
|
|
LanceEmptyQueryBuilder,
|
|
LanceFtsQueryBuilder,
|
|
LanceVectorQueryBuilder,
|
|
MatchQuery,
|
|
PhraseQuery,
|
|
Query,
|
|
FullTextSearchQuery,
|
|
ensure_vector_query,
|
|
)
|
|
from lancedb.rerankers.cross_encoder import CrossEncoderReranker
|
|
from lancedb.table import AsyncTable, LanceTable
|
|
from utils import exception_output
|
|
from importlib.util import find_spec
|
|
|
|
|
|
# Legacy v1 blob columns are only writable at file version <= 2.1.
|
|
LEGACY_BLOB_STORAGE_OPTIONS = {"new_table_data_storage_version": "2.1"}
|
|
|
|
|
|
def _blob_query_data():
|
|
return pa.table(
|
|
{
|
|
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
|
"tag": pa.array(["drop", "keep", "keep", "keep"], pa.utf8()),
|
|
"vector": pa.array(
|
|
[[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
|
|
type=pa.list_(pa.float32(), list_size=2),
|
|
),
|
|
"blob": pa.array([b"one", b"two", b"three", b"four"], pa.large_binary()),
|
|
},
|
|
schema=pa.schema(
|
|
[
|
|
pa.field("id", pa.int64()),
|
|
pa.field("tag", pa.utf8()),
|
|
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
|
pa.field(
|
|
"blob", pa.large_binary(), metadata={"lance-encoding:blob": "true"}
|
|
),
|
|
]
|
|
),
|
|
)
|
|
|
|
|
|
def _fragment_query_data():
|
|
return pa.table(
|
|
{
|
|
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
|
"text": pa.array(["one", "two", "three", "four"], pa.utf8()),
|
|
"vector": pa.array(
|
|
[[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
|
|
type=pa.list_(pa.float32(), list_size=2),
|
|
),
|
|
}
|
|
)
|
|
|
|
|
|
def _fragment_query_table(db, name):
|
|
data = _fragment_query_data()
|
|
table = db.create_table(name, data.slice(0, 2))
|
|
table.add(data.slice(2, 2))
|
|
return table
|
|
|
|
|
|
def _apply_fragment_restriction(query, restriction, fragment):
|
|
if restriction == "ids":
|
|
return query.fragment_ids([fragment.fragment_id])
|
|
if restriction == "empty":
|
|
return query.fragment_ids([])
|
|
if restriction == "fragments":
|
|
return query.with_fragments([fragment])
|
|
raise AssertionError(f"unknown restriction: {restriction}")
|
|
|
|
|
|
def _create_blob_v2_query_table(db, name):
|
|
schema = pa.schema(
|
|
[
|
|
pa.field("id", pa.int64()),
|
|
pa.field("tag", pa.utf8()),
|
|
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
|
lancedb.blob("blob"),
|
|
]
|
|
)
|
|
table = db.create_table(name, schema=schema)
|
|
table.add(
|
|
[
|
|
{"id": 1, "tag": "drop", "vector": [1.0, 0.0], "blob": b"one"},
|
|
{"id": 2, "tag": "keep", "vector": [2.0, 0.0], "blob": b"two"},
|
|
{"id": 3, "tag": "keep", "vector": [3.0, 0.0], "blob": b"three"},
|
|
{"id": 4, "tag": "keep", "vector": [4.0, 0.0], "blob": b"four"},
|
|
]
|
|
)
|
|
return table
|
|
|
|
|
|
async def _create_blob_v2_query_table_async(db, name):
|
|
schema = pa.schema(
|
|
[
|
|
pa.field("id", pa.int64()),
|
|
pa.field("tag", pa.utf8()),
|
|
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
|
lancedb.blob("blob"),
|
|
]
|
|
)
|
|
table = await db.create_table(name, schema=schema)
|
|
await table.add(
|
|
[
|
|
{"id": 1, "tag": "drop", "vector": [1.0, 0.0], "blob": b"one"},
|
|
{"id": 2, "tag": "keep", "vector": [2.0, 0.0], "blob": b"two"},
|
|
{"id": 3, "tag": "keep", "vector": [3.0, 0.0], "blob": b"three"},
|
|
{"id": 4, "tag": "keep", "vector": [4.0, 0.0], "blob": b"four"},
|
|
]
|
|
)
|
|
return table
|
|
|
|
|
|
def _nested_blob_v2_query_schema():
|
|
return pa.schema(
|
|
[
|
|
pa.field("id", pa.int64()),
|
|
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
|
pa.field(
|
|
"info",
|
|
pa.struct([pa.field("label", pa.string()), lancedb.blob("blob")]),
|
|
),
|
|
]
|
|
)
|
|
|
|
|
|
def _nested_blob_v2_query_rows():
|
|
return [
|
|
{"id": 1, "vector": [1.0, 0.0], "info": {"label": "one", "blob": b"one"}},
|
|
{"id": 2, "vector": [2.0, 0.0], "info": {"label": "two", "blob": b"two"}},
|
|
]
|
|
|
|
|
|
def _assert_lazy_blob(value, expected: bytes):
|
|
assert hasattr(value, "readall")
|
|
assert value.readall() == expected
|
|
|
|
|
|
def _assert_blob_bytes_projection(df):
|
|
assert df["id_alias"].tolist() == [3, 4]
|
|
assert df["payload"].tolist() == [b"three", b"four"]
|
|
assert df["double_id"].tolist() == [6, 8]
|
|
|
|
|
|
def _blob_query_table(db, name, blob_schema):
|
|
if blob_schema == "v1":
|
|
return db.create_table(
|
|
name, _blob_query_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS
|
|
)
|
|
return _create_blob_v2_query_table(db, name)
|
|
|
|
|
|
async def _blob_query_table_async(db, name, blob_schema):
|
|
if blob_schema == "v1":
|
|
return await db.create_table(
|
|
name, _blob_query_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS
|
|
)
|
|
return await _create_blob_v2_query_table_async(db, name)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def table(tmpdir_factory) -> lancedb.table.Table:
|
|
tmp_path = str(tmpdir_factory.mktemp("data"))
|
|
db = lancedb.connect(tmp_path)
|
|
df = pa.table(
|
|
{
|
|
"vector": pa.array(
|
|
[[1, 2], [3, 4]], type=pa.list_(pa.float32(), list_size=2)
|
|
),
|
|
"id": pa.array([1, 2]),
|
|
"str_field": pa.array(["a", "b"]),
|
|
"float_field": pa.array([1.0, 2.0]),
|
|
}
|
|
)
|
|
return db.create_table("test", df)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def table_async(tmp_path) -> AsyncTable:
|
|
conn = await lancedb.connect_async(
|
|
tmp_path, read_consistency_interval=timedelta(seconds=0)
|
|
)
|
|
data = pa.table(
|
|
{
|
|
"vector": pa.array(
|
|
[[1, 2], [3, 4]], type=pa.list_(pa.float32(), list_size=2)
|
|
),
|
|
"id": pa.array([1, 2]),
|
|
"str_field": pa.array(["a", "b"]),
|
|
"float_field": pa.array([1.0, 2.0]),
|
|
"text": pa.array(["a", "dog"]),
|
|
}
|
|
)
|
|
return await conn.create_table("test", data)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def table_struct_async(tmp_path) -> AsyncTable:
|
|
conn = await lancedb.connect_async(
|
|
tmp_path, read_consistency_interval=timedelta(seconds=0)
|
|
)
|
|
struct = pa.array([{"n_legs": 2, "animals": "Parrot"}, {"year": 2022, "n_legs": 4}])
|
|
month = pa.array([4, 6])
|
|
table = pa.Table.from_arrays([struct, month], names=["a", "month"])
|
|
return await conn.create_table("test_struct", table)
|
|
|
|
|
|
@pytest.fixture
|
|
def multivec_table(vector_value_type=pa.float32()) -> lancedb.table.Table:
|
|
db = lancedb.connect("memory://")
|
|
# Generate 256 rows of data
|
|
num_rows = 256
|
|
|
|
# Generate data for each column
|
|
vector_data = [
|
|
[[i, i + 1], [i + 2, i + 3]] for i in range(num_rows)
|
|
] # Adjust to match nested structure
|
|
id_data = list(range(1, num_rows + 1))
|
|
float_field_data = [float(i) for i in range(1, num_rows + 1)]
|
|
|
|
# Create the Arrow table
|
|
df = pa.table(
|
|
{
|
|
"vector": pa.array(
|
|
vector_data, type=pa.list_(pa.list_(vector_value_type, list_size=2))
|
|
),
|
|
"id": pa.array(id_data),
|
|
"float_field": pa.array(float_field_data),
|
|
}
|
|
)
|
|
return db.create_table("test", df)
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def multivec_table_async(vector_value_type=pa.float32()) -> AsyncTable:
|
|
conn = await lancedb.connect_async(
|
|
"memory://", read_consistency_interval=timedelta(seconds=0)
|
|
)
|
|
# Generate 256 rows of data
|
|
num_rows = 256
|
|
|
|
# Generate data for each column
|
|
vector_data = [
|
|
[[i, i + 1], [i + 2, i + 3]] for i in range(num_rows)
|
|
] # Adjust to match nested structure
|
|
id_data = list(range(1, num_rows + 1))
|
|
float_field_data = [float(i) for i in range(1, num_rows + 1)]
|
|
|
|
# Create the Arrow table
|
|
df = pa.table(
|
|
{
|
|
"vector": pa.array(
|
|
vector_data, type=pa.list_(pa.list_(vector_value_type, list_size=2))
|
|
),
|
|
"id": pa.array(id_data),
|
|
"float_field": pa.array(float_field_data),
|
|
}
|
|
)
|
|
return await conn.create_table("test_async", df)
|
|
|
|
|
|
def test_cast(table):
|
|
class TestModel(LanceModel):
|
|
vector: Vector(2)
|
|
id: int
|
|
str_field: str
|
|
float_field: float
|
|
|
|
q = LanceVectorQueryBuilder(table, [0, 0], "vector").limit(1)
|
|
results = q.to_pydantic(TestModel)
|
|
assert len(results) == 1
|
|
r0 = results[0]
|
|
assert isinstance(r0, TestModel)
|
|
assert r0.id == 1
|
|
assert r0.vector == [1, 2]
|
|
assert r0.str_field == "a"
|
|
assert r0.float_field == 1.0
|
|
|
|
|
|
def test_offset(table):
|
|
results_without_offset = LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
assert len(results_without_offset.to_pandas()) == 2
|
|
results_with_offset = LanceVectorQueryBuilder(table, [0, 0], "vector").offset(1)
|
|
assert len(results_with_offset.to_pandas()) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_pandas_kwargs(table, table_async):
|
|
sync_df = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.select(["id"])
|
|
.limit(1)
|
|
.to_pandas(split_blocks=True)
|
|
)
|
|
assert sync_df["id"].tolist() == [1]
|
|
|
|
async_df = await (
|
|
table_async.query().select(["id"]).limit(2).to_pandas(split_blocks=True)
|
|
)
|
|
assert async_df["id"].tolist() == [1, 2]
|
|
|
|
|
|
@pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"])
|
|
def test_plain_scan_query_to_pandas_blob_modes(tmp_db, blob_mode):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
f"test_query_to_pandas_blob_{blob_mode}",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
|
|
df = (
|
|
table.search()
|
|
.select(["id", "blob"])
|
|
.where("id = 1")
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
|
|
assert df["id"].tolist() == [1]
|
|
if blob_mode == "lazy":
|
|
_assert_lazy_blob(df["blob"].iloc[0], b"one")
|
|
elif blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [b"one"]
|
|
else:
|
|
first = df["blob"].iloc[0]
|
|
assert first != b"one"
|
|
assert not hasattr(first, "readall")
|
|
|
|
|
|
@pytest.mark.parametrize("blob_schema", ["v1", "v2"])
|
|
def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
|
|
pytest.importorskip("lance")
|
|
table = _blob_query_table(
|
|
tmp_db, f"test_query_to_pandas_blob_{blob_schema}_bytes", blob_schema
|
|
)
|
|
|
|
df = (
|
|
table.search()
|
|
.where("id >= 2")
|
|
.select({"id_alias": "id", "payload": "blob", "double_id": "id * 2"})
|
|
.limit(2)
|
|
.offset(1)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
|
|
_assert_blob_bytes_projection(df)
|
|
assert "_rowid" not in df.columns
|
|
|
|
|
|
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
|
def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
|
tmp_db, monkeypatch, blob_mode
|
|
):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
"test_query_to_pandas_blob_no_arrow_collect",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
query = table.search().where("id = 1").select(["id", "blob"])
|
|
|
|
def fail_to_arrow(*args, **kwargs):
|
|
raise AssertionError("to_arrow should not be called before native pandas")
|
|
|
|
if blob_mode == "descriptions":
|
|
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
|
|
|
df = query.to_pandas(blob_mode=blob_mode)
|
|
|
|
assert df["id"].tolist() == [1]
|
|
if blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [b"one"]
|
|
else:
|
|
first = df["blob"].iloc[0]
|
|
assert first != b"one"
|
|
assert not hasattr(first, "readall")
|
|
|
|
|
|
def test_plain_scan_query_to_pandas_blob_descriptions_flatten_uses_scanner(
|
|
tmp_db, monkeypatch
|
|
):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
"test_query_to_pandas_blob_desc_flatten",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
query = table.search().where("id = 1").select(["id", "blob"])
|
|
|
|
def fail_to_arrow(*args, **kwargs):
|
|
raise AssertionError("to_arrow should not be called before scanner pandas")
|
|
|
|
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
|
|
|
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
|
|
|
assert df["id"].tolist() == [1]
|
|
assert any(column == "blob" or column.startswith("blob.") for column in df.columns)
|
|
|
|
|
|
def test_plain_scan_query_to_pandas_scanner_state(tmp_db):
|
|
pytest.importorskip("lance")
|
|
data = _blob_query_data()
|
|
table = tmp_db.create_table(
|
|
"test_query_to_pandas_scanner_state",
|
|
data.slice(0, 2),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
table.add(data.slice(2, 2))
|
|
|
|
fragments = table.to_lance().get_fragments()
|
|
assert len(fragments) == 2
|
|
|
|
query = (
|
|
table.search()
|
|
.select(["id", "blob"])
|
|
.with_row_address()
|
|
.fragment_ids([fragments[1].fragment_id])
|
|
)
|
|
query_obj = query.to_query_object()
|
|
assert query_obj.with_row_address is True
|
|
assert query_obj.fragment_ids == [fragments[1].fragment_id]
|
|
|
|
df = query.to_pandas(blob_mode="descriptions")
|
|
|
|
assert df["id"].tolist() == [3, 4]
|
|
assert "_rowaddr" in df.columns
|
|
assert {rowaddr >> 32 for rowaddr in df["_rowaddr"]} == {fragments[1].fragment_id}
|
|
|
|
df_by_fragment = (
|
|
table.search()
|
|
.select(["id", "blob"])
|
|
.with_fragments([fragments[0]])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)
|
|
assert df_by_fragment["id"].tolist() == [1, 2]
|
|
|
|
empty = (
|
|
table.search()
|
|
.select(["id", "blob"])
|
|
.fragment_ids([])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)
|
|
assert empty.empty
|
|
with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"):
|
|
(
|
|
table.search()
|
|
.select(["id", "blob"])
|
|
.fragment_ids([999])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"terminal",
|
|
[
|
|
"to_arrow",
|
|
"to_batches",
|
|
"to_pandas",
|
|
"to_polars",
|
|
"to_list",
|
|
"explain_plan",
|
|
"analyze_plan",
|
|
],
|
|
)
|
|
def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal):
|
|
pytest.importorskip("lance")
|
|
table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}")
|
|
fragment_id = table.to_lance().get_fragments()[0].fragment_id
|
|
query = table.search().fragment_ids([fragment_id])
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
getattr(query, terminal)()
|
|
|
|
|
|
def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db):
|
|
pytest.importorskip("lance")
|
|
table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments")
|
|
fragment = table.to_lance().get_fragments()[0]
|
|
|
|
for query in (
|
|
table.search().with_fragments([fragment]),
|
|
table.search([0.0, 0.0]).with_fragments([fragment]),
|
|
):
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
query.to_arrow()
|
|
|
|
|
|
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
|
def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction):
|
|
pytest.importorskip("lance")
|
|
table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}")
|
|
table.create_index("text", config=FTS(with_position=False))
|
|
fragment = table.to_lance().get_fragments()[1]
|
|
query = _apply_fragment_restriction(
|
|
table.search("one", query_type="fts"), restriction, fragment
|
|
)
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
query.count_rows()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"terminal",
|
|
[
|
|
"to_arrow",
|
|
"to_batches",
|
|
"to_pandas",
|
|
"to_polars",
|
|
"to_list",
|
|
"explain_plan",
|
|
"analyze_plan",
|
|
],
|
|
)
|
|
async def test_async_fragment_constraints_fail_loud_on_unsupported_paths(
|
|
tmp_db_async, terminal
|
|
):
|
|
pytest.importorskip("lance")
|
|
data = _fragment_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
f"async_fragment_guard_{terminal}", data.slice(0, 2)
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
fragments = (await table.to_lance()).get_fragments()
|
|
query = table.query().fragment_ids([fragments[0].fragment_id])
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
await getattr(query, terminal)()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries(
|
|
tmp_db_async,
|
|
):
|
|
pytest.importorskip("lance")
|
|
data = _fragment_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
"async_fragment_guard_with_fragments", data.slice(0, 2)
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
fragments = (await table.to_lance()).get_fragments()
|
|
|
|
for query in (
|
|
table.query().with_fragments([fragments[0]]),
|
|
table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]),
|
|
):
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
await query.to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async):
|
|
pytest.importorskip("lance")
|
|
data = _blob_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
"async_fragment_supported",
|
|
data.slice(0, 2),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
fragments = (await table.to_lance()).get_fragments()
|
|
|
|
df = await (
|
|
table.query()
|
|
.select(["id", "blob"])
|
|
.fragment_ids([fragments[1].fragment_id])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)
|
|
|
|
assert df["id"].tolist() == [3, 4]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
|
async def test_async_fts_count_rows_rejects_fragment_constraints(
|
|
tmp_db_async, restriction
|
|
):
|
|
pytest.importorskip("lance")
|
|
data = _fragment_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
f"async_fts_count_rows_{restriction}", data.slice(0, 2)
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
await table.create_index("text", config=FTS(with_position=False))
|
|
fragment = (await table.to_lance()).get_fragments()[1]
|
|
query = _apply_fragment_restriction(
|
|
table.query().nearest_to_text("one"), restriction, fragment
|
|
)
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
await query.count_rows()
|
|
|
|
transitioned = _apply_fragment_restriction(
|
|
table.query(), restriction, fragment
|
|
).nearest_to_text("one")
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
await transitioned.count_rows()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
|
@pytest.mark.parametrize(
|
|
"transition",
|
|
["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"],
|
|
)
|
|
async def test_async_fragment_constraints_survive_query_transitions(
|
|
tmp_db_async, transition, restriction
|
|
):
|
|
pytest.importorskip("lance")
|
|
data = _fragment_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
f"async_transition_{transition}_{restriction}", data.slice(0, 2)
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
await table.create_index("text", config=FTS(with_position=False))
|
|
fragment = (await table.to_lance()).get_fragments()[1]
|
|
|
|
if transition == "query_to_vector":
|
|
query = _apply_fragment_restriction(
|
|
table.query(), restriction, fragment
|
|
).nearest_to([0.0, 0.0])
|
|
elif transition == "query_to_fts":
|
|
query = _apply_fragment_restriction(
|
|
table.query(), restriction, fragment
|
|
).nearest_to_text("one")
|
|
elif transition == "fts_to_hybrid":
|
|
query = _apply_fragment_restriction(
|
|
table.query().nearest_to_text("one"), restriction, fragment
|
|
).nearest_to([0.0, 0.0])
|
|
else:
|
|
query = _apply_fragment_restriction(
|
|
table.query().nearest_to([0.0, 0.0]), restriction, fragment
|
|
).nearest_to_text("one")
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
await query.to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async):
|
|
pytest.importorskip("lance")
|
|
table = await tmp_db_async.create_table(
|
|
"test_async_query_to_pandas_blob_projection",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
|
|
lazy_df = await (
|
|
table.query().where("id = 1").select(["id", "blob"]).to_pandas(blob_mode="lazy")
|
|
)
|
|
assert lazy_df["id"].tolist() == [1]
|
|
_assert_lazy_blob(lazy_df["blob"].iloc[0], b"one")
|
|
|
|
desc_df = await (
|
|
table.query()
|
|
.where("id = 1")
|
|
.select(["blob"])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)
|
|
first = desc_df["blob"].iloc[0]
|
|
assert first != b"one"
|
|
assert not hasattr(first, "readall")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("blob_schema", ["v1", "v2"])
|
|
async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
|
|
tmp_db_async, blob_schema
|
|
):
|
|
pytest.importorskip("lance")
|
|
table = await _blob_query_table_async(
|
|
tmp_db_async,
|
|
f"test_async_query_to_pandas_blob_{blob_schema}_bytes",
|
|
blob_schema,
|
|
)
|
|
|
|
df = await (
|
|
table.query()
|
|
.where("id >= 2")
|
|
.select({"id_alias": "id", "payload": "blob", "double_id": "id * 2"})
|
|
.limit(2)
|
|
.offset(1)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
|
|
_assert_blob_bytes_projection(df)
|
|
assert "_rowid" not in df.columns
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
|
async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
|
tmp_db_async, monkeypatch, blob_mode
|
|
):
|
|
pytest.importorskip("lance")
|
|
table = await tmp_db_async.create_table(
|
|
"test_async_query_to_pandas_blob_no_arrow_collect",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
query = table.query().where("id = 1").select(["id", "blob"])
|
|
|
|
async def fail_to_arrow(*args, **kwargs):
|
|
raise AssertionError("to_arrow should not be called before native pandas")
|
|
|
|
if blob_mode == "descriptions":
|
|
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
|
|
|
df = await query.to_pandas(blob_mode=blob_mode)
|
|
|
|
assert df["id"].tolist() == [1]
|
|
if blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [b"one"]
|
|
else:
|
|
first = df["blob"].iloc[0]
|
|
assert first != b"one"
|
|
assert not hasattr(first, "readall")
|
|
|
|
|
|
def test_vector_query_to_pandas_blob_mode_requires_native_path(tmp_db):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
"test_vector_query_blob_mode",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
|
|
with pytest.raises(RuntimeError, match="no fetchable blob v2 source"):
|
|
table.search([1.0, 0.0]).select(["blob", "vector"]).limit(1).to_pandas(
|
|
blob_mode="lazy"
|
|
)
|
|
|
|
|
|
def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
"test_vector_query_blob_descriptions",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
query = table.search([1.0, 0.0]).select(["blob", "vector"]).limit(1)
|
|
|
|
df = query.to_pandas(blob_mode="descriptions")
|
|
assert df["blob"].tolist() == [{"position": 0, "size": 3}]
|
|
|
|
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
|
query.to_pandas(blob_mode="bytes")
|
|
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
|
query.to_arrow(blob_mode="bytes")
|
|
table_arrow = table.to_arrow(blob_mode="bytes")
|
|
assert table_arrow.schema.field("blob").type == pa.large_binary()
|
|
assert "_rowid" not in table_arrow.column_names
|
|
assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
|
|
assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
|
|
b"one",
|
|
b"two",
|
|
b"three",
|
|
b"four",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes", "descriptions"])
|
|
@pytest.mark.parametrize("with_row_id", [None, True, False])
|
|
def test_vector_query_to_pandas_blob_v2_modes(tmp_db, blob_mode, with_row_id):
|
|
pytest.importorskip("lance")
|
|
table = _create_blob_v2_query_table(tmp_db, f"test_vector_blob_v2_{blob_mode}")
|
|
|
|
query = table.search([1.0, 0.0]).select(["id", "blob", "vector"]).limit(1)
|
|
if with_row_id is not None:
|
|
query = query.with_row_id(with_row_id)
|
|
df = (
|
|
query.to_pandas()
|
|
if blob_mode == "default"
|
|
else query.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
|
|
assert df["id"].tolist() == [1]
|
|
assert ("_rowid" in df.columns) == (with_row_id is True)
|
|
if blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [b"one"]
|
|
else:
|
|
descriptor = df["blob"].iloc[0]
|
|
assert descriptor != b"one"
|
|
assert not hasattr(descriptor, "readall")
|
|
assert "_lance_row_id" not in descriptor
|
|
|
|
|
|
@pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"])
|
|
def test_blob_v2_non_scan_query_shapes_to_pandas(tmp_db, blob_mode):
|
|
pytest.importorskip("lance")
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_query_shapes")
|
|
table.create_index("tag", config=FTS())
|
|
|
|
queries = [
|
|
table.search("keep", query_type="fts").limit(2),
|
|
table.search(query_type="hybrid").vector([1.0, 0.0]).text("keep").limit(2),
|
|
table.take_offsets([1, 2]).select(["id", "blob"]),
|
|
]
|
|
for query in queries:
|
|
df = query.to_pandas(blob_mode=blob_mode)
|
|
assert len(df) == 2
|
|
if blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [
|
|
{1: b"one", 2: b"two", 3: b"three", 4: b"four"}[row_id]
|
|
for row_id in df["id"]
|
|
]
|
|
else:
|
|
assert all("_lance_row_id" not in blob for blob in df["blob"])
|
|
assert "_rowid" not in df.columns
|
|
|
|
|
|
@pytest.mark.parametrize("rename_parent", [False, True])
|
|
def test_vector_query_to_pandas_nested_blob_bytes(tmp_db, rename_parent):
|
|
pytest.importorskip("lance")
|
|
table = tmp_db.create_table(
|
|
f"test_vector_nested_blob_{rename_parent}",
|
|
schema=_nested_blob_v2_query_schema(),
|
|
)
|
|
table.add(_nested_blob_v2_query_rows())
|
|
|
|
projection = {"id": "id", "renamed": "info"} if rename_parent else ["id", "info"]
|
|
df = (
|
|
table.search([1.0, 0.0])
|
|
.select(projection)
|
|
.limit(2)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
|
|
assert df["id"].tolist() == [1, 2]
|
|
parent = "renamed" if rename_parent else "info"
|
|
assert df[parent].tolist() == [
|
|
{"label": "one", "blob": b"one"},
|
|
{"label": "two", "blob": b"two"},
|
|
]
|
|
for blob_mode in ("lazy", "descriptions"):
|
|
descriptors = (
|
|
table.search([1.0, 0.0])
|
|
.select(projection)
|
|
.limit(1)
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert "_lance_row_id" not in descriptors[parent].iloc[0]["blob"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_vector_query_to_pandas_nested_blob_bytes(tmp_db_async):
|
|
pytest.importorskip("lance")
|
|
table = await tmp_db_async.create_table(
|
|
"test_async_vector_nested_blob",
|
|
schema=_nested_blob_v2_query_schema(),
|
|
)
|
|
await table.add(_nested_blob_v2_query_rows())
|
|
|
|
df = await (
|
|
table.vector_search([1.0, 0.0])
|
|
.select(["id", "info"])
|
|
.limit(2)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
|
|
assert df["id"].tolist() == [1, 2]
|
|
assert df["info"].tolist() == [
|
|
{"label": "one", "blob": b"one"},
|
|
{"label": "two", "blob": b"two"},
|
|
]
|
|
|
|
|
|
def test_blob_v2_vector_projection_and_plain_scan_options(tmp_db, monkeypatch):
|
|
pytest.importorskip("lance")
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_pandas_options")
|
|
|
|
df = (
|
|
table.search([1.0, 0.0])
|
|
.select({"payload": "blob", "id": "id"})
|
|
.limit(1)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
assert df["payload"].tolist() == [b"one"]
|
|
|
|
query = table.search().where("id = 1")
|
|
|
|
def fail_to_lance(*args, **kwargs):
|
|
raise AssertionError("blob v2 bytes should not open a pylance dataset")
|
|
|
|
monkeypatch.setattr(table, "to_lance", fail_to_lance)
|
|
assert query.to_pandas(blob_mode="bytes", flatten=True)["blob"].tolist() == [b"one"]
|
|
|
|
flattened_lazy = table.search().where("id = 1").to_pandas(flatten=True)
|
|
assert flattened_lazy["id"].tolist() == [1]
|
|
assert not any("_lance_row_id" in col for col in flattened_lazy.columns)
|
|
|
|
timed = (
|
|
table.search()
|
|
.where("id = 1")
|
|
.to_pandas(blob_mode="bytes", timeout=timedelta(seconds=10))
|
|
)
|
|
assert timed["blob"].tolist() == [b"one"]
|
|
|
|
timed_lazy = table.search().where("id = 1").to_pandas(timeout=timedelta(seconds=10))
|
|
assert timed_lazy["id"].tolist() == [1]
|
|
|
|
|
|
def test_blob_v2_pandas_preserves_fetch_error(tmp_db, monkeypatch):
|
|
pytest.importorskip("lance")
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_fetch_error")
|
|
|
|
def missing_blob(*args, **kwargs):
|
|
raise FileNotFoundError("missing obj.bin")
|
|
|
|
monkeypatch.setattr(table, "fetch_blobs", missing_blob)
|
|
with pytest.raises(FileNotFoundError, match="missing obj.bin"):
|
|
table.search().to_pandas(blob_mode="bytes")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"])
|
|
@pytest.mark.parametrize("with_row_id", [False, True])
|
|
async def test_async_vector_query_to_pandas_blob_v2_modes(
|
|
tmp_db_async, blob_mode, with_row_id
|
|
):
|
|
pytest.importorskip("lance")
|
|
table = await _create_blob_v2_query_table_async(
|
|
tmp_db_async, f"test_async_vector_blob_v2_{blob_mode}"
|
|
)
|
|
|
|
query = table.vector_search([1.0, 0.0]).limit(1)
|
|
if with_row_id:
|
|
query = query.with_row_id()
|
|
df = await query.to_pandas(blob_mode=blob_mode)
|
|
assert df["id"].tolist() == [1]
|
|
assert ("_rowid" in df.columns) == with_row_id
|
|
if blob_mode == "bytes":
|
|
assert df["blob"].tolist() == [b"one"]
|
|
else:
|
|
assert "_lance_row_id" not in df["blob"].iloc[0]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
|
|
pytest.importorskip("lance")
|
|
table = await _create_blob_v2_query_table_async(
|
|
tmp_db_async, "test_async_take_blob_v2"
|
|
)
|
|
|
|
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
|
|
assert set(df["blob"]) == {b"two", b"three"}
|
|
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
|
|
blob_mode="bytes"
|
|
)
|
|
assert ordered["blob"].tolist() == [b"three", b"two"]
|
|
|
|
|
|
def test_order_by_plain_query(mem_db):
|
|
table = mem_db.create_table(
|
|
"test_order_by",
|
|
pa.table(
|
|
{
|
|
"group": [1, 1, 1, 2],
|
|
"score": [None, 1.0, 1.0, 0.5],
|
|
"name": ["z", "b", "a", "c"],
|
|
}
|
|
),
|
|
)
|
|
|
|
res = (
|
|
table.search()
|
|
.order_by(
|
|
[
|
|
ColumnOrdering(column_name="group", ascending=True, nulls_first=False),
|
|
ColumnOrdering(column_name="score", ascending=True, nulls_first=True),
|
|
ColumnOrdering(column_name="name", ascending=True, nulls_first=False),
|
|
]
|
|
)
|
|
.to_arrow()
|
|
)
|
|
|
|
assert res.select(["group", "score", "name"]).to_pylist() == [
|
|
{"group": 1, "score": None, "name": "z"},
|
|
{"group": 1, "score": 1.0, "name": "a"},
|
|
{"group": 1, "score": 1.0, "name": "b"},
|
|
{"group": 2, "score": 0.5, "name": "c"},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_order_by_async_query(mem_db_async: AsyncConnection):
|
|
table = await mem_db_async.create_table(
|
|
"test_order_by_async",
|
|
pa.table(
|
|
{
|
|
"group": [1, 1, 1, 2],
|
|
"score": [None, 1.0, 1.0, 0.5],
|
|
"name": ["z", "b", "a", "c"],
|
|
}
|
|
),
|
|
)
|
|
|
|
res = await (
|
|
table.query()
|
|
.order_by(
|
|
[
|
|
ColumnOrdering(column_name="group", ascending=True, nulls_first=False),
|
|
ColumnOrdering(column_name="score", ascending=True, nulls_first=True),
|
|
ColumnOrdering(column_name="name", ascending=True, nulls_first=False),
|
|
]
|
|
)
|
|
.to_arrow()
|
|
)
|
|
|
|
assert res.select(["group", "score", "name"]).to_pylist() == [
|
|
{"group": 1, "score": None, "name": "z"},
|
|
{"group": 1, "score": 1.0, "name": "a"},
|
|
{"group": 1, "score": 1.0, "name": "b"},
|
|
{"group": 2, "score": 0.5, "name": "c"},
|
|
]
|
|
|
|
|
|
def test_order_by_accepts_strings_tuples_and_dicts(mem_db):
|
|
table = mem_db.create_table(
|
|
"test_order_by_forms",
|
|
pa.table(
|
|
{
|
|
"group": [1, 1, 1, 2],
|
|
"score": [None, 1.0, 1.0, 0.5],
|
|
"name": ["z", "b", "a", "c"],
|
|
}
|
|
),
|
|
)
|
|
|
|
rows = (
|
|
table.search()
|
|
.order_by(
|
|
[
|
|
"group",
|
|
("score", "desc"),
|
|
{"column_name": "name", "ascending": True},
|
|
]
|
|
)
|
|
.select(["name"])
|
|
.to_list()
|
|
)
|
|
assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}]
|
|
|
|
# A bare tuple is one direction pair; a list holds separate orderings.
|
|
assert table.search().order_by("name").select(["name"]).to_list() == [
|
|
{"name": "a"},
|
|
{"name": "b"},
|
|
{"name": "c"},
|
|
{"name": "z"},
|
|
]
|
|
assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [
|
|
{"name": "z"},
|
|
{"name": "c"},
|
|
{"name": "b"},
|
|
{"name": "a"},
|
|
]
|
|
assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [
|
|
{"name": "a"},
|
|
{"name": "b"},
|
|
{"name": "z"},
|
|
{"name": "c"},
|
|
]
|
|
|
|
|
|
def test_order_by_clears_with_none_and_empty_list(mem_db):
|
|
table = mem_db.create_table("test_order_by_clear", [{"name": "a"}])
|
|
|
|
query = table.search().order_by("name")
|
|
assert query.to_query_object().order_by is not None
|
|
assert query.order_by(None).to_query_object().order_by is None
|
|
assert query.order_by([]).to_query_object().order_by is None
|
|
|
|
|
|
def test_plain_scan_with_row_address_sync(tmp_db):
|
|
table = tmp_db.create_table(
|
|
"row_addresses",
|
|
pa.table({"id": [1, 2, 3], "value": ["a", "b", "c"]}),
|
|
storage_options={"new_table_enable_stable_row_ids": "true"},
|
|
)
|
|
table.add(pa.table({"id": [4], "value": ["d"]}))
|
|
assert table.stats()["fragment_stats"]["num_fragments"] == 2
|
|
|
|
query = table.search()
|
|
assert query.to_arrow().column_names == ["id", "value"]
|
|
reader = query.with_row_address().to_batches()
|
|
assert "_rowaddr" in reader.schema.names
|
|
rows = reader.read_all().sort_by("id")
|
|
assert rows["_rowaddr"].type == pa.uint64()
|
|
assert rows["_rowaddr"].to_pylist() == [0, 1, 2, 1 << 32]
|
|
assert "_rowid" not in rows.column_names
|
|
|
|
projected = (
|
|
query.where("id >= 3").select(["id"]).with_row_id(True).to_arrow()
|
|
).sort_by("id")
|
|
assert set(projected.column_names) == {"id", "_rowid", "_rowaddr"}
|
|
assert projected["_rowaddr"].to_pylist() == [2, 1 << 32]
|
|
assert projected["_rowid"][1].as_py() != projected["_rowaddr"][1].as_py()
|
|
assert query.with_row_address(False).to_arrow().column_names == ["id", "_rowid"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_plain_scan_with_row_address_async(tmp_db_async):
|
|
table = await tmp_db_async.create_table(
|
|
"row_addresses",
|
|
pa.table({"id": [1, 2, 3], "value": ["a", "b", "c"]}),
|
|
storage_options={"new_table_enable_stable_row_ids": "true"},
|
|
)
|
|
await table.add(pa.table({"id": [4], "value": ["d"]}))
|
|
assert (await table.stats())["fragment_stats"]["num_fragments"] == 2
|
|
|
|
query = table.query()
|
|
assert (await query.to_arrow()).column_names == ["id", "value"]
|
|
rows = (await query.with_row_address().to_arrow()).sort_by("id")
|
|
assert "_rowaddr" in rows.column_names
|
|
assert rows["_rowaddr"].type == pa.uint64()
|
|
assert rows["_rowaddr"].to_pylist() == [0, 1, 2, 1 << 32]
|
|
assert "_rowid" not in rows.column_names
|
|
|
|
query = query.where("id >= 3").select({"key": "id"}).with_row_id()
|
|
projected = (await query.to_arrow()).sort_by("key")
|
|
assert set(projected.column_names) == {"key", "_rowid", "_rowaddr"}
|
|
assert projected["_rowaddr"].to_pylist() == [2, 1 << 32]
|
|
assert projected["_rowid"][1].as_py() != projected["_rowaddr"][1].as_py()
|
|
assert (await query.with_row_address(False).to_arrow()).column_names == [
|
|
"key",
|
|
"_rowid",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("fts", [False, True], ids=["vector", "fts"])
|
|
async def test_async_search_conversion_does_not_add_row_address(tmp_db_async, fts):
|
|
table = await tmp_db_async.create_table(
|
|
"row_address_search", _fragment_query_data()
|
|
)
|
|
if fts:
|
|
await table.create_index("text", config=FTS())
|
|
|
|
def as_search(query):
|
|
if fts:
|
|
return query.nearest_to_text("one")
|
|
return query.nearest_to([1.0, 0.0])
|
|
|
|
scan = table.query().with_row_address()
|
|
before = as_search(scan)
|
|
after = as_search(table.query()).with_row_address()
|
|
|
|
for query in (before, after):
|
|
assert "_rowaddr" not in (await query.output_schema()).names
|
|
result = await query.to_arrow()
|
|
assert result.num_rows > 0
|
|
assert "_rowaddr" not in result.column_names
|
|
|
|
assert "_rowaddr" in (await scan.to_arrow()).column_names
|
|
|
|
|
|
def test_scan_in_order_plain_query(tmp_db):
|
|
table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
|
|
table.add(pa.table({"id": [2, 3]}))
|
|
table.add(pa.table({"id": [4, 5]}))
|
|
|
|
fragments = table.to_lance().get_fragments()
|
|
assert len(fragments) == 3, "the test needs real multi-fragment data"
|
|
|
|
version = table.version
|
|
table.checkout(version)
|
|
|
|
default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
|
|
assert default == [0, 1, 2, 3, 4, 5]
|
|
assert table.search().to_query_object().scan_in_order is None
|
|
|
|
ordered = table.search().scan_in_order().select(["id"]).to_arrow()
|
|
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
|
repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
|
|
assert repeated.equals(ordered)
|
|
|
|
unordered = (
|
|
table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
|
|
)
|
|
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
|
|
|
sorted_desc = (
|
|
table.search()
|
|
.scan_in_order(False)
|
|
.order_by(("id", "desc"))
|
|
.select(["id"])
|
|
.to_arrow()["id"]
|
|
.to_pylist()
|
|
)
|
|
assert sorted_desc == [5, 4, 3, 2, 1, 0]
|
|
|
|
with pytest.raises(ValueError, match="nonempty order_by"):
|
|
table.search().scan_in_order().order_by("id").to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
|
|
table = await tmp_db_async.create_table(
|
|
"scan_in_order_async", pa.table({"id": [0, 1]})
|
|
)
|
|
await table.add(pa.table({"id": [2, 3]}))
|
|
await table.add(pa.table({"id": [4, 5]}))
|
|
|
|
assert len((await table.to_lance()).get_fragments()) == 3
|
|
version = await table.version()
|
|
await table.checkout(version)
|
|
|
|
ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
|
|
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
|
assert table.query().to_query_object().scan_in_order is None
|
|
|
|
unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
|
|
"id"
|
|
].to_pylist()
|
|
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
|
|
|
with pytest.raises(ValueError, match="nonempty order_by"):
|
|
await table.query().scan_in_order().order_by("id").to_arrow()
|
|
with pytest.raises(ValueError, match="ranked results"):
|
|
await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
|
|
|
|
|
|
@pytest.mark.parametrize("ordered", [False, True])
|
|
def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
|
|
pytest.importorskip("lance")
|
|
data = _blob_query_data()
|
|
table = tmp_db.create_table(
|
|
f"scan_in_order_scanner_{ordered}",
|
|
data.slice(0, 2),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
table.add(data.slice(2, 2))
|
|
|
|
query = table.search().select(["id", "blob"]).scan_in_order(ordered)
|
|
|
|
def fail_to_arrow(*args, **kwargs):
|
|
raise AssertionError("scanner-backed pandas must not collect through to_arrow")
|
|
|
|
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
|
|
|
dataset = table.to_lance()
|
|
dataset_cls = type(dataset)
|
|
real_scanner = dataset_cls.scanner
|
|
captured = {}
|
|
|
|
def capture_scanner(self, **kwargs):
|
|
captured.update(kwargs)
|
|
return real_scanner(self, **kwargs)
|
|
|
|
monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
|
|
|
|
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
|
|
|
assert captured["scan_in_order"] is ordered
|
|
assert captured.get("use_scalar_index") is (False if ordered else None)
|
|
assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
|
|
|
|
|
|
@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
|
|
def test_scan_in_order_indexed_filter_preserves_manifest_order(
|
|
tmp_path, storage_version
|
|
):
|
|
lance = pytest.importorskip("lance")
|
|
data = pa.table({"id": list(range(20)), "value": list(range(20))})
|
|
dataset = lance.write_dataset(
|
|
data,
|
|
tmp_path / "t.lance",
|
|
data_storage_version=storage_version,
|
|
max_rows_per_file=10,
|
|
)
|
|
dataset.create_scalar_index("value", "BTREE")
|
|
version_before_update = dataset.version
|
|
dataset.update({"value": "100"}, where="id = 0")
|
|
|
|
table = lancedb.connect(str(tmp_path)).open_table("t")
|
|
for version in (version_before_update, dataset.version):
|
|
table.checkout(version)
|
|
base = table.search().scan_in_order(True).select(["id"]).limit(100)
|
|
expected = base.to_arrow()["id"].to_pylist()
|
|
actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
|
|
assert actual == expected
|
|
|
|
|
|
def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
|
|
pytest.importorskip("lance")
|
|
data = _blob_query_data()
|
|
table = tmp_db.create_table(
|
|
"scan_in_order_fragments",
|
|
data.slice(0, 2),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
table.add(data.slice(2, 2))
|
|
table.checkout(table.version)
|
|
|
|
fragments = table.to_lance().get_fragments()
|
|
reversed_fragments = fragments[::-1]
|
|
with pytest.raises(ValueError, match="use fragment_ids"):
|
|
(
|
|
table.search()
|
|
.scan_in_order()
|
|
.select(["id", "blob"])
|
|
.with_fragments(reversed_fragments)
|
|
.to_pandas(blob_mode="descriptions", flatten=True)
|
|
)
|
|
|
|
# fragment_ids is already resolved from the manifest and stays ordered.
|
|
df_by_id = (
|
|
table.search()
|
|
.scan_in_order()
|
|
.select(["id", "blob"])
|
|
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
|
.to_pandas(blob_mode="descriptions", flatten=True)
|
|
)
|
|
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
|
|
tmp_db_async,
|
|
):
|
|
pytest.importorskip("lance")
|
|
data = _blob_query_data()
|
|
table = await tmp_db_async.create_table(
|
|
"scan_in_order_fragments_async",
|
|
data.slice(0, 2),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
await table.add(data.slice(2, 2))
|
|
await table.checkout(await table.version())
|
|
|
|
fragments = (await table.to_lance()).get_fragments()
|
|
reversed_fragments = fragments[::-1]
|
|
with pytest.raises(ValueError, match="use fragment_ids"):
|
|
await (
|
|
table.query()
|
|
.scan_in_order()
|
|
.with_fragments(fragments[::-1])
|
|
.select(["id", "blob"])
|
|
.to_pandas(blob_mode="descriptions", flatten=True)
|
|
)
|
|
|
|
df_by_id = await (
|
|
table.query()
|
|
.scan_in_order()
|
|
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
|
.select(["id", "blob"])
|
|
.to_pandas(blob_mode="descriptions", flatten=True)
|
|
)
|
|
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
|
|
|
|
|
def test_order_by_rejects_invalid_input_early(mem_db):
|
|
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
|
|
|
|
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
|
table.search().order_by([{"column": "name", "ascending": True}])
|
|
with pytest.raises(ValueError, match="missing 'column_name'"):
|
|
table.search().order_by({"ascending": True})
|
|
with pytest.raises(ValueError, match="invalid direction"):
|
|
table.search().order_by([("name", "sideways")])
|
|
with pytest.raises(TypeError, match="must be a column name"):
|
|
table.search().order_by([42])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection):
|
|
table = await mem_db_async.create_table(
|
|
"test_order_by_async_forms",
|
|
pa.table({"name": ["z", "b", "a", "c"]}),
|
|
)
|
|
|
|
rows = await (
|
|
table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow()
|
|
)
|
|
assert rows["name"].to_pylist() == ["z", "c", "b", "a"]
|
|
|
|
query = table.query().order_by("name")
|
|
assert query.to_query_object().order_by is not None
|
|
assert query.order_by(None).to_query_object().order_by is None
|
|
assert query.order_by([]).to_query_object().order_by is None
|
|
|
|
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
|
table.query().order_by([{"column": "name"}])
|
|
|
|
|
|
def test_column_ordering_is_exported_at_top_level():
|
|
assert lancedb.ColumnOrdering is ColumnOrdering
|
|
|
|
|
|
def test_order_by_hybrid_sync_is_explicitly_unsupported(table):
|
|
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a")
|
|
|
|
with pytest.raises(NotImplementedError, match="order_by is not supported"):
|
|
query.order_by(["id"])
|
|
|
|
# Clearing is still allowed, and invalid input still fails on its own terms.
|
|
query.order_by(None)
|
|
query.order_by([])
|
|
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
|
query.order_by([{"column": "id"}])
|
|
|
|
|
|
def test_query_builder(table):
|
|
rs = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.limit(1)
|
|
.select(["id", "vector"])
|
|
.to_list()
|
|
)
|
|
assert rs[0]["id"] == 1
|
|
assert all(np.array(rs[0]["vector"]) == [1, 2])
|
|
|
|
|
|
def test_query_multiple_vectors(table):
|
|
results = table.search([np.array([1, 2]), np.array([4, 5])]).limit(1).to_list()
|
|
|
|
assert len(results) == 2
|
|
results_by_query = {result["query_index"]: result for result in results}
|
|
assert results_by_query[0]["id"] == 1
|
|
assert results_by_query[1]["id"] == 2
|
|
|
|
|
|
def test_with_row_id(table: lancedb.table.Table):
|
|
rs = table.search().with_row_id(True).to_arrow()
|
|
assert "_rowid" in rs.column_names
|
|
assert rs["_rowid"].to_pylist() == [0, 1]
|
|
|
|
|
|
def test_filter_preserves_deeply_nested_struct_fields(tmp_db):
|
|
# Regression test for https://github.com/lancedb/lancedb/issues/2217.
|
|
data = [
|
|
{
|
|
"item": "test",
|
|
"sub_obj": {
|
|
"second_sub_obj": [
|
|
{
|
|
"third_sub_obj": {"int_val": 1},
|
|
"str_val": "test",
|
|
}
|
|
]
|
|
},
|
|
}
|
|
]
|
|
table = tmp_db.create_table("deeply_nested_struct", data=data)
|
|
|
|
result = table.search().where("item = 'test'").limit(1).to_arrow()
|
|
|
|
assert result.to_pylist() == data
|
|
|
|
|
|
def test_blob_v2_query_omits_auto_row_id(tmp_db):
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_omits_auto_rowid")
|
|
|
|
query_obj = table.search().select(["id", "blob"]).limit(2).to_query_object()
|
|
assert query_obj.with_row_id is None
|
|
|
|
rs = table.search().select(["id", "blob"]).limit(2).to_arrow()
|
|
|
|
assert "_rowid" not in rs.column_names
|
|
assert rs["id"].to_pylist() == [1, 2]
|
|
|
|
|
|
def test_where_repeated_combines_with_and(table: lancedb.table.Table):
|
|
# Calling where() more than once should AND the filters together instead of
|
|
# silently replacing the previous one (regression test for #2649).
|
|
builder = table.search().where("id >= 1").where("id < 2")
|
|
assert builder._where == "(id >= 1) AND (id < 2)"
|
|
|
|
ids = [row["id"] for row in builder.limit(10).to_list()]
|
|
assert ids == [1]
|
|
|
|
|
|
def test_where_repeated_combines_expr(table: lancedb.table.Table):
|
|
from lancedb.expr import col, lit
|
|
|
|
builder = table.search().where(col("id") >= lit(1)).where(col("id") < lit(2))
|
|
ids = [row["id"] for row in builder.limit(10).to_list()]
|
|
assert ids == [1]
|
|
|
|
|
|
def test_where_mixed_filter_kinds_combines(table: lancedb.table.Table):
|
|
# Mixing a SQL string filter with an expression filter lowers the
|
|
# expression to SQL and combines them as SQL strings.
|
|
from lancedb.expr import col, lit
|
|
|
|
builder = table.search().where("id >= 1").where(col("id") < lit(2))
|
|
ids = [row["id"] for row in builder.limit(10).to_list()]
|
|
assert ids == [1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_where_repeated_combines_with_and_async(table_async: AsyncTable):
|
|
ids = [
|
|
row["id"]
|
|
for row in (
|
|
await table_async.query().where("id >= 1").where("id < 2").to_list()
|
|
)
|
|
]
|
|
assert ids == [1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_where_mixed_filter_kinds_combines_async(table_async: AsyncTable):
|
|
from lancedb.expr import col, lit
|
|
|
|
ids = [
|
|
row["id"]
|
|
for row in (
|
|
await table_async.query()
|
|
.where("id >= 1")
|
|
.where(col("id") < lit(2))
|
|
.to_list()
|
|
)
|
|
]
|
|
assert ids == [1]
|
|
|
|
|
|
def test_distance_range(table: lancedb.table.Table):
|
|
q = [0, 0]
|
|
rs = table.search(q).to_arrow()
|
|
dists = rs["_distance"].to_pylist()
|
|
min_dist = dists[0]
|
|
max_dist = dists[-1]
|
|
|
|
res = table.search(q).distance_range(upper_bound=min_dist).to_arrow()
|
|
assert len(res) == 0
|
|
|
|
res = table.search(q).distance_range(lower_bound=max_dist).to_arrow()
|
|
assert len(res) == 1
|
|
assert res["_distance"].to_pylist() == [max_dist]
|
|
|
|
res = table.search(q).distance_range(upper_bound=max_dist).to_arrow()
|
|
assert len(res) == 1
|
|
assert res["_distance"].to_pylist() == [min_dist]
|
|
|
|
res = table.search(q).distance_range(lower_bound=min_dist).to_arrow()
|
|
assert len(res) == 2
|
|
assert res["_distance"].to_pylist() == [min_dist, max_dist]
|
|
|
|
|
|
@pytest.mark.parametrize("expression", ["1 - _distance", "1.0 - _distance"])
|
|
def test_select_arithmetic_with_distance(table, expression):
|
|
result = (
|
|
table.search([10, 10])
|
|
.select({"similarity": expression, "_distance": "_distance"})
|
|
.distance_type("cosine")
|
|
.to_arrow()
|
|
)
|
|
|
|
assert result.schema.field("similarity").type == pa.float32()
|
|
assert result["similarity"].to_pylist() == pytest.approx(
|
|
[1 - distance for distance in result["_distance"].to_pylist()]
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_distance_range_async(table_async: AsyncTable):
|
|
q = [0, 0]
|
|
rs = await table_async.query().nearest_to(q).to_arrow()
|
|
dists = rs["_distance"].to_pylist()
|
|
min_dist = dists[0]
|
|
max_dist = dists[-1]
|
|
|
|
res = (
|
|
await table_async.query()
|
|
.nearest_to(q)
|
|
.distance_range(upper_bound=min_dist)
|
|
.to_arrow()
|
|
)
|
|
assert len(res) == 0
|
|
|
|
res = (
|
|
await table_async.query()
|
|
.nearest_to(q)
|
|
.distance_range(lower_bound=max_dist)
|
|
.to_arrow()
|
|
)
|
|
assert len(res) == 1
|
|
assert res["_distance"].to_pylist() == [max_dist]
|
|
|
|
res = (
|
|
await table_async.query()
|
|
.nearest_to(q)
|
|
.distance_range(upper_bound=max_dist)
|
|
.to_arrow()
|
|
)
|
|
assert len(res) == 1
|
|
assert res["_distance"].to_pylist() == [min_dist]
|
|
|
|
res = (
|
|
await table_async.query()
|
|
.nearest_to(q)
|
|
.distance_range(lower_bound=min_dist)
|
|
.to_arrow()
|
|
)
|
|
assert len(res) == 2
|
|
assert res["_distance"].to_pylist() == [min_dist, max_dist]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_distance_range_with_new_rows_async():
|
|
conn = await lancedb.connect_async(
|
|
"memory://", read_consistency_interval=timedelta(seconds=0)
|
|
)
|
|
data = pa.table(
|
|
{
|
|
"vector": pa.FixedShapeTensorArray.from_numpy_ndarray(
|
|
np.random.rand(256, 2)
|
|
),
|
|
}
|
|
)
|
|
table = await conn.create_table("test", data)
|
|
await table.create_index(
|
|
"vector", config=IvfPq(num_partitions=1, num_sub_vectors=2)
|
|
)
|
|
|
|
q = [0, 0]
|
|
rs = await table.query().nearest_to(q).to_arrow()
|
|
dists = rs["_distance"].to_pylist()
|
|
min_dist = dists[0]
|
|
max_dist = dists[-1]
|
|
|
|
# append more rows so that execution plan would be mixed with ANN & Flat KNN
|
|
new_data = pa.table(
|
|
{
|
|
"vector": pa.FixedShapeTensorArray.from_numpy_ndarray(
|
|
np.random.rand(4, 2) + 1
|
|
),
|
|
}
|
|
)
|
|
await table.add(new_data)
|
|
|
|
res = (
|
|
await table.query()
|
|
.nearest_to(q)
|
|
.distance_range(upper_bound=min_dist)
|
|
.to_arrow()
|
|
)
|
|
assert len(res) == 0
|
|
|
|
res = (
|
|
await table.query()
|
|
.nearest_to(q)
|
|
.distance_range(lower_bound=max_dist)
|
|
.to_arrow()
|
|
)
|
|
for dist in res["_distance"].to_pylist():
|
|
assert dist >= max_dist
|
|
|
|
res = (
|
|
await table.query()
|
|
.nearest_to(q)
|
|
.distance_range(upper_bound=max_dist)
|
|
.to_arrow()
|
|
)
|
|
for dist in res["_distance"].to_pylist():
|
|
assert dist < max_dist
|
|
|
|
res = (
|
|
await table.query()
|
|
.nearest_to(q)
|
|
.distance_range(lower_bound=min_dist)
|
|
.to_arrow()
|
|
)
|
|
for dist in res["_distance"].to_pylist():
|
|
assert dist >= min_dist
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"multivec_table", [pa.float16(), pa.float32(), pa.float64()], indirect=True
|
|
)
|
|
def test_multivector(multivec_table: lancedb.table.Table):
|
|
# create index on multivector
|
|
multivec_table.create_index(
|
|
metric="cosine",
|
|
vector_column_name="vector",
|
|
index_type="IVF_PQ",
|
|
num_partitions=1,
|
|
num_sub_vectors=2,
|
|
)
|
|
|
|
# query with single vector
|
|
q = [1, 2]
|
|
rs = multivec_table.search(q).to_arrow()
|
|
|
|
# query with multiple vectors
|
|
q = [[1, 2], [1, 2]]
|
|
rs2 = multivec_table.search(q).to_arrow()
|
|
assert len(rs2) == len(rs)
|
|
for i in range(2):
|
|
assert rs2["_distance"][i].as_py() == rs["_distance"][i].as_py() * 2
|
|
|
|
# can't query with vector that dim not matched
|
|
with pytest.raises(Exception):
|
|
multivec_table.search([1, 2, 3]).to_arrow()
|
|
# can't query with vector list that some dim not matched
|
|
with pytest.raises(Exception):
|
|
multivec_table.search([[1, 2], [1, 2, 3]]).to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"multivec_table_async", [pa.float16(), pa.float32(), pa.float64()], indirect=True
|
|
)
|
|
async def test_multivector_async(multivec_table_async: AsyncTable):
|
|
# create index on multivector
|
|
await multivec_table_async.create_index(
|
|
"vector",
|
|
config=IvfPq(distance_type="cosine", num_partitions=1, num_sub_vectors=2),
|
|
)
|
|
|
|
# query with single vector
|
|
q = [1, 2]
|
|
rs = await multivec_table_async.query().nearest_to(q).to_arrow()
|
|
|
|
# query with multiple vectors
|
|
q = [[1, 2], [1, 2]]
|
|
rs2 = await multivec_table_async.query().nearest_to(q).to_arrow()
|
|
assert len(rs2) == len(rs)
|
|
for i in range(2):
|
|
assert rs2["_distance"][i].as_py() == rs["_distance"][i].as_py() * 2
|
|
|
|
# can't query with vector that dim not matched
|
|
with pytest.raises(Exception):
|
|
await multivec_table_async.query().nearest_to([1, 2, 3]).to_arrow()
|
|
# can't query with vector list that some dim not matched
|
|
with pytest.raises(Exception):
|
|
await multivec_table_async.query().nearest_to([[1, 2], [1, 2, 3]]).to_arrow()
|
|
|
|
|
|
def test_plain_scan_limit_zero_preserves_projection_without_returning_rows(mem_db):
|
|
table = mem_db.create_table("plain_limit", [{"id": 1, "text": "one"}])
|
|
query = table.search().select(["id"])
|
|
empty = pa.table({"id": pa.array([], pa.int64())})
|
|
|
|
assert query.limit(0).to_arrow().equals(empty)
|
|
assert query.to_batches().read_all().equals(empty)
|
|
assert query.limit(None).to_list() == [{"id": 1}]
|
|
|
|
|
|
def test_vector_query_with_no_limit(table):
|
|
with pytest.raises(ValueError):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").limit(0).select(
|
|
["id", "vector"]
|
|
).to_list()
|
|
|
|
with pytest.raises(ValueError):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").limit(None).select(
|
|
["id", "vector"]
|
|
).to_list()
|
|
|
|
|
|
def test_query_builder_batches(table):
|
|
rs = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.limit(2)
|
|
.select(["id", "vector"])
|
|
.to_batches(1)
|
|
)
|
|
rs_list = []
|
|
for item in rs:
|
|
rs_list.append(item)
|
|
assert isinstance(item, pa.RecordBatch)
|
|
assert len(rs_list) == 2
|
|
assert len(rs_list[0]["id"]) == 1
|
|
assert all(rs_list[0].to_pandas()["vector"][0] == [1.0, 2.0])
|
|
assert rs_list[0].to_pandas()["id"][0] == 1
|
|
assert all(rs_list[1].to_pandas()["vector"][0] == [3.0, 4.0])
|
|
assert rs_list[1].to_pandas()["id"][0] == 2
|
|
|
|
rs = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.limit(2)
|
|
.select(["id", "vector"])
|
|
.to_batches(2)
|
|
)
|
|
rs_list = []
|
|
for item in rs:
|
|
rs_list.append(item)
|
|
assert isinstance(item, pa.RecordBatch)
|
|
assert len(rs_list) == 1
|
|
assert len(rs_list[0]["id"]) == 2
|
|
rs_list = rs_list[0].to_pandas()
|
|
assert rs_list["id"][0] == 1
|
|
assert rs_list["id"][1] == 2
|
|
|
|
|
|
def test_batch_vector_query_shares_filtered_flat_scan(table):
|
|
query = (
|
|
table.search([[1.0, 2.0], [3.0, 4.0]])
|
|
.where("id > 0", prefilter=True)
|
|
.limit(1)
|
|
.select(["id"])
|
|
)
|
|
|
|
plan = query.explain_plan(verbose=True)
|
|
assert "KNNVectorDistance: queries=2" in plan
|
|
assert "UnionExec" not in plan
|
|
|
|
results = query.to_arrow()
|
|
assert len(results) == 2
|
|
assert results["query_index"].to_pylist() == [0, 1]
|
|
|
|
|
|
def test_dynamic_projection(table):
|
|
rs = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.limit(1)
|
|
.select({"id": "id", "id2": "id * 2"})
|
|
.to_list()
|
|
)
|
|
assert rs[0]["id"] == 1
|
|
assert rs[0]["id2"] == 2
|
|
|
|
|
|
def test_query_builder_with_filter(table):
|
|
rs = LanceVectorQueryBuilder(table, [0, 0], "vector").where("id = 2").to_list()
|
|
assert rs[0]["id"] == 2
|
|
assert all(np.array(rs[0]["vector"]) == [3, 4])
|
|
|
|
|
|
@pytest.mark.parametrize("query_type", ["vector", "hybrid"])
|
|
@pytest.mark.parametrize("nprobes", [0, -1])
|
|
def test_nprobes_nonpositive_sync(table, query_type, nprobes):
|
|
if query_type == "hybrid":
|
|
query = table.search(query_type="hybrid").vector([0, 0]).text("a")
|
|
else:
|
|
query = table.search([0, 0])
|
|
with pytest.raises(
|
|
ValueError, match="^Invalid input, nprobes must be greater than 0$"
|
|
):
|
|
query.nprobes(nprobes)
|
|
|
|
|
|
def test_invalid_nprobes_sync(table):
|
|
with pytest.raises(ValueError, match="minimum_nprobes must be greater than 0"):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").minimum_nprobes(0).to_list()
|
|
with pytest.raises(
|
|
ValueError,
|
|
match="maximum_nprobes must be greater than or equal to minimum_nprobes",
|
|
):
|
|
(
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.minimum_nprobes(10)
|
|
.maximum_nprobes(5)
|
|
.to_list()
|
|
)
|
|
with pytest.raises(
|
|
ValueError,
|
|
match="maximum_nprobes must be greater than or equal to minimum_nprobes",
|
|
):
|
|
(
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.maximum_nprobes(5)
|
|
.minimum_nprobes(100)
|
|
.to_list()
|
|
)
|
|
|
|
|
|
def test_nprobes_works_sync(table):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").nprobes(30).to_list()
|
|
|
|
|
|
def test_nprobes_min_max_works_sync(table):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").minimum_nprobes(2).maximum_nprobes(
|
|
4
|
|
).to_list()
|
|
|
|
|
|
def test_multiple_nprobes_calls_works_sync(table):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").nprobes(30).maximum_nprobes(
|
|
20
|
|
).minimum_nprobes(20).to_list()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("hybrid", [False, True])
|
|
async def test_nprobes_zero_async(table_async: AsyncTable, hybrid):
|
|
query = table_async.query().nearest_to([0, 0])
|
|
if hybrid:
|
|
query = query.nearest_to_text("dog")
|
|
with pytest.raises(
|
|
ValueError, match="^Invalid input, nprobes must be greater than 0$"
|
|
):
|
|
query.nprobes(0)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_invalid_nprobes_async(table_async: AsyncTable):
|
|
with pytest.raises(ValueError, match="minimum_nprobes must be greater than 0"):
|
|
await table_async.vector_search([0, 0]).minimum_nprobes(0).to_list()
|
|
with pytest.raises(
|
|
ValueError,
|
|
match="maximum_nprobes must be greater than or equal to minimum_nprobes",
|
|
):
|
|
await (
|
|
table_async.vector_search([0, 0])
|
|
.minimum_nprobes(10)
|
|
.maximum_nprobes(5)
|
|
.to_list()
|
|
)
|
|
with pytest.raises(
|
|
ValueError,
|
|
match="minimum_nprobes must be less than or equal to maximum_nprobes",
|
|
):
|
|
await (
|
|
table_async.vector_search([0, 0])
|
|
.maximum_nprobes(5)
|
|
.minimum_nprobes(100)
|
|
.to_list()
|
|
)
|
|
|
|
|
|
def test_approx_mode_works_sync(table):
|
|
for mode in ["fast", "normal", "accurate"]:
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode(mode).to_list()
|
|
|
|
|
|
def test_invalid_approx_mode_sync(table):
|
|
with pytest.raises(ValueError, match="approx_mode must be one of"):
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode("turbo").to_list()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approx_mode_works_async(table_async: AsyncTable):
|
|
for mode in ["fast", "normal", "accurate"]:
|
|
await table_async.vector_search([0, 0]).approx_mode(mode).to_list()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_invalid_approx_mode_async(table_async: AsyncTable):
|
|
with pytest.raises(ValueError, match="approx_mode must be one of"):
|
|
table_async.vector_search([0, 0]).approx_mode("turbo")
|
|
|
|
|
|
def test_query_builder_with_prefilter(table):
|
|
df = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.where("id = 2", prefilter=True)
|
|
.limit(1)
|
|
.to_pandas()
|
|
)
|
|
assert df["id"].values[0] == 2
|
|
assert all(df["vector"].values[0] == [3, 4])
|
|
|
|
df = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.where("id = 2", prefilter=False)
|
|
.limit(1)
|
|
.to_pandas()
|
|
)
|
|
assert len(df) == 0
|
|
|
|
# ensure the default prefilter = True
|
|
df = (
|
|
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
.where("id = 2")
|
|
.limit(1)
|
|
.to_pandas()
|
|
)
|
|
assert df["id"].values[0] == 2
|
|
assert all(df["vector"].values[0] == [3, 4])
|
|
|
|
|
|
def test_query_builder_with_metric(table):
|
|
query = [4, 8]
|
|
vector_column_name = "vector"
|
|
df_default = LanceVectorQueryBuilder(table, query, vector_column_name).to_pandas()
|
|
df_l2 = (
|
|
LanceVectorQueryBuilder(table, query, vector_column_name)
|
|
.distance_type("l2")
|
|
.to_pandas()
|
|
)
|
|
tm.assert_frame_equal(df_default, df_l2)
|
|
|
|
df_cosine = (
|
|
LanceVectorQueryBuilder(table, query, vector_column_name)
|
|
.distance_type("cosine")
|
|
.limit(1)
|
|
.to_pandas()
|
|
)
|
|
assert df_cosine._distance[0] == pytest.approx(
|
|
cosine_distance(query, df_cosine.vector[0]),
|
|
abs=1e-6,
|
|
)
|
|
assert 0 <= df_cosine._distance[0] <= 1
|
|
|
|
|
|
def test_query_builder_with_different_vector_column():
|
|
table = mock.MagicMock(spec=LanceTable)
|
|
query = [4, 8]
|
|
vector_column_name = "foo_vector"
|
|
builder = (
|
|
LanceVectorQueryBuilder(table, query, vector_column_name)
|
|
.distance_type("cosine")
|
|
.where("b < 10")
|
|
.select(["b"])
|
|
.limit(2)
|
|
)
|
|
ds = mock.Mock()
|
|
table.to_lance.return_value = ds
|
|
builder.to_arrow()
|
|
expected = Query(
|
|
vector=query,
|
|
filter="b < 10",
|
|
limit=2,
|
|
distance_type="cosine",
|
|
columns=["b"],
|
|
vector_column="foo_vector",
|
|
)
|
|
expected._blob_row_id_prepared = True
|
|
table._execute_arrow.assert_called_once_with(expected, timeout=None)
|
|
|
|
|
|
def cosine_distance(vec1, vec2):
|
|
return 1 - np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
|
|
|
|
|
|
async def check_query(
|
|
query: AsyncQueryBase, *, expected_num_rows=None, expected_columns=None
|
|
):
|
|
num_rows = 0
|
|
results = await query.to_batches()
|
|
async for batch in results:
|
|
if expected_columns is not None:
|
|
assert batch.schema.names == expected_columns
|
|
num_rows += batch.num_rows
|
|
if expected_num_rows is not None:
|
|
assert num_rows == expected_num_rows
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_async(table_async: AsyncTable):
|
|
await check_query(
|
|
table_async.query(),
|
|
expected_num_rows=2,
|
|
expected_columns=["vector", "id", "str_field", "float_field", "text"],
|
|
)
|
|
await check_query(table_async.query().where("id = 2"), expected_num_rows=1)
|
|
await check_query(
|
|
table_async.query().select(["id", "vector"]), expected_columns=["id", "vector"]
|
|
)
|
|
await check_query(
|
|
table_async.query().select({"foo": "id", "bar": "id + 1"}),
|
|
expected_columns=["foo", "bar"],
|
|
)
|
|
|
|
await check_query(table_async.query().limit(1), expected_num_rows=1)
|
|
await check_query(table_async.query().offset(1), expected_num_rows=1)
|
|
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])), expected_num_rows=2
|
|
)
|
|
# Support different types of inputs for the vector query
|
|
for vector_query in [
|
|
[1, 2],
|
|
[1.0, 2.0],
|
|
np.array([1, 2]),
|
|
(1, 2),
|
|
]:
|
|
await check_query(
|
|
table_async.query().nearest_to(vector_query), expected_num_rows=2
|
|
)
|
|
|
|
# No easy way to check these vector query parameters are doing what they say. We
|
|
# just check that they don't raise exceptions and assume this is tested at a lower
|
|
# level.
|
|
await check_query(
|
|
table_async.query().where("id = 2").nearest_to(pa.array([1, 2])).postfilter(),
|
|
expected_num_rows=1,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).refine_factor(1),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).nprobes(10),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).minimum_nprobes(10),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).maximum_nprobes(30),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query()
|
|
.nearest_to(pa.array([1, 2]))
|
|
.minimum_nprobes(10)
|
|
.maximum_nprobes(20),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).bypass_vector_index(),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).distance_type("dot"),
|
|
expected_num_rows=2,
|
|
)
|
|
await check_query(
|
|
table_async.query().nearest_to(pa.array([1, 2])).distance_type("DoT"),
|
|
expected_num_rows=2,
|
|
)
|
|
|
|
# Make sure we can use a vector query as a base query (e.g. call limit on it)
|
|
# Also make sure `vector_search` works
|
|
await check_query(table_async.vector_search([1, 2]).limit(1), expected_num_rows=1)
|
|
|
|
# Also check an empty query
|
|
await check_query(table_async.query().where("id < 0"), expected_num_rows=0)
|
|
|
|
# with row id
|
|
await check_query(
|
|
table_async.query().select(["id", "vector"]).with_row_id(),
|
|
expected_columns=["id", "vector", "_rowid"],
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.slow
|
|
async def test_query_reranked_async(table_async: AsyncTable):
|
|
# CrossEncoderReranker requires torch
|
|
if find_spec("torch") is None:
|
|
pytest.skip("torch not installed")
|
|
|
|
# FTS with rerank
|
|
await table_async.create_index("text", config=FTS(with_position=False))
|
|
await check_query(
|
|
table_async.query().nearest_to_text("dog").rerank(CrossEncoderReranker()),
|
|
expected_num_rows=1,
|
|
)
|
|
|
|
# Vector query with rerank
|
|
await check_query(
|
|
table_async.vector_search([1, 2]).rerank(
|
|
CrossEncoderReranker(), query_string="dog"
|
|
),
|
|
expected_num_rows=2,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_arrow_async(table_async: AsyncTable):
|
|
table = await table_async.to_arrow()
|
|
assert table.num_rows == 2
|
|
assert table.num_columns == 5
|
|
|
|
table = await table_async.query().to_arrow()
|
|
assert table.num_rows == 2
|
|
assert table.num_columns == 5
|
|
|
|
table = await table_async.query().where("id < 0").to_arrow()
|
|
assert table.num_rows == 0
|
|
assert table.num_columns == 5
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_pandas_async(table_async: AsyncTable):
|
|
df = await table_async.to_pandas()
|
|
assert df.shape == (2, 5)
|
|
|
|
df = await table_async.query().to_pandas()
|
|
assert df.shape == (2, 5)
|
|
|
|
df = await table_async.query().where("id < 0").to_pandas()
|
|
assert df.shape == (0, 5)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_pandas_flatten_async(table_struct_async: AsyncTable):
|
|
df = await table_struct_async.query().to_pandas()
|
|
assert df.shape == (2, 2)
|
|
|
|
df = await table_struct_async.query().to_pandas(flatten=True)
|
|
assert df.shape == (2, 4)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_polars_async(table_async: AsyncTable):
|
|
schema = await table_async.schema()
|
|
num_columns = len(schema.names)
|
|
df = await table_async.query().to_polars()
|
|
assert df.shape == (2, num_columns)
|
|
|
|
df = await table_async.query().where("id < 0").to_polars()
|
|
assert df.shape == (0, num_columns)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("search_kwargs", [{}, {"query": None}])
|
|
@pytest.mark.parametrize("with_vector", [False, True])
|
|
async def test_async_search_without_query(mem_db_async, search_kwargs, with_vector):
|
|
data = [{"id": i} for i in range(10)]
|
|
if with_vector:
|
|
for row in data:
|
|
row["vector"] = [float(row["id"]), 1.0]
|
|
table = await mem_db_async.create_table("test", data)
|
|
|
|
query = await table.search(**search_kwargs)
|
|
assert isinstance(query, AsyncQuery)
|
|
assert await query.limit(3).to_arrow() == await table.query().limit(3).to_arrow()
|
|
|
|
query = await table.search(**search_kwargs)
|
|
assert await query.where("id >= 8").select(["id"]).limit(3).to_list() == [
|
|
{"id": 8},
|
|
{"id": 9},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_none_query(table_async: AsyncTable):
|
|
with pytest.raises(ValueError):
|
|
await table_async.query().nearest_to(None).to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fast_search_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
vectors = pa.FixedShapeTensorArray.from_numpy_ndarray(
|
|
np.random.rand(256, 32)
|
|
).storage
|
|
table = await db.create_table("test", pa.table({"vector": vectors}))
|
|
await table.create_index(
|
|
"vector", config=IvfPq(num_partitions=1, num_sub_vectors=1)
|
|
)
|
|
await table.add(pa.table({"vector": vectors}))
|
|
|
|
q = [1.0] * 32
|
|
plan = await table.query().nearest_to(q).explain_plan(True)
|
|
assert "LanceScan" in plan
|
|
plan = await table.query().nearest_to(q).fast_search().explain_plan(True)
|
|
assert "LanceScan" not in plan
|
|
|
|
|
|
def test_analyze_plan(table):
|
|
q = LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
res = q.analyze_plan()
|
|
assert "AnalyzeExec" in res
|
|
assert "metrics=" in res
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_analyze_plan_async(table_async: AsyncTable):
|
|
res = await table_async.query().nearest_to(pa.array([1, 2])).analyze_plan()
|
|
assert "AnalyzeExec" in res
|
|
assert "metrics=" in res
|
|
|
|
|
|
def test_explain_plan(table):
|
|
q = LanceVectorQueryBuilder(table, [0, 0], "vector")
|
|
plan = q.explain_plan(verbose=True)
|
|
assert "KNN" in plan
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_explain_plan_async(table_async: AsyncTable):
|
|
plan = await table_async.query().nearest_to(pa.array([1, 2])).explain_plan(True)
|
|
assert "KNN" in plan
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_explain_plan_fts(table_async: AsyncTable):
|
|
"""Test explain plan for FTS queries"""
|
|
# Create FTS index
|
|
from lancedb.index import FTS
|
|
|
|
await table_async.create_index("text", config=FTS())
|
|
|
|
# Test pure FTS query
|
|
query = await table_async.search("dog", query_type="fts", fts_columns="text")
|
|
plan = await query.explain_plan()
|
|
# Should show FTS details (issue #2465 is now fixed)
|
|
assert "MatchQuery: column=text, query=[dog]" in plan
|
|
assert "GlobalLimitExec" in plan # Default limit
|
|
|
|
# Test FTS query with limit
|
|
query_with_limit = await table_async.search(
|
|
"dog", query_type="fts", fts_columns="text"
|
|
)
|
|
plan_with_limit = await query_with_limit.limit(1).explain_plan()
|
|
assert "MatchQuery: column=text, query=[dog]" in plan_with_limit
|
|
assert "GlobalLimitExec: skip=0, fetch=1" in plan_with_limit
|
|
|
|
# Test FTS query with offset and limit
|
|
query_with_offset = await table_async.search(
|
|
"dog", query_type="fts", fts_columns="text"
|
|
)
|
|
plan_with_offset = await query_with_offset.offset(1).limit(1).explain_plan()
|
|
assert "MatchQuery: column=text, query=[dog]" in plan_with_offset
|
|
assert "GlobalLimitExec: skip=1, fetch=1" in plan_with_offset
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_explain_plan_vector_with_limit_offset(table_async: AsyncTable):
|
|
"""Test explain plan for vector queries with limit and offset"""
|
|
# Test vector query with limit
|
|
plan_with_limit = await (
|
|
table_async.query().nearest_to(pa.array([1, 2])).limit(1).explain_plan()
|
|
)
|
|
assert "KNN" in plan_with_limit
|
|
assert "GlobalLimitExec: skip=0, fetch=1" in plan_with_limit
|
|
|
|
# Test vector query with offset and limit
|
|
plan_with_offset = await (
|
|
table_async.query()
|
|
.nearest_to(pa.array([1, 2]))
|
|
.offset(1)
|
|
.limit(1)
|
|
.explain_plan()
|
|
)
|
|
assert "KNN" in plan_with_offset
|
|
assert "GlobalLimitExec: skip=1, fetch=1" in plan_with_offset
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_explain_plan_with_filters(table_async: AsyncTable):
|
|
"""Test explain plan for queries with filters"""
|
|
# Test vector query with filter
|
|
plan_with_filter = await (
|
|
table_async.query().nearest_to(pa.array([1, 2])).where("id = 1").explain_plan()
|
|
)
|
|
assert "KNN" in plan_with_filter
|
|
assert "LanceRead" in plan_with_filter
|
|
|
|
# Test FTS query with filter
|
|
from lancedb.index import FTS
|
|
|
|
await table_async.create_index("text", config=FTS())
|
|
query_fts_filter = await table_async.search(
|
|
"dog", query_type="fts", fts_columns="text"
|
|
)
|
|
plan_fts_filter = await query_fts_filter.where("id = 1").explain_plan()
|
|
assert "MatchQuery: column=text, query=[dog]" in plan_fts_filter
|
|
assert "LanceRead" in plan_fts_filter
|
|
assert "full_filter=id = Int64(1)" in plan_fts_filter # Should show filter details
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_camelcase_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
table = await db.create_table("test", pa.table({"camelCase": pa.array([1, 2])}))
|
|
|
|
result = await table.query().select(["camelCase"]).to_arrow()
|
|
assert result == pa.table({"camelCase": pa.array([1, 2])})
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_to_list_async(table_async: AsyncTable):
|
|
list = await table_async.query().to_list()
|
|
assert len(list) == 2
|
|
assert list[0]["vector"] == [1, 2]
|
|
assert list[1]["vector"] == [3, 4]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_with_f16(tmp_path: Path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
f16_arr = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16)
|
|
|
|
df = pa.table(
|
|
{
|
|
"vector": pa.FixedSizeListArray.from_arrays(f16_arr, 2),
|
|
"id": pa.array([1, 2]),
|
|
}
|
|
)
|
|
tbl = await db.create_table("test", df)
|
|
results = await tbl.vector_search([np.float16(1), np.float16(2)]).to_pandas()
|
|
assert len(results) == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_search_auto(mem_db_async: AsyncConnection):
|
|
nrows = 1000
|
|
data = pa.table(
|
|
{
|
|
"text": [str(i) for i in range(nrows)],
|
|
}
|
|
)
|
|
|
|
@register("test2")
|
|
class TestEmbedding(TextEmbeddingFunction):
|
|
def ndims(self):
|
|
return 4
|
|
|
|
def generate_embeddings(
|
|
self, texts: Union[List[str], np.ndarray]
|
|
) -> List[np.array]:
|
|
embeddings = []
|
|
for text in texts:
|
|
vec = np.array([float(text) / 1000] * self.ndims())
|
|
embeddings.append(vec)
|
|
return embeddings
|
|
|
|
registry = get_registry()
|
|
func = registry.get("test2").create()
|
|
|
|
class TestModel(LanceModel):
|
|
text: str = func.SourceField()
|
|
vector: Vector(func.ndims()) = func.VectorField()
|
|
|
|
tbl = await mem_db_async.create_table("test", data, schema=TestModel)
|
|
|
|
funcs = await tbl.embedding_functions()
|
|
assert len(funcs) == 1
|
|
|
|
# No FTS or vector index
|
|
# Search for vector -> vector query
|
|
q = [0.1] * 4
|
|
query = await tbl.search(q)
|
|
assert isinstance(query, AsyncVectorQuery)
|
|
|
|
# Search for string -> vector query
|
|
query = await tbl.search("0.1")
|
|
assert isinstance(query, AsyncVectorQuery)
|
|
|
|
await tbl.create_index("text", config=FTS())
|
|
|
|
query = await tbl.search("0.1")
|
|
assert isinstance(query, AsyncHybridQuery)
|
|
|
|
data_with_vecs = await tbl.to_arrow()
|
|
data_with_vecs = data_with_vecs.replace_schema_metadata(None)
|
|
tbl2 = await mem_db_async.create_table("test2", data_with_vecs)
|
|
with pytest.raises(
|
|
Exception,
|
|
match=(
|
|
"Cannot perform full text search unless an INVERTED index has been created"
|
|
),
|
|
):
|
|
query = await (await tbl2.search("0.1")).to_arrow()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_search_specified(mem_db_async: AsyncConnection):
|
|
nrows, ndims = 1000, 16
|
|
data = pa.table(
|
|
{
|
|
"text": [str(i) for i in range(nrows)],
|
|
"vector": pa.FixedSizeListArray.from_arrays(
|
|
pc.random(nrows * ndims).cast(pa.float32()), ndims
|
|
),
|
|
}
|
|
)
|
|
table = await mem_db_async.create_table("test", data)
|
|
await table.create_index("text", config=FTS())
|
|
|
|
# Validate that specifying fts, vector or hybrid gets the right query.
|
|
q = [0.1] * ndims
|
|
query = await table.search(q, query_type="vector")
|
|
assert isinstance(query, AsyncVectorQuery)
|
|
|
|
query = await table.search("0.1", query_type="fts")
|
|
assert isinstance(query, AsyncFTSQuery)
|
|
|
|
with pytest.raises(ValueError, match="Unknown query type: 'foo'"):
|
|
await table.search("0.1", query_type="foo")
|
|
|
|
with pytest.raises(
|
|
ValueError, match="Column 'vector' has no registered embedding function"
|
|
) as e:
|
|
await table.search("0.1", query_type="vector")
|
|
|
|
assert "No embedding functions are registered for any columns" in exception_output(
|
|
e
|
|
)
|
|
|
|
|
|
# Helper method used in the following tests. Looks at the simple python object `q` and
|
|
# checks that the properties match the expected values in kwargs.
|
|
def check_set_props(q, **kwargs):
|
|
for k in dict(q):
|
|
if not k.startswith("_"):
|
|
if k in kwargs:
|
|
assert kwargs[k] == getattr(q, k), (
|
|
f"{k} should be {kwargs[k]} but is {getattr(q, k)}"
|
|
)
|
|
else:
|
|
assert getattr(q, k) is None, f"{k} should be None"
|
|
|
|
|
|
def test_query_serialization_sync(table: lancedb.table.Table):
|
|
# Simple queries
|
|
q = table.search().where("id = 1").limit(500).offset(10).to_query_object()
|
|
check_set_props(q, limit=500, offset=10, filter="id = 1")
|
|
|
|
q = table.search().select(["id", "vector"]).to_query_object()
|
|
check_set_props(q, columns=["id", "vector"])
|
|
|
|
q = table.search().with_row_id(True).to_query_object()
|
|
check_set_props(q, with_row_id=True)
|
|
|
|
# Vector queries
|
|
q = table.search([5.0, 6.0]).limit(10).to_query_object()
|
|
check_set_props(q, limit=10, vector_column="vector", vector=[5.0, 6.0])
|
|
|
|
q = table.search([5.0, 6.0]).to_query_object()
|
|
check_set_props(q, vector_column="vector", vector=[5.0, 6.0])
|
|
|
|
q = (
|
|
table.search([5.0, 6.0])
|
|
.limit(10)
|
|
.where("id = 1", prefilter=False)
|
|
.to_query_object()
|
|
)
|
|
check_set_props(
|
|
q,
|
|
limit=10,
|
|
vector_column="vector",
|
|
filter="id = 1",
|
|
postfilter=True,
|
|
vector=[5.0, 6.0],
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).nprobes(10).refine_factor(5).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
nprobes=10,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
refine_factor=5,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).minimum_nprobes(10).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
minimum_nprobes=10,
|
|
maximum_nprobes=None,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).nprobes(50).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
nprobes=50,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).minimum_nprobes(5).nprobes(50).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
nprobes=50,
|
|
minimum_nprobes=5,
|
|
maximum_nprobes=None,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).maximum_nprobes(10).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
maximum_nprobes=10,
|
|
minimum_nprobes=None,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).nprobes(5).maximum_nprobes(0).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector_column="vector",
|
|
vector=[5.0, 6.0],
|
|
nprobes=5,
|
|
maximum_nprobes=0,
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).distance_range(0.0, 1.0).to_query_object()
|
|
check_set_props(
|
|
q, vector_column="vector", vector=[5.0, 6.0], lower_bound=0.0, upper_bound=1.0
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).distance_type("cosine").to_query_object()
|
|
check_set_props(
|
|
q, distance_type="cosine", vector_column="vector", vector=[5.0, 6.0]
|
|
)
|
|
|
|
q = table.search([5.0, 6.0]).ef(7).to_query_object()
|
|
check_set_props(q, ef=7, vector_column="vector", vector=[5.0, 6.0])
|
|
|
|
q = table.search([5.0, 6.0]).approx_mode("fast").to_query_object()
|
|
check_set_props(q, approx_mode="fast", vector_column="vector", vector=[5.0, 6.0])
|
|
|
|
q = table.search([5.0, 6.0]).bypass_vector_index().to_query_object()
|
|
check_set_props(
|
|
q, bypass_vector_index=True, vector_column="vector", vector=[5.0, 6.0]
|
|
)
|
|
|
|
# FTS queries
|
|
q = table.search("foo").limit(10).to_query_object()
|
|
check_set_props(
|
|
q, limit=10, full_text_query=FullTextSearchQuery(columns=[], query="foo")
|
|
)
|
|
|
|
q = table.search("foo", query_type="fts").to_query_object()
|
|
check_set_props(q, full_text_query=FullTextSearchQuery(columns=[], query="foo"))
|
|
|
|
|
|
@pytest.mark.parametrize("fts", [False, True])
|
|
def test_ordered_results_sync(tmp_db, fts):
|
|
table = tmp_db.create_table(
|
|
"search_order",
|
|
pa.table(
|
|
{
|
|
"id": [0, 1, 2, 3],
|
|
"vector": pa.array(
|
|
[[3], [1], [2], [0]], type=pa.list_(pa.float32(), 1)
|
|
),
|
|
"text": ["cat dog bird", "dog", "robin", "dog dog"],
|
|
}
|
|
),
|
|
)
|
|
if fts:
|
|
table.create_index("text", config=FTS())
|
|
search = table.search("dog", query_type="fts")
|
|
else:
|
|
search = table.search([0.0])
|
|
search = search.limit(2)
|
|
ranked = search.to_arrow().sort_by("id")
|
|
assert ranked["id"].to_pylist() == [1, 3]
|
|
search.ordered_results(False)
|
|
assert search.to_query_object().ordered is False
|
|
assert search.to_arrow().sort_by("id").equals(ranked)
|
|
assert search.ordered_results(True).to_query_object().ordered is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("fts", [False, True])
|
|
async def test_ordered_results_async(table_async, fts):
|
|
if fts:
|
|
await table_async.create_index("text", config=FTS())
|
|
search = table_async.query().nearest_to_text("dog")
|
|
else:
|
|
search = table_async.vector_search([0.0, 0.0])
|
|
search = search.limit(2)
|
|
ranked = (await search.to_arrow()).sort_by("id")
|
|
assert ranked.num_rows > 0
|
|
search.ordered_results(False)
|
|
assert search.to_query_object().ordered is False
|
|
assert (await search.to_arrow()).sort_by("id").equals(ranked)
|
|
if fts:
|
|
search.rerank(RRFReranker())
|
|
else:
|
|
search.rerank(RRFReranker(), query_string="dog")
|
|
assert search.to_query_object().ordered is None
|
|
assert search.ordered_results(False).to_query_object().ordered is None
|
|
|
|
if fts:
|
|
text_query = table_async.query().nearest_to_text("dog").ordered_results(False)
|
|
hybrid = text_query.nearest_to([0.0, 0.0])
|
|
else:
|
|
vector_query = table_async.vector_search([0.0, 0.0]).ordered_results(False)
|
|
hybrid = vector_query.nearest_to_text("dog")
|
|
fts_leg, vector_leg, _, _ = await hybrid._create_child_queries()
|
|
assert fts_leg.to_query_object().ordered is None
|
|
assert vector_leg.to_query_object().ordered is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("query_type", ["plain", "fts", "vector"])
|
|
@pytest.mark.parametrize("fast_search", [False, True])
|
|
@pytest.mark.parametrize("postfilter", [False, True])
|
|
async def test_query_serialization_async_search_options(
|
|
table_async: AsyncTable, query_type, fast_search, postfilter
|
|
):
|
|
query = table_async.query().where("id = 1")
|
|
if query_type == "fts":
|
|
query = query.nearest_to_text(MatchQuery("dog", "text"))
|
|
elif query_type == "vector":
|
|
query = query.nearest_to([1.0, 2.0])
|
|
if fast_search:
|
|
query = query.fast_search()
|
|
if postfilter:
|
|
query = query.postfilter()
|
|
|
|
serialized = query.to_query_object()
|
|
assert serialized.fast_search is (True if fast_search else None)
|
|
default_postfilter = False if query_type == "vector" else None
|
|
assert serialized.postfilter is (True if postfilter else default_postfilter)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("fast_search", [False, True])
|
|
async def test_query_serialization_async_fast_search_execution(
|
|
table_async, fast_search
|
|
):
|
|
await table_async.create_index("text", config=FTS())
|
|
await table_async.add(
|
|
[
|
|
{
|
|
"id": 3,
|
|
"vector": [5.0, 6.0],
|
|
"str_field": "c",
|
|
"float_field": 3.0,
|
|
"text": "unindexed dog",
|
|
}
|
|
]
|
|
)
|
|
query = table_async.query().nearest_to_text(MatchQuery("unindexed", "text"))
|
|
if fast_search:
|
|
query = query.fast_search()
|
|
|
|
expected_ids = [] if fast_search else [3]
|
|
assert [row["id"] for row in await query.to_list()] == expected_ids
|
|
restored = table_async._sync_query_to_async(query.to_query_object())
|
|
assert [row["id"] for row in await restored.to_list()] == expected_ids
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_serialization_async(table_async: AsyncTable):
|
|
# Simple queries
|
|
q = table_async.query().where("id = 1").limit(500).offset(10).to_query_object()
|
|
check_set_props(q, limit=500, offset=10, filter="id = 1", with_row_id=False)
|
|
|
|
q = table_async.query().select(["id", "vector"]).to_query_object()
|
|
check_set_props(q, columns=["id", "vector"], with_row_id=False)
|
|
|
|
q = table_async.query().with_row_id().to_query_object()
|
|
check_set_props(q, with_row_id=True)
|
|
|
|
sample_vector = [pa.array([5.0, 6.0], type=pa.float32())]
|
|
|
|
# Vector queries
|
|
q = (await table_async.search([5.0, 6.0])).limit(10).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
limit=10,
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).nprobes(50).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
nprobes=50,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (
|
|
(await table_async.search([5.0, 6.0]))
|
|
.limit(10)
|
|
.where("id = 1")
|
|
.postfilter()
|
|
.to_query_object()
|
|
)
|
|
check_set_props(
|
|
q,
|
|
limit=10,
|
|
filter="id = 1",
|
|
postfilter=True,
|
|
vector=sample_vector,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
)
|
|
|
|
q = (
|
|
(await table_async.search([5.0, 6.0]))
|
|
.nprobes(10)
|
|
.refine_factor(5)
|
|
.to_query_object()
|
|
)
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
nprobes=10,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
refine_factor=5,
|
|
postfilter=False,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).minimum_nprobes(5).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
minimum_nprobes=5,
|
|
maximum_nprobes=None,
|
|
postfilter=False,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (
|
|
(await table_async.search([5.0, 6.0]))
|
|
.nprobes(5)
|
|
.maximum_nprobes(0)
|
|
.to_query_object()
|
|
)
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
nprobes=5,
|
|
maximum_nprobes=0,
|
|
postfilter=False,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (
|
|
(await table_async.search([5.0, 6.0]))
|
|
.distance_range(0.0, 1.0)
|
|
.to_query_object()
|
|
)
|
|
check_set_props(
|
|
q,
|
|
vector=sample_vector,
|
|
lower_bound=0.0,
|
|
upper_bound=1.0,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).distance_type("cosine").to_query_object()
|
|
check_set_props(
|
|
q,
|
|
distance_type="cosine",
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).ef(7).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
ef=7,
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).approx_mode("fast").to_query_object()
|
|
check_set_props(
|
|
q,
|
|
approx_mode="fast",
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
bypass_vector_index=False,
|
|
limit=10,
|
|
)
|
|
|
|
q = (await table_async.search([5.0, 6.0])).bypass_vector_index().to_query_object()
|
|
check_set_props(
|
|
q,
|
|
bypass_vector_index=True,
|
|
vector=sample_vector,
|
|
postfilter=False,
|
|
minimum_nprobes=None,
|
|
maximum_nprobes=None,
|
|
with_row_id=False,
|
|
limit=10,
|
|
)
|
|
|
|
# FTS queries
|
|
match_query = MatchQuery("foo", "text")
|
|
q = (await table_async.search(match_query)).limit(10).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
limit=10,
|
|
full_text_query=FullTextSearchQuery(columns=None, query=match_query),
|
|
with_row_id=False,
|
|
)
|
|
|
|
q = (await table_async.search(match_query)).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
full_text_query=FullTextSearchQuery(columns=None, query=match_query),
|
|
with_row_id=False,
|
|
)
|
|
|
|
phrase_query = PhraseQuery("foo", "text", slop=1)
|
|
q = (await table_async.search(phrase_query)).to_query_object()
|
|
check_set_props(
|
|
q,
|
|
full_text_query=FullTextSearchQuery(columns=None, query=phrase_query),
|
|
with_row_id=False,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hybrid_query_serialization_async(table_async: AsyncTable):
|
|
q = (
|
|
table_async.query()
|
|
.nearest_to([5.0, 6.0])
|
|
.nearest_to_text(MatchQuery("dog", "text"))
|
|
.ef(7)
|
|
.approx_mode("fast")
|
|
.to_query_object()
|
|
)
|
|
assert q.ef == 7
|
|
assert q.approx_mode == "fast"
|
|
|
|
|
|
def test_query_schema(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
tbl = db.create_table(
|
|
"test",
|
|
pa.table(
|
|
{
|
|
"a": [1, 2, 3],
|
|
"text": ["a", "b", "c"],
|
|
"vec": pa.array(
|
|
[[1, 2], [3, 4], [5, 6]], pa.list_(pa.float32(), list_size=2)
|
|
),
|
|
}
|
|
),
|
|
)
|
|
|
|
assert tbl.search(None).output_schema() == pa.schema(
|
|
{
|
|
"a": pa.int64(),
|
|
"text": pa.string(),
|
|
"vec": pa.list_(pa.float32(), list_size=2),
|
|
}
|
|
)
|
|
assert tbl.search(None).select({"bl": "a * 2"}).output_schema() == pa.schema(
|
|
{"bl": pa.int64()}
|
|
)
|
|
assert tbl.search([1, 2]).select(["a"]).output_schema() == pa.schema(
|
|
{"a": pa.int64(), "_distance": pa.float32()}
|
|
)
|
|
assert tbl.search("blah").select(["a"]).output_schema() == pa.schema(
|
|
{"a": pa.int64()}
|
|
)
|
|
assert tbl.take_offsets([0]).select(["text"]).output_schema() == pa.schema(
|
|
{"text": pa.string()}
|
|
)
|
|
|
|
|
|
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table(
|
|
"test",
|
|
pa.table(
|
|
{
|
|
"id": [1, 2, 3],
|
|
"vector": pa.array(
|
|
[[1, 2], [3, 4], [5, 6]],
|
|
pa.list_(pa.float32(), list_size=2),
|
|
),
|
|
}
|
|
),
|
|
)
|
|
|
|
calls = 0
|
|
original = AsyncTable._schema_sync
|
|
|
|
def counted(self):
|
|
nonlocal calls
|
|
calls += 1
|
|
return original(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
|
|
|
|
table.search().where("id = 1").select(["id"]).to_arrow()
|
|
assert calls <= 1
|
|
|
|
calls = 0
|
|
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
|
|
assert calls <= 1
|
|
|
|
calls = 0
|
|
table.search([1, 2]).limit(1).to_arrow()
|
|
# At most one lookup infers the vector column, one prepares execution.
|
|
assert calls <= 2
|
|
|
|
calls = 0
|
|
table.search().where("id = 1").select(["id"]).to_batches().read_all()
|
|
assert calls <= 1
|
|
|
|
builder = table.search().where("id = 1")
|
|
before = builder.to_arrow()
|
|
assert "extra" not in before.column_names
|
|
assert "image" not in before.column_names
|
|
|
|
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
|
|
calls = 0
|
|
after = builder.to_arrow()
|
|
assert calls <= 1
|
|
assert after["extra"].to_pylist() == [None]
|
|
assert "_lance_row_id" in str(after.schema)
|
|
assert "_rowid" not in after.column_names
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_schema_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
tbl = await db.create_table(
|
|
"test",
|
|
pa.table(
|
|
{
|
|
"a": [1, 2, 3],
|
|
"text": ["a", "b", "c"],
|
|
"vec": pa.array(
|
|
[[1, 2], [3, 4], [5, 6]], pa.list_(pa.float32(), list_size=2)
|
|
),
|
|
}
|
|
),
|
|
)
|
|
|
|
assert await tbl.query().output_schema() == pa.schema(
|
|
{
|
|
"a": pa.int64(),
|
|
"text": pa.string(),
|
|
"vec": pa.list_(pa.float32(), list_size=2),
|
|
}
|
|
)
|
|
assert await tbl.query().select({"bl": "a * 2"}).output_schema() == pa.schema(
|
|
{"bl": pa.int64()}
|
|
)
|
|
assert await tbl.vector_search([1, 2]).select(["a"]).output_schema() == pa.schema(
|
|
{"a": pa.int64(), "_distance": pa.float32()}
|
|
)
|
|
assert await (await tbl.search("blah")).select(["a"]).output_schema() == pa.schema(
|
|
{"a": pa.int64()}
|
|
)
|
|
assert await tbl.take_offsets([0]).select(["text"]).output_schema() == pa.schema(
|
|
{"text": pa.string()}
|
|
)
|
|
|
|
|
|
def test_query_timeout(tmp_path):
|
|
# Use local directory instead of memory:// to add a bit of latency to
|
|
# operations so a timeout of zero will trigger exceptions.
|
|
db = lancedb.connect(tmp_path)
|
|
data = pa.table(
|
|
{
|
|
"text": ["a", "b"],
|
|
"vector": pa.FixedSizeListArray.from_arrays(
|
|
pc.random(4).cast(pa.float32()), 2
|
|
),
|
|
}
|
|
)
|
|
table = db.create_table("test", data)
|
|
table.create_fts_index("text")
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search().where("text = 'a'").to_list(timeout=timedelta(0))
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search([0.0, 0.0]).to_arrow(timeout=timedelta(0))
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search("a", query_type="fts").to_pandas(timeout=timedelta(0))
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search(query_type="hybrid").vector([0.0, 0.0]).text("a").to_arrow(
|
|
timeout=timedelta(0)
|
|
)
|
|
|
|
|
|
def test_take_queries(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
data = pa.table(
|
|
{
|
|
"idx": range(100),
|
|
}
|
|
)
|
|
table = db.create_table("test", data)
|
|
|
|
# Take by offset
|
|
assert list(
|
|
sorted(table.take_offsets([5, 2, 17]).to_pandas()["idx"].to_list())
|
|
) == [
|
|
2,
|
|
5,
|
|
17,
|
|
]
|
|
|
|
# Duplicate offsets are occurrences, not set members. Ordering is unspecified.
|
|
assert sorted(table.take_offsets([5, 2, 5, 17]).to_pandas()["idx"].to_list()) == [
|
|
2,
|
|
5,
|
|
5,
|
|
17,
|
|
]
|
|
|
|
# Converting a take builder to its serializable query representation must
|
|
# retain occurrence metadata and execute with the same multiplicity.
|
|
query = table.take_offsets([5, 2, 5, 17]).select(["idx"]).to_query_object()
|
|
assert query.take_offsets == [5, 2, 5, 17]
|
|
converted = table._execute_query(query).read_all()
|
|
assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17]
|
|
|
|
# Take by row id
|
|
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
|
|
|
|
|
|
def test_take_offsets_preserve_order_sync(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table("test", pa.table({"idx": range(4)}))
|
|
table.add(pa.table({"idx": range(4, 8)}))
|
|
table.delete("idx IN (1, 6)")
|
|
requested = [5, 0, 5, 2, 99, 4, 0]
|
|
expected = [7, 0, 7, 3, 5, 0]
|
|
|
|
actual = (
|
|
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
|
|
)
|
|
assert actual.column_names == ["idx"]
|
|
assert actual["idx"].to_pylist() == expected
|
|
|
|
batches = list(
|
|
table.take_offsets(requested, preserve_order=True)
|
|
.select(["idx"])
|
|
.to_batches(max_batch_length=1)
|
|
)
|
|
assert all(batch.num_rows <= 1 for batch in batches)
|
|
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
|
|
|
# The default path keeps its unspecified-order behavior.
|
|
default = table.take_offsets(requested).select(["idx"]).to_arrow()
|
|
assert sorted(default["idx"].to_pylist()) == sorted(expected)
|
|
|
|
assert table.take_offsets(requested).to_query_object().preserve_order is None
|
|
query = (
|
|
table.take_offsets(requested, preserve_order=True)
|
|
.select(["idx"])
|
|
.to_query_object()
|
|
)
|
|
assert query.preserve_order is True
|
|
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
|
|
|
|
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
|
|
assert empty.num_rows == 0
|
|
assert empty.column_names == ["idx"]
|
|
|
|
query.order_by = [ColumnOrdering(column_name="idx")]
|
|
with pytest.raises(
|
|
ValueError, match="preserve_order cannot be combined with an explicit order_by"
|
|
):
|
|
table._execute_query(query)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_take_offsets_preserve_order_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
table = await db.create_table("test", pa.table({"idx": range(4)}))
|
|
await table.add(pa.table({"idx": range(4, 8)}))
|
|
await table.delete("idx IN (1, 6)")
|
|
requested = [5, 0, 5, 2, 99, 4, 0]
|
|
expected = [7, 0, 7, 3, 5, 0]
|
|
|
|
actual = (
|
|
await table.take_offsets(requested, preserve_order=True)
|
|
.select(["idx"])
|
|
.to_arrow()
|
|
)
|
|
assert actual.column_names == ["idx"]
|
|
assert actual["idx"].to_pylist() == expected
|
|
|
|
reader = (
|
|
await table.take_offsets(requested, preserve_order=True)
|
|
.select(["idx"])
|
|
.to_batches(max_batch_length=1)
|
|
)
|
|
batches = [batch async for batch in reader]
|
|
assert all(batch.num_rows <= 1 for batch in batches)
|
|
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
|
|
|
query = (
|
|
table.take_offsets(requested, preserve_order=True)
|
|
.select(["idx"])
|
|
.to_query_object()
|
|
)
|
|
assert query.preserve_order is True
|
|
|
|
|
|
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
|
|
@pytest.mark.parametrize("empty", [False, True])
|
|
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
|
|
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]}))
|
|
table.add(pa.table({"idx": [2, 3]}))
|
|
rows = table.search().with_row_id(True).to_arrow().to_pylist()
|
|
row_ids = {row["idx"]: row["_rowid"] for row in rows}
|
|
table.delete("idx = 1")
|
|
requested = (
|
|
[] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]]
|
|
)
|
|
take = table.take_row_ids(requested)
|
|
if selection is not None:
|
|
take = take.select(selection)
|
|
actual = take.to_arrow()
|
|
assert actual.num_rows == (0 if empty else 3)
|
|
if selection == {"_rowid": "100 - idx"}:
|
|
assert actual.column_names == ["_rowid"]
|
|
assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100])
|
|
elif selection == []:
|
|
assert actual.num_columns == 0
|
|
else:
|
|
assert actual.column_names == ["idx"]
|
|
assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0])
|
|
query = take.to_query_object()
|
|
assert query.take_row_ids == requested
|
|
assert table._execute_query(query).read_all() == actual
|
|
|
|
|
|
def test_take_queries_with_row_id(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table("test", pa.table({"idx": range(100)}))
|
|
|
|
by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
|
assert "_rowid" in by_row_id.column_names
|
|
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
|
by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
|
assert "_rowid" in by_offset.column_names
|
|
|
|
# The column is opt-in and must stay out of the default projection.
|
|
assert "_rowid" not in table.take_row_ids([5, 2, 17]).to_arrow().column_names
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_take_queries_with_row_id_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
table = await db.create_table("test", pa.table({"idx": range(100)}))
|
|
|
|
by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
|
assert "_rowid" in by_row_id.column_names
|
|
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
|
by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
|
assert "_rowid" in by_offset.column_names
|
|
|
|
default = await table.take_row_ids([5, 2, 17]).to_arrow()
|
|
assert "_rowid" not in default.column_names
|
|
|
|
|
|
def test_take_queries_to_batches(tmp_path):
|
|
# Regression test for the sync take-query path: `to_batches` previously
|
|
# raised ``AttributeError: 'AsyncTakeQuery' object has no attribute
|
|
# 'execute'`` because the inherited ``BaseQueryBuilder.to_batches`` called
|
|
# ``execute`` on the async wrapper instead of the native query.
|
|
db = lancedb.connect(tmp_path)
|
|
data = pa.table({"idx": list(range(100)), "label": [str(i) for i in range(100)]})
|
|
table = db.create_table("test", data)
|
|
|
|
# Take by offset → to_batches
|
|
rs = list(table.take_offsets([5, 2, 17]).to_batches())
|
|
assert all(isinstance(b, pa.RecordBatch) for b in rs)
|
|
assert sum(b.num_rows for b in rs) == 3
|
|
assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17]
|
|
|
|
# Take by row id → to_batches
|
|
rs = list(table.take_row_ids([5, 2, 17]).to_batches())
|
|
assert all(isinstance(b, pa.RecordBatch) for b in rs)
|
|
assert sum(b.num_rows for b in rs) == 3
|
|
assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17]
|
|
|
|
# Take with select projection → to_batches preserves the projection
|
|
rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches())
|
|
assert all(b.schema.names == ["label"] for b in rs)
|
|
assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"]
|
|
|
|
|
|
def test_getitems(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
data = pa.table(
|
|
{
|
|
"idx": range(100),
|
|
}
|
|
)
|
|
# Make two fragments
|
|
table = db.create_table("test", data)
|
|
table.add(pa.table({"idx": range(100, 200)}))
|
|
|
|
assert table.__getitems__([5, 2, 117]) == pa.table(
|
|
{
|
|
"idx": [5, 2, 117],
|
|
}
|
|
)
|
|
|
|
offsets = random.sample(range(200), 10)
|
|
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
|
|
|
|
|
|
def test_getitems_rejects_missing_offsets(tmp_path):
|
|
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
|
|
|
|
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
|
|
table.__getitems__([0, 99])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_query_timeout_async(tmp_path):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
data = pa.table(
|
|
{
|
|
"text": ["a", "b"],
|
|
"vector": pa.FixedSizeListArray.from_arrays(
|
|
pc.random(4).cast(pa.float32()), 2
|
|
),
|
|
}
|
|
)
|
|
table = await db.create_table("test", data)
|
|
await table.create_index("text", config=FTS())
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
await table.query().where("text != 'a'").to_list(timeout=timedelta(0))
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
await table.vector_search([0.0, 0.0]).to_arrow(timeout=timedelta(0))
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
await (await table.search("a", query_type="fts")).to_pandas(
|
|
timeout=timedelta(0)
|
|
)
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
await (
|
|
table.query()
|
|
.nearest_to_text("a")
|
|
.nearest_to([0.0, 0.0])
|
|
.to_list(timeout=timedelta(0))
|
|
)
|
|
|
|
|
|
def test_search_empty_table(mem_db):
|
|
"""Test searching on empty table should not crash
|
|
|
|
Regression test for issue #303:
|
|
https://github.com/lancedb/lancedb/issues/303
|
|
Searching on empty table produces scary error message
|
|
"""
|
|
schema = pa.schema(
|
|
[pa.field("vector", pa.list_(pa.float32(), 2)), pa.field("id", pa.int64())]
|
|
)
|
|
table = mem_db.create_table("test_empty_search", schema=schema)
|
|
|
|
# Search on empty table should return empty results, not crash
|
|
results = table.search([1.0, 2.0]).limit(5).to_list()
|
|
assert results == []
|
|
|
|
|
|
def test_ensure_vector_query_empty_list():
|
|
"""Regression: ensure_vector_query used to return instead of raise ValueError."""
|
|
with pytest.raises(ValueError, match="non-empty"):
|
|
ensure_vector_query([])
|
|
|
|
|
|
def test_ensure_vector_query_nested_empty_list():
|
|
"""Regression: ensure_vector_query used to return instead of raise ValueError."""
|
|
with pytest.raises(ValueError, match="non-empty"):
|
|
ensure_vector_query([[]])
|
|
|
|
|
|
@pytest.mark.parametrize("query", [[], np.array([], dtype=np.float32)])
|
|
def test_vector_query_builder_empty_vector(table, query):
|
|
with pytest.raises(ValueError, match="^Query vector must not be empty$"):
|
|
LanceVectorQueryBuilder(table, query, "vector")
|
|
|
|
|
|
def test_fast_search(tmp_path):
|
|
db = lancedb.connect(tmp_path)
|
|
|
|
# Generate data matching the async test style
|
|
vectors = pa.FixedShapeTensorArray.from_numpy_ndarray(
|
|
np.random.rand(256, 32)
|
|
).storage
|
|
|
|
table = db.create_table("test", pa.table({"vector": vectors}))
|
|
|
|
# FIX: Pass arguments directly instead of using 'config=IvfPq(...)'
|
|
table.create_index(vector_column_name="vector", num_partitions=1, num_sub_vectors=1)
|
|
|
|
# Add data to ensure table has enough segments/rows
|
|
table.add(pa.table({"vector": vectors}))
|
|
|
|
q = [1.0] * 32
|
|
|
|
# 1. Normal Search -> Should include "LanceScan" (Brute Force / Scan)
|
|
plan = table.search(q).explain_plan(True)
|
|
assert "LanceScan" in plan
|
|
|
|
# 2. Fast Search -> Should NOT include "LanceScan" (Uses Index)
|
|
plan = table.search(q).fast_search().explain_plan(True)
|
|
assert "LanceScan" not in plan
|
|
|
|
|
|
def test_blob_v2_with_row_id_bytes_pandas(tmp_db):
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_rowid_bytes_pandas")
|
|
|
|
df = (
|
|
table.search()
|
|
.with_row_id(True)
|
|
.select(["id", "blob"])
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
|
|
assert "_rowid" in df.columns
|
|
assert df["id"].tolist() == [1, 2, 3, 4]
|
|
assert df["blob"].tolist() == [b"one", b"two", b"three", b"four"]
|
|
|
|
|
|
def test_blob_v2_expr_projection_stash(tmp_db):
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_expr_projection_stash")
|
|
|
|
hits = table.search().select({"blob_alias": col("blob")}).limit(2).to_arrow()
|
|
|
|
assert "_rowid" not in hits.column_names
|
|
assert "_lance_row_id" in hits.schema.field("blob_alias").type.names
|
|
blobs = table.fetch_blobs("blob", hits)
|
|
assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"]
|
|
|
|
|
|
def test_blob_v2_to_batches_row_id(tmp_db):
|
|
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_to_batches_rowid")
|
|
|
|
hits = table.search().select(["id", "blob"]).limit(2).to_batches().read_all()
|
|
|
|
assert "_rowid" in hits.column_names
|
|
blobs = table.fetch_blobs("blob", hits)
|
|
assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)]
|
|
)
|
|
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
|
def test_search_effort_probe_budget(
|
|
tmp_path, monkeypatch, metric, effort, probes80, probes90
|
|
):
|
|
import re
|
|
from lancedb.index import IvfFlat
|
|
|
|
monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0")
|
|
monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4")
|
|
monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4")
|
|
# The lower tiers use metric/k calibration; Auto and the upper tiers retain
|
|
# their existing budgets. Keep exact execution counts and precedence checks.
|
|
probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[
|
|
effort
|
|
]
|
|
rng = np.random.default_rng(42)
|
|
vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0)
|
|
vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32)
|
|
data = pa.table(
|
|
{
|
|
"id": np.arange(512),
|
|
"text": ["dog"] * 512,
|
|
"vector": pa.FixedSizeListArray.from_arrays(pa.array(vectors.ravel()), 16),
|
|
}
|
|
)
|
|
table = lancedb.connect(tmp_path).create_table("effort", data.slice(0, 256))
|
|
table.add(data.slice(256))
|
|
table.create_index(
|
|
"vector", config=IvfFlat(distance_type=metric, num_partitions=16)
|
|
)
|
|
vector = np.eye(16, dtype=np.float32)[0]
|
|
|
|
def search(value=effort):
|
|
return table.search(vector).distance_type(metric).search_effort(value).limit(8)
|
|
|
|
def partitions(query):
|
|
vector_plan = query.analyze_plan().split("FTS Search Plan:", 1)[0]
|
|
values = re.findall(r"partitions_searched=(\d+)", vector_plan)
|
|
assert values
|
|
return sum(map(int, values))
|
|
|
|
assert partitions(search()) == probes
|
|
exact = set(
|
|
table.search(vector)
|
|
.distance_type(metric)
|
|
.bypass_vector_index()
|
|
.limit(8)
|
|
.to_arrow()["id"]
|
|
.to_pylist()
|
|
)
|
|
actual = set(search().to_arrow()["id"].to_pylist())
|
|
assert len(actual & exact) / 8 >= 0.5
|
|
expected = 1 if effort is None else probes
|
|
assert partitions(search().nprobes(1)) == expected
|
|
assert (
|
|
partitions(
|
|
table.search(vector)
|
|
.distance_type(metric)
|
|
.nprobes(1)
|
|
.search_effort(effort)
|
|
.limit(8)
|
|
)
|
|
== expected
|
|
)
|
|
assert partitions(search().nprobes(1).search_effort(None)) == 1
|
|
assert partitions(search().maximum_nprobes(2)) <= 2
|
|
assert partitions(search().minimum_nprobes(3).maximum_nprobes(3)) == 3
|
|
assert partitions(search(0).nprobes(16).maximum_nprobes(0)) == 1
|
|
if effort is None:
|
|
assert search().to_arrow() == search(0.5).to_arrow()
|
|
filtered = search(0).maximum_nprobes(2).where("id % 8 = 0", prefilter=True)
|
|
assert partitions(filtered) <= 2
|
|
assert all(row["id"] % 8 == 0 for row in filtered.to_list())
|
|
|
|
if metric == "l2" and effort == 0.5:
|
|
table.create_index("text", config=FTS())
|
|
hybrid = (
|
|
table.search(query_type="hybrid")
|
|
.vector(vector)
|
|
.text("dog")
|
|
.nprobes(1)
|
|
.search_effort(0.5)
|
|
.limit(8)
|
|
)
|
|
assert partitions(hybrid) == 4
|
|
assert partitions(hybrid.search_effort(None)) == 1
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"effort", [-0.1, 1.1, float("nan"), float("inf"), -float("inf")]
|
|
)
|
|
def test_search_effort_invalid_sync(table, effort):
|
|
with pytest.raises(ValueError, match="search_effort must be finite and in"):
|
|
table.search([0, 0]).search_effort(effort).to_list()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("hybrid", [False, True])
|
|
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
|
async def test_search_effort_async_roundtrip(table_async, hybrid, effort):
|
|
query = table_async.vector_search([0, 0])
|
|
if hybrid:
|
|
query = query.nearest_to_text("dog")
|
|
query = query.nprobes(5).search_effort(effort).minimum_nprobes(2).maximum_nprobes(3)
|
|
request = query.to_query_object()
|
|
assert request.search_effort == effort
|
|
assert request.nprobes == 5
|
|
assert request.minimum_nprobes == 2
|
|
assert request.maximum_nprobes == 3
|
|
assert query.search_effort(None).to_query_object().search_effort is None
|
|
query.search_effort(effort)
|
|
if not hybrid:
|
|
assert len(await query.limit(1).to_list()) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("hybrid", [False, True])
|
|
@pytest.mark.parametrize(
|
|
"effort", [-0.1, 1.1, float("nan"), float("inf"), -float("inf")]
|
|
)
|
|
async def test_search_effort_invalid_async(table_async, hybrid, effort):
|
|
query = table_async.vector_search([0, 0])
|
|
if hybrid:
|
|
query = query.nearest_to_text("dog")
|
|
with pytest.raises(ValueError, match="search_effort must be finite and in"):
|
|
query.search_effort(effort)
|
|
|
|
|
|
def test_query_result_metadata(tmp_db):
|
|
from lancedb.exceptions import MetadataCancelled, MetadataPending
|
|
from lancedb.query_result import QueryMetadata, TotalHits
|
|
|
|
table = _fragment_query_table(tmp_db, "result_metadata")
|
|
query = table.search().where("id >= 2").limit(1)
|
|
with query.to_result(track_total_hits=True) as result:
|
|
batch = next(result.batches)
|
|
assert isinstance(batch, pa.RecordBatch)
|
|
assert batch.num_rows == 1
|
|
with pytest.raises(MetadataPending):
|
|
result.metadata()
|
|
assert result.finish() == QueryMetadata(TotalHits(3, "eq"))
|
|
assert result.metadata() == QueryMetadata(TotalHits(3, "eq"))
|
|
|
|
with query.to_result(track_total_hits=2) as result:
|
|
assert result.finish() == QueryMetadata(TotalHits(2, "gte"))
|
|
|
|
with query.to_result(track_total_hits=True) as result:
|
|
next(result.batches)
|
|
with pytest.raises(MetadataCancelled):
|
|
result.metadata()
|
|
|
|
with query.to_result() as result:
|
|
assert result.finish() == QueryMetadata(None)
|
|
assert isinstance(query.to_arrow(), pa.Table)
|
|
assert isinstance(query.to_list(), list)
|
|
|
|
|
|
@pytest.mark.parametrize("cap", [0, -1, 2**64, 1.5, "1"])
|
|
def test_query_result_invalid_cap(tmp_db, cap):
|
|
table = tmp_db.create_table("result_cap", [{"id": 1}])
|
|
with pytest.raises((TypeError, ValueError), match="track_total_hits"):
|
|
table.search().to_result(track_total_hits=cap)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_query_result_metadata(tmp_db_async):
|
|
from lancedb.exceptions import MetadataPending, UnsupportedMetadata
|
|
from lancedb.query_result import TotalHits
|
|
|
|
table = await tmp_db_async.create_table("result_fts", _fragment_query_data())
|
|
await table.create_index("text", config=FTS(with_position=False))
|
|
query = table.query().nearest_to_text("one two", columns="text").limit(1)
|
|
async with await query.to_result(track_total_hits=True) as result:
|
|
batches = [batch async for batch in result.batches]
|
|
assert sum(batch.num_rows for batch in batches) == 1
|
|
assert result.metadata().total_hits == TotalHits(2, "eq")
|
|
async with await table.query().limit(0).to_result(track_total_hits=True) as empty:
|
|
with pytest.raises(MetadataPending):
|
|
empty.metadata()
|
|
assert sum([batch.num_rows async for batch in empty]) == 0
|
|
assert empty.metadata().total_hits == TotalHits(4, "eq")
|
|
with pytest.raises(UnsupportedMetadata):
|
|
await table.query().nearest_to([0.0, 0.0]).to_result(track_total_hits=True)
|
|
|
|
|
|
def test_query_result_sync_fts_empty_page(tmp_db):
|
|
from lancedb.query_result import TotalHits
|
|
|
|
table = _fragment_query_table(tmp_db, "result_fts_empty")
|
|
table.create_index("text", config=FTS(with_position=False))
|
|
query = table.search("one two", query_type="fts").limit(0)
|
|
assert query.to_arrow().num_rows == 2
|
|
with query.to_result(track_total_hits=True) as result:
|
|
assert sum(batch.num_rows for batch in result.batches) == 0
|
|
assert result.metadata().total_hits == TotalHits(2, "eq")
|
|
|
|
|
|
def test_query_result_sync_reranked_fts_empty_page(tmp_db):
|
|
from lancedb.exceptions import UnsupportedMetadata
|
|
|
|
table = _fragment_query_table(tmp_db, "result_fts_empty_reranked")
|
|
table.create_index("text", config=FTS(with_position=False))
|
|
ranker = RRFReranker()
|
|
query = table.search("one two", query_type="fts").select(["id"]).rerank(ranker)
|
|
query.limit(0)
|
|
with mock.patch.object(ranker, "rerank_fts", wraps=ranker.rerank_fts) as rerank:
|
|
with query.to_result() as empty:
|
|
assert sum(batch.num_rows for batch in empty) == 0
|
|
assert empty.metadata().total_hits is None
|
|
rerank.assert_called_once()
|
|
candidates = rerank.call_args.args[1]
|
|
assert candidates.num_rows == 0
|
|
assert {"id", "_score"} <= set(candidates.column_names)
|
|
with pytest.raises(UnsupportedMetadata):
|
|
query.to_result(track_total_hits=True)
|
|
rerank.assert_called_once()
|
|
|
|
# The legacy FTS terminal on the same builder still treats zero as unset.
|
|
legacy = query.to_arrow()
|
|
assert sorted(legacy["id"].to_pylist()) == [1, 2]
|
|
assert "_relevance_score" in legacy.column_names
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("async_api", [False, True], ids=["sync", "async"])
|
|
async def test_query_result_plain_scan_row_address(tmp_path, async_api):
|
|
from lancedb.exceptions import UnsupportedMetadata
|
|
from lancedb.query_result import TotalHits
|
|
|
|
data = _fragment_query_data()
|
|
options = {"new_table_enable_stable_row_ids": "true"}
|
|
if async_api:
|
|
db = await lancedb.connect_async(tmp_path)
|
|
table = await db.create_table("rows", data.slice(0, 2), storage_options=options)
|
|
await table.add(data.slice(2))
|
|
query = table.query()
|
|
else:
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table("rows", data.slice(0, 2), storage_options=options)
|
|
table.add(data.slice(2))
|
|
query = table.search()
|
|
query = (
|
|
query.where("id >= 2")
|
|
.select(["id"])
|
|
.scan_in_order()
|
|
.with_row_address()
|
|
.offset(1)
|
|
.limit(1)
|
|
)
|
|
for tracking, hits in [
|
|
(False, None),
|
|
(True, TotalHits(3, "eq")),
|
|
(2, TotalHits(2, "gte")),
|
|
]:
|
|
if async_api:
|
|
async with await query.to_result(track_total_hits=tracking) as result:
|
|
batches = [batch async for batch in result]
|
|
else:
|
|
with query.to_result(track_total_hits=tracking) as result:
|
|
batches = list(result)
|
|
rows = pa.Table.from_batches(batches)
|
|
assert rows.to_pylist() == [{"id": 3, "_rowaddr": 1 << 32}]
|
|
assert rows["_rowaddr"].type == pa.uint64()
|
|
assert result.metadata().total_hits == hits
|
|
|
|
if async_api:
|
|
ranked = table.query().nearest_to([0.0, 0.0]).with_row_address()
|
|
with pytest.raises(UnsupportedMetadata):
|
|
await ranked.to_result()
|
|
else:
|
|
ranked = table.search([0.0, 0.0]).with_row_address()
|
|
with pytest.raises(UnsupportedMetadata):
|
|
ranked.to_result()
|
|
restricted = query.fragment_ids([0])
|
|
with pytest.raises(UnsupportedMetadata):
|
|
if async_api:
|
|
await restricted.to_result()
|
|
else:
|
|
restricted.to_result()
|
|
|
|
|
|
def test_query_result_off_preserves_pull_reader(tmp_db, monkeypatch):
|
|
from lancedb.exceptions import MetadataCancelled
|
|
|
|
table = _fragment_query_table(tmp_db, "result_pull")
|
|
query = table.search()
|
|
monkeypatch.setattr(table, "_namespace_client", object())
|
|
monkeypatch.setattr(table, "_pushdown_operations", {"QueryTable"})
|
|
monkeypatch.setattr(table, "_route_pushdown_to_rust", False)
|
|
polled = []
|
|
schema = pa.schema([("id", pa.int64())])
|
|
|
|
def batches():
|
|
for i in range(3):
|
|
polled.append(i)
|
|
yield pa.record_batch([[i]], schema=schema)
|
|
|
|
monkeypatch.setattr(
|
|
query,
|
|
"to_batches",
|
|
lambda: pa.RecordBatchReader.from_batches(schema, batches()),
|
|
)
|
|
with query.to_result() as result:
|
|
assert not polled
|
|
assert next(result.batches).column(0).to_pylist() == [0]
|
|
assert polled == [0]
|
|
with pytest.raises(MetadataCancelled):
|
|
result.metadata()
|
|
|
|
|
|
@pytest.mark.parametrize("async_api", [False, True], ids=["sync", "async"])
|
|
@pytest.mark.asyncio
|
|
async def test_query_result_cap_boundaries(tmp_path, async_api):
|
|
from lancedb.query_result import TotalHits
|
|
|
|
data = pa.table({"id": [1, 2, 3]})
|
|
if async_api:
|
|
db = await lancedb.connect_async(tmp_path)
|
|
query = (await db.create_table("rows", data)).query().limit(1)
|
|
else:
|
|
db = lancedb.connect(tmp_path)
|
|
query = db.create_table("rows", data).search().limit(1)
|
|
for cap, expected in (
|
|
(2, TotalHits(2, "gte")),
|
|
(3, TotalHits(3, "gte")),
|
|
(4, TotalHits(3, "eq")),
|
|
(2**64 - 1, TotalHits(3, "eq")),
|
|
):
|
|
if async_api:
|
|
async with await query.to_result(track_total_hits=cap) as result:
|
|
metadata = await result.finish()
|
|
else:
|
|
with query.to_result(track_total_hits=cap) as result:
|
|
metadata = result.finish()
|
|
assert metadata.total_hits == expected
|
|
with pytest.raises(ValueError, match="track_total_hits"):
|
|
if async_api:
|
|
await query.to_result(track_total_hits=2**64)
|
|
else:
|
|
query.to_result(track_total_hits=2**64)
|
|
|
|
|
|
def test_query_result_count_error_after_last_page_batch(tmp_path):
|
|
from lancedb.exceptions import MetadataPending
|
|
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table("fallible_count", [{"id": 0}, {"id": 1}])
|
|
table.add([{"id": 2}, {"id": 3}])
|
|
query = table.search().where("id >= 0").limit(1)
|
|
with query.to_result(track_total_hits=True) as result:
|
|
assert next(result).num_rows == 1
|
|
with pytest.raises(MetadataPending):
|
|
result.metadata()
|
|
# The result page is complete. Simulate loss of the test table's
|
|
# storage before the EOF poll opens the independent count traversal.
|
|
dataset = tmp_path / "fallible_count.lance"
|
|
offline = tmp_path / "offline"
|
|
dataset.rename(offline)
|
|
try:
|
|
with pytest.raises(RuntimeError) as failure:
|
|
next(result)
|
|
with pytest.raises(type(failure.value)) as metadata:
|
|
result.metadata()
|
|
assert metadata.value is failure.value
|
|
finally:
|
|
offline.rename(dataset)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_to_pandas_non_blob_custom_to_arrow_override_still_called(
|
|
tmp_path, monkeypatch
|
|
):
|
|
data = pa.table(
|
|
{
|
|
"id": pa.array([1, 2], type=pa.int64()),
|
|
"text": pa.array(["alpha one", "alpha two"], type=pa.utf8()),
|
|
"vector": pa.array(
|
|
[[1.0, 0.0], [0.0, 1.0]], type=pa.list_(pa.float32(), 2)
|
|
),
|
|
}
|
|
)
|
|
|
|
sync_db = lancedb.connect(tmp_path / "sync_override")
|
|
sync_table = sync_db.create_table("items", data)
|
|
sync_table.create_index("text", config=FTS(with_position=True))
|
|
|
|
# Sync instance-monkeypatched to_arrow
|
|
sync_query = sync_table.search().select(["id"])
|
|
orig_sync_to_arrow = sync_query.to_arrow
|
|
sync_instance_calls = 0
|
|
|
|
def wrapped_sync_to_arrow(*args, **kwargs):
|
|
nonlocal sync_instance_calls
|
|
sync_instance_calls += 1
|
|
return orig_sync_to_arrow(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(sync_query, "to_arrow", wrapped_sync_to_arrow)
|
|
assert sorted(sync_query.to_pandas()["id"].tolist()) == [1, 2]
|
|
assert sync_instance_calls == 1
|
|
assert sorted(sync_query.to_pandas(blob_mode="descriptions")["id"].tolist()) == [
|
|
1,
|
|
2,
|
|
]
|
|
assert sync_instance_calls == 2
|
|
|
|
# Sync subclass overriding to_arrow(self, *, timeout=None) without blob_mode
|
|
sync_subclass_calls = 0
|
|
|
|
class CustomSyncQuery(LanceEmptyQueryBuilder):
|
|
def to_arrow(self, *, timeout=None):
|
|
nonlocal sync_subclass_calls
|
|
sync_subclass_calls += 1
|
|
return super().to_arrow(timeout=timeout)
|
|
|
|
custom_sync = CustomSyncQuery(sync_table).select(["id"])
|
|
assert sorted(custom_sync.to_pandas()["id"].tolist()) == [1, 2]
|
|
assert sync_subclass_calls == 1
|
|
assert sorted(custom_sync.to_pandas(blob_mode="descriptions")["id"].tolist()) == [
|
|
1,
|
|
2,
|
|
]
|
|
assert sync_subclass_calls == 2
|
|
|
|
# Async setup
|
|
async_db = await lancedb.connect_async(tmp_path / "async_override")
|
|
async_table = await async_db.create_table("items", data)
|
|
await async_table.create_index("text", config=FTS(with_position=True))
|
|
|
|
# Async instance-monkeypatched to_arrow
|
|
async_query = async_table.query().select(["id"])
|
|
orig_async_to_arrow = async_query.to_arrow
|
|
async_instance_calls = 0
|
|
|
|
async def wrapped_async_to_arrow(*args, **kwargs):
|
|
nonlocal async_instance_calls
|
|
async_instance_calls += 1
|
|
return await orig_async_to_arrow(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(async_query, "to_arrow", wrapped_async_to_arrow)
|
|
assert sorted((await async_query.to_pandas())["id"].tolist()) == [1, 2]
|
|
assert async_instance_calls == 1
|
|
assert sorted(
|
|
(await async_query.to_pandas(blob_mode="descriptions"))["id"].tolist()
|
|
) == [1, 2]
|
|
assert async_instance_calls == 2
|
|
|
|
# Async class-monkeypatched AsyncQuery.to_arrow
|
|
class_calls = 0
|
|
orig_cls_to_arrow = AsyncQuery.to_arrow
|
|
|
|
async def wrapped_cls_to_arrow(self, *args, **kwargs):
|
|
nonlocal class_calls
|
|
class_calls += 1
|
|
return await orig_cls_to_arrow(self, *args, **kwargs)
|
|
|
|
with monkeypatch.context() as mp:
|
|
mp.setattr(AsyncQuery, "to_arrow", wrapped_cls_to_arrow)
|
|
assert sorted(
|
|
(await async_table.query().select(["id"]).to_pandas())["id"].tolist()
|
|
) == [1, 2]
|
|
assert class_calls == 1
|
|
assert sorted(
|
|
(
|
|
await async_table.query()
|
|
.select(["id"])
|
|
.to_pandas(blob_mode="descriptions")
|
|
)["id"].tolist()
|
|
) == [1, 2]
|
|
assert class_calls == 2
|
|
|
|
# Async subclass overriding async def to_arrow(self, timeout=None) without blob_mode
|
|
async_subclass_calls = 0
|
|
|
|
class CustomAsyncQuery(AsyncQuery):
|
|
async def to_arrow(self, timeout=None):
|
|
nonlocal async_subclass_calls
|
|
async_subclass_calls += 1
|
|
return await super().to_arrow(timeout=timeout)
|
|
|
|
custom_async = CustomAsyncQuery(async_table._inner.query(), async_table).select(
|
|
["id"]
|
|
)
|
|
assert sorted((await custom_async.to_pandas())["id"].tolist()) == [1, 2]
|
|
assert async_subclass_calls == 1
|
|
assert sorted(
|
|
(await custom_async.to_pandas(blob_mode="descriptions"))["id"].tolist()
|
|
) == [1, 2]
|
|
assert async_subclass_calls == 2
|
|
|
|
# Hybrid child-leg monkeypatch parity (sync and async)
|
|
with monkeypatch.context() as mp:
|
|
sync_legs = []
|
|
orig_sync_fts = LanceFtsQueryBuilder.to_arrow
|
|
orig_sync_vec = LanceVectorQueryBuilder.to_arrow
|
|
|
|
def counted_sync_fts(self, *args, **kwargs):
|
|
sync_legs.append("fts")
|
|
return orig_sync_fts(self, *args, **kwargs)
|
|
|
|
def counted_sync_vec(self, *args, **kwargs):
|
|
sync_legs.append("vec")
|
|
return orig_sync_vec(self, *args, **kwargs)
|
|
|
|
mp.setattr(LanceFtsQueryBuilder, "to_arrow", counted_sync_fts)
|
|
mp.setattr(LanceVectorQueryBuilder, "to_arrow", counted_sync_vec)
|
|
|
|
sync_hybrid = (
|
|
sync_table.search(query_type="hybrid")
|
|
.vector([1.0, 0.0])
|
|
.text("alpha")
|
|
.limit(2)
|
|
)
|
|
assert len(sync_hybrid.to_pandas()) == 2
|
|
assert sorted(sync_legs) == ["fts", "vec"]
|
|
sync_legs.clear()
|
|
assert sync_hybrid.to_arrow().num_rows == 2
|
|
assert sorted(sync_legs) == ["fts", "vec"]
|
|
|
|
with monkeypatch.context() as mp:
|
|
async_legs = []
|
|
orig_async_fts = AsyncFTSQuery.to_arrow
|
|
orig_async_vec = AsyncVectorQuery.to_arrow
|
|
|
|
async def counted_async_fts(self, *args, **kwargs):
|
|
async_legs.append("fts")
|
|
return await orig_async_fts(self, *args, **kwargs)
|
|
|
|
async def counted_async_vec(self, *args, **kwargs):
|
|
async_legs.append("vec")
|
|
return await orig_async_vec(self, *args, **kwargs)
|
|
|
|
mp.setattr(AsyncFTSQuery, "to_arrow", counted_async_fts)
|
|
mp.setattr(AsyncVectorQuery, "to_arrow", counted_async_vec)
|
|
|
|
async_hybrid = (
|
|
async_table.vector_search([1.0, 0.0]).nearest_to_text("alpha").limit(2)
|
|
)
|
|
assert len(await async_hybrid.to_pandas()) == 2
|
|
assert sorted(async_legs) == ["fts", "vec"]
|
|
async_legs.clear()
|
|
assert (await async_hybrid.to_arrow()).num_rows == 2
|
|
assert sorted(async_legs) == ["fts", "vec"]
|
|
|
|
# Unbound AsyncQueryBase (table=None) conservatively falls back to output_schema()
|
|
unbound = AsyncQuery(async_table._inner.query(), table=None)
|
|
orig_unbound_output_schema = unbound.output_schema
|
|
unbound_output_schema_calls = 0
|
|
|
|
async def counted_unbound_output_schema():
|
|
nonlocal unbound_output_schema_calls
|
|
unbound_output_schema_calls += 1
|
|
return await orig_unbound_output_schema()
|
|
|
|
monkeypatch.setattr(unbound, "output_schema", counted_unbound_output_schema)
|
|
unbound_df = await unbound.to_pandas()
|
|
assert sorted(unbound_df["id"].tolist()) == [1, 2]
|
|
assert unbound_output_schema_calls == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_to_pandas_non_blob_subquery_skips_output_schema(tmp_path, monkeypatch):
|
|
items_data = pa.table(
|
|
{
|
|
"id": pa.array([1, 2, 3], type=pa.int64()),
|
|
"text": pa.array(["alpha one", "alpha two", "alpha three"], type=pa.utf8()),
|
|
"vector": pa.array(
|
|
[[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]], type=pa.list_(pa.float32(), 2)
|
|
),
|
|
}
|
|
)
|
|
other_data = pa.table({"id": pa.array([2, 3], type=pa.int64())})
|
|
filter_sql = "id IN (SELECT id FROM other)"
|
|
|
|
def fail_output_schema(*_args, **_kwargs):
|
|
raise AssertionError("output_schema must not be called on non-blob to_pandas")
|
|
|
|
async def fail_async_output_schema(*_args, **_kwargs):
|
|
raise AssertionError(
|
|
"async output_schema must not be called on non-blob to_pandas"
|
|
)
|
|
|
|
# Sync
|
|
sync_db = lancedb.connect(tmp_path / "sync_subquery")
|
|
sync_table = sync_db.create_table("items", items_data)
|
|
sync_table.create_index("text", config=FTS(with_position=True))
|
|
sync_db.create_table("other", other_data)
|
|
|
|
monkeypatch.setattr(sync_table, "_output_schema", fail_output_schema)
|
|
|
|
sync_queries = [
|
|
sync_table.search().where(filter_sql).select(["id"]),
|
|
sync_table.search([1.0, 0.0]).where(filter_sql).select(["id"]).limit(2),
|
|
sync_table.search("alpha", query_type="fts")
|
|
.where(filter_sql)
|
|
.select(["id"])
|
|
.limit(2),
|
|
sync_table.search(query_type="hybrid")
|
|
.vector([1.0, 0.0])
|
|
.text("alpha")
|
|
.where(filter_sql)
|
|
.select(["id"])
|
|
.limit(2),
|
|
]
|
|
for query in sync_queries:
|
|
expected = sorted(query.to_arrow()["id"].to_pylist())
|
|
actual = sorted(query.to_pandas()["id"].tolist())
|
|
assert expected == [2, 3]
|
|
assert actual == expected
|
|
|
|
# Async
|
|
async_db = await lancedb.connect_async(tmp_path / "async_subquery")
|
|
async_table = await async_db.create_table("items", items_data)
|
|
await async_table.create_index("text", config=FTS(with_position=True))
|
|
await async_db.create_table("other", other_data)
|
|
|
|
monkeypatch.setattr(AsyncQueryBase, "output_schema", fail_async_output_schema)
|
|
|
|
async_queries = [
|
|
async_table.query().where(filter_sql).select(["id"]),
|
|
async_table.vector_search([1.0, 0.0]).where(filter_sql).select(["id"]).limit(2),
|
|
(await async_table.search("alpha", query_type="fts"))
|
|
.where(filter_sql)
|
|
.select(["id"])
|
|
.limit(2),
|
|
async_table.vector_search([1.0, 0.0])
|
|
.nearest_to_text("alpha")
|
|
.where(filter_sql)
|
|
.select(["id"])
|
|
.limit(2),
|
|
]
|
|
for query in async_queries:
|
|
expected = sorted((await query.to_arrow())["id"].to_pylist())
|
|
actual = sorted((await query.to_pandas())["id"].tolist())
|
|
assert expected == [2, 3]
|
|
assert actual == expected
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_blob_to_pandas_does_not_add_extra_schema_fetches(
|
|
tmp_db, tmp_db_async, monkeypatch
|
|
):
|
|
pytest.importorskip("lance")
|
|
|
|
v1_sync = tmp_db.create_table(
|
|
"blob_v1_sync",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
v1_async = await tmp_db_async.create_table(
|
|
"blob_v1_async",
|
|
_blob_query_data(),
|
|
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
|
)
|
|
|
|
v2_schema = pa.schema(
|
|
[
|
|
pa.field("id", pa.int64()),
|
|
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
|
lancedb.blob("image"),
|
|
]
|
|
)
|
|
v2_rows = [
|
|
{"id": 1, "vector": [1.0, 0.0], "image": b"one"},
|
|
{"id": 2, "vector": [0.0, 1.0], "image": b"two"},
|
|
]
|
|
v2_sync = tmp_db.create_table("blob_v2_sync", schema=v2_schema)
|
|
v2_sync.add(v2_rows)
|
|
v2_async = await tmp_db_async.create_table("blob_v2_async", schema=v2_schema)
|
|
await v2_async.add(v2_rows)
|
|
|
|
mem_sync_db = lancedb.connect("memory:///")
|
|
v2_mem_sync = mem_sync_db.create_table("blob_v2_mem_sync", schema=v2_schema)
|
|
v2_mem_sync.add(v2_rows)
|
|
mem_async_db = await lancedb.connect_async("memory:///")
|
|
v2_mem_async = await mem_async_db.create_table(
|
|
"blob_v2_mem_async", schema=v2_schema
|
|
)
|
|
await v2_mem_async.add(v2_rows)
|
|
|
|
schema_calls = 0
|
|
validated_blob_sources_calls = 0
|
|
blob_output_schema_calls = 0
|
|
|
|
orig_schema_sync = AsyncTable._schema_sync
|
|
orig_schema_async = AsyncTable.schema
|
|
orig_validated_blob_sources = AsyncQueryBase._validated_blob_sources
|
|
orig_blob_output_schema = AsyncQueryBase._blob_output_schema
|
|
|
|
def counted_schema_sync(self):
|
|
nonlocal schema_calls
|
|
schema_calls += 1
|
|
return orig_schema_sync(self)
|
|
|
|
async def counted_schema_async(self):
|
|
nonlocal schema_calls
|
|
schema_calls += 1
|
|
return await orig_schema_async(self)
|
|
|
|
async def counted_validated_blob_sources(self, *args, **kwargs):
|
|
nonlocal validated_blob_sources_calls
|
|
validated_blob_sources_calls += 1
|
|
return await orig_validated_blob_sources(self, *args, **kwargs)
|
|
|
|
async def counted_blob_output_schema(self):
|
|
nonlocal blob_output_schema_calls
|
|
blob_output_schema_calls += 1
|
|
return await orig_blob_output_schema(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "_schema_sync", counted_schema_sync)
|
|
monkeypatch.setattr(AsyncTable, "schema", counted_schema_async)
|
|
monkeypatch.setattr(
|
|
AsyncQueryBase, "_validated_blob_sources", counted_validated_blob_sources
|
|
)
|
|
monkeypatch.setattr(
|
|
AsyncQueryBase, "_blob_output_schema", counted_blob_output_schema
|
|
)
|
|
|
|
# 1. Plain-scan blob v1 and v2 to_pandas (sync & async, all modes): 1 schema fetch
|
|
for blob_mode in ("lazy", "descriptions", "bytes"):
|
|
schema_calls = 0
|
|
df = (
|
|
v1_sync.search()
|
|
.where("id = 1")
|
|
.select(["id", "blob"])
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert df["id"].tolist() == [1]
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
df = (
|
|
await v1_async.query()
|
|
.where("id = 1")
|
|
.select(["id", "blob"])
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert df["id"].tolist() == [1]
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
df = (
|
|
v2_sync.search()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert df["id"].tolist() == [1]
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
df = (
|
|
await v2_async.query()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert df["id"].tolist() == [1]
|
|
assert schema_calls == 1
|
|
|
|
# 2. Non-plain-scan / memory:// / flatten=True default blob_mode="lazy"
|
|
# blob v2 to_pandas: 1 schema fetch (sync & async), and async calls
|
|
# _validated_blob_sources 1 time.
|
|
sync_v2_fallbacks = [
|
|
lambda: v2_sync.search([1.0, 0.0], vector_column_name="vector")
|
|
.select(["id", "image"])
|
|
.limit(1)
|
|
.to_pandas(),
|
|
lambda: v2_sync.take_offsets([0]).select(["id", "image"]).to_pandas(),
|
|
lambda: v2_sync.search()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(flatten=True),
|
|
lambda: v2_mem_sync.search()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(),
|
|
]
|
|
for run in sync_v2_fallbacks:
|
|
schema_calls = 0
|
|
df = run()
|
|
assert len(df) == 1
|
|
assert schema_calls == 1
|
|
|
|
async_v2_fallbacks = [
|
|
lambda: v2_async.vector_search([1.0, 0.0])
|
|
.select(["id", "image"])
|
|
.limit(1)
|
|
.to_pandas(),
|
|
lambda: v2_async.take_offsets([0]).select(["id", "image"]).to_pandas(),
|
|
lambda: v2_async.query()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(flatten=True),
|
|
lambda: v2_mem_async.query()
|
|
.where("id = 1")
|
|
.select(["id", "image"])
|
|
.to_pandas(),
|
|
]
|
|
for run in async_v2_fallbacks:
|
|
schema_calls = 0
|
|
validated_blob_sources_calls = 0
|
|
df = await run()
|
|
assert len(df) == 1
|
|
assert schema_calls == 1
|
|
assert validated_blob_sources_calls == 1
|
|
|
|
# 3. Async non-plain-scan blob to_arrow / to_pandas (blob_mode="bytes")
|
|
# calls _blob_output_schema == 1 time (not twice).
|
|
schema_calls = 0
|
|
blob_output_schema_calls = 0
|
|
tbl = (
|
|
await v2_async.vector_search([1.0, 0.0])
|
|
.select(["id", "image"])
|
|
.limit(1)
|
|
.to_arrow(blob_mode="bytes")
|
|
)
|
|
assert tbl["image"].to_pylist() == [b"one"]
|
|
assert schema_calls == 1
|
|
assert blob_output_schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
blob_output_schema_calls = 0
|
|
df = (
|
|
await v2_async.vector_search([1.0, 0.0])
|
|
.select(["id", "image"])
|
|
.limit(1)
|
|
.to_pandas(blob_mode="bytes")
|
|
)
|
|
assert df["image"].tolist() == [b"one"]
|
|
assert schema_calls == 1
|
|
assert blob_output_schema_calls == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_to_batches_override_preserved_on_non_blob_table(
|
|
tmp_path, monkeypatch
|
|
):
|
|
db = await lancedb.connect_async(tmp_path / "to_batches_override")
|
|
table = await db.create_table("items", data=[{"id": 1}, {"id": 2}])
|
|
|
|
def _filter_id_one(reader: AsyncRecordBatchReader) -> AsyncRecordBatchReader:
|
|
async def filtered_batches():
|
|
async for batch in reader:
|
|
filtered = batch.filter(pc.equal(batch["id"], 1))
|
|
if filtered.num_rows > 0:
|
|
yield filtered
|
|
|
|
return AsyncRecordBatchReader._from_batches(reader.schema, filtered_batches())
|
|
|
|
class FilteringAsyncQuery(AsyncQuery):
|
|
async def to_batches(
|
|
self,
|
|
*,
|
|
max_batch_length=None,
|
|
timeout=None,
|
|
blob_mode="lazy",
|
|
):
|
|
reader = await super().to_batches(
|
|
max_batch_length=max_batch_length,
|
|
timeout=timeout,
|
|
blob_mode=blob_mode,
|
|
)
|
|
return _filter_id_one(reader)
|
|
|
|
query = FilteringAsyncQuery(table._inner.query(), table)
|
|
assert (await query.to_arrow(blob_mode="descriptions"))["id"].to_pylist() == [1]
|
|
assert (await query.to_arrow(blob_mode="bytes"))["id"].to_pylist() == [1]
|
|
assert (await query.to_pandas())["id"].tolist() == [1]
|
|
assert (await query.to_pandas(blob_mode="descriptions"))["id"].tolist() == [1]
|
|
assert (await query.to_pandas(blob_mode="bytes"))["id"].tolist() == [1]
|
|
assert sorted((await query.to_arrow())["id"].to_pylist()) == [1, 2]
|
|
|
|
instance_query = table.query()
|
|
orig_instance_to_batches = instance_query.to_batches
|
|
|
|
async def instance_to_batches(
|
|
*, max_batch_length=None, timeout=None, blob_mode="lazy"
|
|
):
|
|
reader = await orig_instance_to_batches(
|
|
max_batch_length=max_batch_length,
|
|
timeout=timeout,
|
|
blob_mode=blob_mode,
|
|
)
|
|
return _filter_id_one(reader)
|
|
|
|
monkeypatch.setattr(instance_query, "to_batches", instance_to_batches)
|
|
assert (await instance_query.to_arrow(blob_mode="descriptions"))[
|
|
"id"
|
|
].to_pylist() == [1]
|
|
assert (await instance_query.to_pandas())["id"].tolist() == [1]
|
|
|
|
orig_class_to_batches = AsyncQuery.to_batches
|
|
|
|
async def class_to_batches(
|
|
self, *, max_batch_length=None, timeout=None, blob_mode="lazy"
|
|
):
|
|
reader = await orig_class_to_batches(
|
|
self,
|
|
max_batch_length=max_batch_length,
|
|
timeout=timeout,
|
|
blob_mode=blob_mode,
|
|
)
|
|
return _filter_id_one(reader)
|
|
|
|
with monkeypatch.context() as mp:
|
|
mp.setattr(AsyncQuery, "to_batches", class_to_batches)
|
|
assert (await table.query().to_arrow(blob_mode="descriptions"))[
|
|
"id"
|
|
].to_pylist() == [1]
|
|
assert (await table.query().to_pandas())["id"].tolist() == [1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"blob_metadata",
|
|
[
|
|
{"lance-encoding:blob": "true"},
|
|
{"ARROW:extension:name": "lance.blob.v2"},
|
|
],
|
|
)
|
|
async def test_reranker_synthesized_blob_column_validated_in_to_pandas(
|
|
tmp_path, blob_metadata
|
|
):
|
|
blob_struct_type = pa.struct([("position", pa.uint64())])
|
|
blob_field = pa.field("external_image", blob_struct_type, metadata=blob_metadata)
|
|
|
|
class BlobSynthesizingReranker(Reranker):
|
|
def rerank_fts(self, query: str, fts_results: pa.Table) -> pa.Table:
|
|
n = len(fts_results)
|
|
return fts_results.append_column(
|
|
"_relevance_score", pa.array([1.0] * n, type=pa.float32())
|
|
).append_column(
|
|
blob_field,
|
|
pa.array([{"position": 1}] * n, type=blob_struct_type),
|
|
)
|
|
|
|
def rerank_hybrid(
|
|
self,
|
|
query: str,
|
|
vector_results: pa.Table,
|
|
fts_results: pa.Table,
|
|
) -> pa.Table:
|
|
return fts_results
|
|
|
|
reranker = BlobSynthesizingReranker()
|
|
rows = [{"id": 1, "text": "alpha"}, {"id": 2, "text": "beta"}]
|
|
|
|
sync_db = lancedb.connect(tmp_path / "sync_rerank_blob")
|
|
sync_table = sync_db.create_table("docs", data=rows)
|
|
sync_table.create_index("text", config=FTS(with_position=True))
|
|
|
|
async_db = await lancedb.connect_async(tmp_path / "async_rerank_blob")
|
|
async_table = await async_db.create_table("docs", data=rows)
|
|
await async_table.create_index("text", config=FTS(with_position=True))
|
|
|
|
async_fts_query = (await async_table.search("alpha", query_type="fts")).rerank(
|
|
reranker
|
|
)
|
|
with pytest.raises(
|
|
ValueError, match="could not match result columns.*external_image"
|
|
):
|
|
await async_fts_query.to_pandas(blob_mode="bytes")
|
|
with pytest.raises(
|
|
ValueError, match="could not match result columns.*external_image"
|
|
):
|
|
await async_fts_query.to_arrow(blob_mode="bytes")
|
|
with pytest.raises(RuntimeError, match="no fetchable blob v2 source"):
|
|
await async_fts_query.to_pandas()
|
|
async_desc_df = await async_fts_query.to_pandas(blob_mode="descriptions")
|
|
assert async_desc_df["external_image"].tolist() == [{"position": 1}]
|
|
|
|
sync_fts_query = sync_table.search("alpha", query_type="fts").rerank(reranker)
|
|
with pytest.raises(
|
|
ValueError, match="could not match result columns.*external_image"
|
|
):
|
|
sync_fts_query.to_pandas(blob_mode="bytes")
|
|
with pytest.raises(
|
|
ValueError, match="could not match result columns.*external_image"
|
|
):
|
|
sync_fts_query.to_list(blob_mode="bytes")
|
|
with pytest.raises(
|
|
ValueError, match="could not match result columns.*external_image"
|
|
):
|
|
sync_fts_query.to_arrow(blob_mode="bytes")
|
|
with pytest.raises(RuntimeError, match="no fetchable blob v2 source"):
|
|
sync_fts_query.to_pandas()
|
|
sync_desc_df = sync_fts_query.to_pandas(blob_mode="descriptions")
|
|
assert sync_desc_df["external_image"].tolist() == [{"position": 1}]
|
|
|
|
assert list(sync_table.search().select(["id", "_rowid"]).to_pandas().columns) == [
|
|
"id",
|
|
"_rowid",
|
|
]
|
|
assert list(
|
|
sync_table.search()
|
|
.select(["id", "_rowid"])
|
|
.to_pandas(blob_mode="bytes")
|
|
.columns
|
|
) == ["id", "_rowid"]
|
|
assert list(
|
|
(await async_table.query().select(["id", "_rowid"]).to_pandas()).columns
|
|
) == ["id", "_rowid"]
|
|
assert list(
|
|
(
|
|
await async_table.query()
|
|
.select(["id", "_rowid"])
|
|
.to_pandas(blob_mode="bytes")
|
|
).columns
|
|
) == ["id", "_rowid"]
|
|
|
|
synthesized_tbl = pa.Table.from_arrays(
|
|
[
|
|
pa.array([1], type=pa.int64()),
|
|
pa.array([{"position": 1}], type=blob_struct_type),
|
|
],
|
|
schema=pa.schema([pa.field("id", pa.int64()), blob_field]),
|
|
)
|
|
|
|
class LegacyAsyncToArrowQuery(AsyncQuery):
|
|
async def to_arrow(self, timeout=None):
|
|
return synthesized_tbl
|
|
|
|
custom_async = LegacyAsyncToArrowQuery(async_table._inner.query(), async_table)
|
|
with pytest.raises(ValueError, match="external_image"):
|
|
await custom_async.to_pandas(blob_mode="bytes")
|
|
|
|
class LegacySyncToArrowQuery(LanceEmptyQueryBuilder):
|
|
def to_arrow(self, *, timeout=None):
|
|
return synthesized_tbl
|
|
|
|
custom_sync = LegacySyncToArrowQuery(sync_table)
|
|
with pytest.raises(ValueError, match="external_image"):
|
|
custom_sync.to_pandas(blob_mode="bytes")
|
|
with pytest.raises(ValueError, match="external_image"):
|
|
custom_sync.to_list(blob_mode="bytes")
|
|
|
|
recorded_modes: list[str] = []
|
|
|
|
class KeywordOnlyBlobModeAsyncQuery(AsyncQuery):
|
|
async def to_arrow(self, timeout=None, *, blob_mode="lazy"):
|
|
recorded_modes.append(blob_mode)
|
|
return await super().to_arrow(timeout=timeout, blob_mode=blob_mode)
|
|
|
|
kw_async = KeywordOnlyBlobModeAsyncQuery(async_table._inner.query(), async_table)
|
|
await kw_async.to_pandas()
|
|
await kw_async.to_pandas(blob_mode="bytes")
|
|
assert recorded_modes == ["descriptions", "bytes"]
|