Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,40 @@ pip install 'daft[lance]'

## Usage

### Vector Search

`read_lance` exposes Lance's `_distance` column as Float32 when `nearest` is
set. Use `nearest.distance_range` to restrict the search before its Top-K
cutoff, and sort explicitly when the output needs to be ordered.

```python
from daft_lance import read_lance

df = read_lance(
"data.lance",
default_scan_options={
"nearest": {
"column": "embedding",
"q": [0.0, 1.0],
"k": 10,
"metric": "l2",
"distance_range": (None, 0.5),
}
},
)
result = df.select("id", "_distance").sort("_distance")
```

The example includes distances strictly below `0.5`. The lower bound is
inclusive, the upper bound is exclusive, and `None` leaves a side unbounded.
For an inclusive cutoff of `0.5`, pass the next representable Float32 as the
upper bound, for example `np.nextafter(np.float32(0.5), np.float32(np.inf)).item()`.
A Daft filter on `_distance` runs on the matches returned by the nearest scan.

Smaller distances rank first. L2 reports squared Euclidean distance, cosine
reports one minus cosine similarity, dot reports one minus the dot product, and
Hamming counts differing bits. Thresholds use the chosen metric's units.

### Compaction

```python
Expand Down
53 changes: 47 additions & 6 deletions daft_lance/lance_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import logging
import warnings
from collections.abc import Iterator
from typing import Any
from typing import Any, cast

import lance

from daft.context import get_context
from daft.daft import CountMode, PyExpr, PyPartitionField, PyPushdowns, PyRecordBatch, ScanTask
from daft.dependencies import pa
from daft.expressions import Expression
from daft.expressions.visitor import _ColumnVisitor
from daft.io.pushdowns import SupportsPushdownFilters
from daft.io.scan import ScanOperator
from daft.logical.schema import Schema
Expand Down Expand Up @@ -91,16 +92,42 @@ def _iter_batches() -> Iterator[PyRecordBatch]:

# If fragment_ids is None, let Lance choose fragments via index; omit the fragments parameter.
if fragment_ids is None:
columns = required_columns
scanner_options: dict[str, Any] = {}
append_fragment_id = nearest is not None and include_fragment_id
if nearest is not None:
scanner_options["disable_scoring_autoprojection"] = True
# With no Daft projection, expose the full nearest scan schema.
if columns is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Handle empty scan projections in nearest searches

If the query only selects a literal, such as df.select(daft.lit(1).alias("one")), Daft asks Lance for columns=[]. With scoring auto-projection disabled, Lance returns a batch with rows but no columns, which Daft cannot convert. On a search with two matches, the base commit returns {"one": [1, 1]}, while this PR raises on both pylance 12.0.0 and 14.0.2.

Could we explicitly request _distance when the final Lance projection is empty, and add a regression test that verifies one output row per match?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! Fixed in e2a1f1e to request _distance on empty projections, and added a regression test for literal-only selects.

columns = ds.schema.names
if "_distance" not in columns:
columns.append("_distance")
if append_fragment_id:
columns = [column for column in columns if column != "fragment_id"]
scanner_options["with_row_address"] = True
elif not columns:
# Daft needs a column to preserve row counts for literal-only projections.
columns = ["_distance"]
keep_row_address = columns is not None and "_rowaddr" in columns

scanner = ds.scanner(
columns=required_columns,
columns=columns,
filter=filter,
limit=limit,
nearest=nearest,
blob_handling="blobs_descriptions",
**scanner_options,
)

def _batches() -> Iterator[PyRecordBatch]:
for rb in scanner.to_batches():
if append_fragment_id:
# Lance stores the fragment ID in the high 32 bits of the physical row address.
row_address = cast(pa.UInt64Array, rb.column("_rowaddr"))
fragment_id = pa.compute.shift_right(row_address, pa.scalar(32, type=pa.uint64()))
if not keep_row_address:
rb = rb.drop_columns(["_rowaddr"])
rb = rb.append_column("fragment_id", fragment_id.cast(pa.int64()))
yield RecordBatch.from_arrow_record_batches([rb], rb.schema)._recordbatch

return _batches()
Expand Down Expand Up @@ -166,8 +193,11 @@ def __init__(
self._remaining_filters: list[PyExpr] | None = None
self._fragment_group_size = fragment_group_size
self._include_fragment_id = include_fragment_id
self._nearest = self._nearest_default_option()
self._enable_strict_filter_pushdown = get_context().daft_planning_config.enable_strict_filter_pushdown
base = self._ds.schema
if self._nearest is not None and "_distance" not in base.names:
base = base.append(pa.field("_distance", pa.float32()))
if self._include_fragment_id:
metadata: dict[bytes | str, bytes | str] | None = (
{k: v for k, v in base.metadata.items()} if base.metadata else None
Expand Down Expand Up @@ -198,7 +228,7 @@ def can_absorb_select(self) -> bool:

def supports_count_pushdown(self) -> bool:
"""Returns whether this scan operator supports count pushdown."""
return True
return self._nearest is None

def supported_count_modes(self) -> list[CountMode]:
"""Returns the count modes supported by this scan operator."""
Expand All @@ -216,10 +246,20 @@ def multiline_display(self) -> list[str]:
def push_filters(self, filters: list[PyExpr]) -> tuple[list[PyExpr], list[PyExpr]]:
pushed = []
remaining = []
post_scan_columns = set()
if self._nearest is not None:
post_scan_columns.add("_distance")
if self._include_fragment_id:
post_scan_columns.add("fragment_id")

for expr in filters:
try:
Expression._from_pyexpr(expr).to_arrow_expr()
expression = Expression._from_pyexpr(expr)
# Daft applies predicates on generated columns after the nearest scan.
if post_scan_columns and not post_scan_columns.isdisjoint(_ColumnVisitor().visit(expression)):
remaining.append(expr)
continue
expression.to_arrow_expr()
pushed.append(expr)
except NotImplementedError:
remaining.append(expr)
Expand Down Expand Up @@ -249,11 +289,12 @@ def to_scan_tasks(self, pushdowns: PyPushdowns) -> Iterator[ScanTask]:
if self._include_fragment_id:
required_columns.append("fragment_id")

nearest_option = self._nearest_default_option()
nearest_option = self._nearest

# Check if there is a count aggregation pushdown
if (
pushdowns.aggregation is not None
nearest_option is None
and pushdowns.aggregation is not None
and pushdowns.aggregation_count_mode() is not None
and pushdowns.aggregation_required_column_names()
and pushdowns.limit is None
Expand Down
137 changes: 116 additions & 21 deletions tests/io/lance/test_lance_vector_search.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
from __future__ import annotations

import inspect
import io

import lance
import numpy as np
import pyarrow as pa
import pytest

import daft
from daft import col
from daft_lance import merge_columns_df
from daft_lance.lance_scan import LanceDBScanOperator


Expand Down Expand Up @@ -97,7 +98,78 @@ def test_nearest_multi_fragment_global_k1(tmp_path_factory) -> None:
df = daft.read_lance(dataset_path, default_scan_options={"nearest": nearest})
result = df.select("id").to_pydict()

assert result["id"] == [2]
assert result == {"id": [2]}


def test_nearest_distance_projection(tmp_path_factory) -> None:
dataset_path = build_single_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [1.0, 0.0], "k": 2}
df = daft.read_lance(dataset_path, default_scan_options={"nearest": nearest})

assert df.to_arrow().schema.field("_distance").type == pa.float32()
assert df.select("_distance").sort("_distance").to_pydict() == {"_distance": [0.0, 1.0]}
assert df.select("id").sort("id").to_pydict() == {"id": [0, 1]}
assert df.count_rows() == 2
assert daft.read_lance(dataset_path).column_names == ["id", "vector"]


@pytest.mark.parametrize("include_fragment_id", [False, True])
@pytest.mark.parametrize("with_row_address", [False, True])
@pytest.mark.parametrize(("distance_range", "expected"), [((0.0, 2.0), [1, 1]), ((3.0, 4.0), [])])
def test_nearest_constant_projection(
tmp_path_factory: pytest.TempPathFactory,
include_fragment_id: bool,
with_row_address: bool,
distance_range: tuple[float, float],
expected: list[int],
) -> None:
dataset_path = build_single_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [1.0, 0.0], "k": 2, "distance_range": distance_range}
df = daft.read_lance(
dataset_path,
include_fragment_id=include_fragment_id,
default_scan_options={"nearest": nearest, "with_row_address": with_row_address},
)

assert df.select(daft.lit(1).alias("one")).to_pydict() == {"one": expected}


def test_nearest_distance_with_fragment_id(tmp_path_factory) -> None:
dataset_path = build_multi_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [0.0, 0.0], "k": 3}
df = daft.read_lance(dataset_path, include_fragment_id=True, default_scan_options={"nearest": nearest})

result = df.select("id", "fragment_id", "_distance").sort("_distance").to_pydict()
assert result["id"] == [2, 3, 0]
assert result["fragment_id"] == [1, 1, 0]
assert result["_distance"] == pytest.approx([0.01, 4.0, 10000.0])


def test_nearest_filter_fragment_id_after_search(tmp_path_factory) -> None:
dataset_path = build_multi_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [0.0, 0.0], "k": 3}
with daft.planning_config_ctx(enable_strict_filter_pushdown=True):
df = daft.read_lance(dataset_path, include_fragment_id=True, default_scan_options={"nearest": nearest})
result = df.where(col("fragment_id") == 0).select("id").to_pydict()

assert result == {"id": [0]}


def test_nearest_merge_distances_by_row_address(tmp_path_factory) -> None:
dataset_path = build_multi_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [0.0, 0.0], "k": 3}
df = daft.read_lance(
dataset_path,
include_fragment_id=True,
default_scan_options={"nearest": nearest, "with_row_address": True},
)
scores = df.select("fragment_id", "_rowaddr", col("_distance").alias("query_distance"))
merge_columns_df(scores, dataset_path)

table = lance.dataset(dataset_path).to_table(columns=["id", "query_distance"]).sort_by("id")
result = table["query_distance"].to_pylist()
assert result[1] is None
assert [result[0], *result[2:]] == pytest.approx([10000.0, 0.01, 4.0])


def test_nearest_global_single_scan_task(tmp_path_factory) -> None:
Expand Down Expand Up @@ -206,24 +278,6 @@ def test_nearest_with_projection(tmp_path_factory) -> None:


def test_nearest_distance_range(tmp_path_factory) -> None:
# distance_range is only available in newer versions of Lance. Skip the test
# if the installed version does not support it to keep the suite compatible
# with older environments.
import importlib

try:
lance_dataset_module = importlib.import_module("lance.dataset")
except Exception:
pytest.skip("lance.dataset module not available; skipping distance_range test")

ScannerBuilder = getattr(lance_dataset_module, "ScannerBuilder", None)
if ScannerBuilder is None:
pytest.skip("ScannerBuilder not available; distance_range not supported")

nearest_sig = inspect.signature(ScannerBuilder.nearest)
if "distance_range" not in nearest_sig.parameters:
pytest.skip("distance_range is not supported by the installed lance version")

dataset_path = build_multi_fragment_dataset(tmp_path_factory)

query = pa.array([0.0, 0.0], type=pa.float32())
Expand All @@ -241,6 +295,35 @@ def test_nearest_distance_range(tmp_path_factory) -> None:
assert ids == [2]


@pytest.mark.parametrize(
("upper", "expected"),
[
(10000.0, {"id": [3], "_distance": [4.0]}),
(
np.nextafter(np.float32(10000.0), np.float32(np.inf)).item(),
{"id": [3, 0], "_distance": [4.0, 10000.0]},
),
],
)
def test_nearest_distance_range_before_top_k(tmp_path_factory, upper, expected) -> None:
dataset_path = build_multi_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [0.0, 0.0], "k": 2, "use_index": False, "distance_range": (4.0, upper)}
df = daft.read_lance(dataset_path, default_scan_options={"nearest": nearest})

assert df.select("id", "_distance").sort("_distance").to_pydict() == expected


def test_nearest_hamming_distance_is_float32(tmp_path) -> None:
binary_vectors = pa.array([[0], [1], [3], [255]], type=pa.list_(pa.uint8(), 1))
lance.write_dataset(pa.table({"vector": binary_vectors}), tmp_path)
nearest = {"column": "vector", "q": pa.array([0], type=pa.uint8()), "k": 3, "metric": "hamming"}
df = daft.read_lance(tmp_path, default_scan_options={"nearest": nearest})

result = df.select("_distance").sort("_distance").to_arrow()
assert result.schema.field("_distance").type == pa.float32()
assert result["_distance"].to_pylist() == [0.0, 1.0, 2.0]


def test_nearest_with_prefilter_true(tmp_path_factory) -> None:
dataset_path = build_prefilter_dataset(tmp_path_factory)

Expand All @@ -255,12 +338,24 @@ def test_nearest_with_prefilter_true(tmp_path_factory) -> None:
default_scan_options={"nearest": nearest, "prefilter": True},
)
filtered = df.where(col("group") == 1)
result = filtered.select("id", "group").to_pydict()
result = filtered.select("id", "group", "_distance").to_pydict()

# With prefilter=True, Lance should restrict to group==1 before running nearest
# so the closest row in that group (id=1) is returned.
assert result["id"] == [1]
assert result["group"] == [1]
assert result["_distance"] == pytest.approx([0.04])


@pytest.mark.parametrize("strict_filter_pushdown", [False, True])
def test_nearest_distance_filter(tmp_path_factory, strict_filter_pushdown) -> None:
dataset_path = build_single_fragment_dataset(tmp_path_factory)
nearest = {"column": "vector", "q": [1.0, 0.0], "k": 2}
with daft.planning_config_ctx(enable_strict_filter_pushdown=strict_filter_pushdown):
df = daft.read_lance(dataset_path, default_scan_options={"nearest": nearest})
result = df.where(col("_distance") < 0.5).select("id").to_pydict()

assert result == {"id": [1]}


def test_nearest_with_prefilter_false(tmp_path_factory) -> None:
Expand Down