Skip to content

feat: add any_element filter for per-element predicates on list<struct> columns - #10901

Merged
BubbleCal merged 4 commits into
lance-format:mainfrom
sarwarbhuiyan:feat/any-element
Nov 11, 2026
Merged

BubbleCal merged 4 commits into
lance-format:mainfrom
sarwarbhuiyan:feat/any-element

Conversation

@sarwarbhuiyan

@sarwarbhuiyan sarwarbhuiyan commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

any_element is an experimental API. Its function name, call syntax, and predicate syntax are not finalized and may change incompatibly in future releases.

Adds any_element(list_column, 'predicate'), a filter function that is TRUE when some element of a list<struct> column satisfies the predicate, with every condition evaluated on that same element:

any_element(detections, 'label = ''car'' AND confidence > 0.9')

A filter can't express this today. Conditions on a list each apply to the list as a whole, so label = 'car' and confidence > 0.9 can be met by two different elements.

This is the first part of #10900. An index that answers the same function is planned as a follow-up.

Design

  • Predicate: a string literal over the element's fields, planned with Lance's filter planner against the element struct's fields.
  • Evaluation: the predicate runs once over all elements in the batch. The results fold back to one value per row, in SQL three-valued logic:
    • NULL for a null list;
    • TRUE if some element matches;
    • otherwise NULL if the predicate is NULL on some element (a null element reads as NULL in every field);
    • otherwise FALSE, which includes the empty list.
  • Validation at planning: return_field_from_args sees the predicate literal, so a predicate that refers to a column outside the element, or isn't boolean, fails before any data is read. Compiled predicates are cached per (predicate, element type).
  • Types: works for List and LargeList of structs.
  • Availability: registered in register_functions, so it's available in every binding's filter strings and through Substrait.

The function lives in lance-datafusion rather than lance-datafusion-exec, because it plans its predicate with Planner.

Tests

  • Unit tests in lance-datafusion:
    • same-element semantics, including a low-confidence car next to a high-confidence person;
    • null lists, null elements, null fields and empty lists;
    • NOT, and AND with a row-level column;
    • >=, IN, BETWEEN, IS NULL and OR inside the predicate;
    • List and LargeList;
    • clear errors for a column outside the element, a column that isn't a list<struct>, and a predicate that isn't boolean, including that they're raised at planning.
  • Substrait round trip.
  • Dataset tests in lance:
    • four fragments, one of them not covered by a BTree on a row-level column;
    • results checked against a reference evaluation, with and without the scalar index, and through count_rows;
    • the edge-case rows, and the error path.

Docs

Added to the filter push-down section of the read and write guide.

Part of #10900.

Lint: cargo fmt --all, and cargo clippy -p lance-datafusion -p lance --features lance-datafusion/substrait --tests -- -D warnings. The workspace-wide clippy run was not done locally, because no other crate is touched.

🤖 Generated with Claude Code

…t> columns

`any_element(list_column, 'predicate')` is TRUE when some element of a
list<struct> column satisfies the predicate, with every condition
evaluated on that same element. The predicate is a string literal over
the element's fields, planned with Lance's filter planner and checked
when the query is planned. It runs once per batch over all elements, and
the results fold back to rows with SQL three-valued logic.

Part of lance-format#10900.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added A-docs Documentation enhancement New feature or request labels Nov 10, 2026
@sarwarbhuiyan
sarwarbhuiyan marked this pull request as ready for review November 10, 2026 15:26

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Nov 10, 2026
Compiled element predicates are cached across queries, and optimizing a
predicate folds a stable function such as `now()` into a constant. A
cached predicate then kept the first query's timestamp. The predicate is
now checked before it is optimized, and a call to a function that is not
immutable is rejected when the query is planned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Nov 10, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

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.

✅ Gate recommendation: approve.

The cache finding is addressed: element predicates now reject stable and volatile functions before optimization, with the restriction documented. No remaining blockers found.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 10, 2026
A NULL element was masked only at its direct fields. A struct field kept
its children's values, and DataFusion's `get_field` returns a child as
stored, so `details.label` under a NULL element (or under a NULL
`details`) read the hidden value. Every struct's nulls are now pushed
down into its children before the predicate runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 10, 2026
@BubbleCal
BubbleCal merged commit 0259a51 into lance-format:main Nov 11, 2026
40 of 43 checks passed
BubbleCal pushed a commit that referenced this pull request Nov 11, 2026
…element (#10947)

## Summary

Filters can now use the lambda form for per-element predicates on
`list<struct>` columns:

```sql
array_any_match(detections, d -> d.label = 'car' AND d.confidence > 0.9)
```

While parsing the filter, Lance rewrites it to the `any_element` call
from #10901:

```sql
any_element(detections, 'label = ''car'' AND confidence > 0.9')
```

The two forms behave the same. The lambda never reaches DataFusion's
lambda planning, Substrait or execution, so the DataFusion gaps listed
in #10873 don't apply.

This is track 1 of #10873. General lambda support, track 2, still waits
on DataFusion.

## Design

- **Dialect:** `LanceDialect` enables `supports_lambda_functions`.
Without it, `->` parses as the JSON arrow operator, which Lance already
rejects, so no accepted filter changes meaning. `->>` is unaffected.
- **Rewrite:** `Planner::parse_filter` rewrites the parsed SQL before
planning it. `array_any_match` and its alias `any_match` with a
one-parameter lambda become `any_element(list, '<body>')`:
- `d.label`, `d.details.kind` and `d['my field']` become `label`,
`details.kind` and `` `my field` ``.
- The body is printed back as SQL and becomes the predicate literal, so
Lance's own literal handling applies inside it.
- The list argument must be a `list<struct>` column. Its type is checked
against the schema.
- **Clear errors** for anything `any_element` can't express:
- a column outside the element, or a bare `label` without the parameter;
    - the parameter itself (`d IS NOT NULL`);
    - a numeric subscript (`d[1]`);
    - two parameters;
    - a nested lambda;
    - an argument that isn't a `list<struct>`;
- a lambda in any other function, such as `array_filter`, or outside a
function.

## Tests

- **Dialect:** a lambda argument with a bare and a parenthesized
parameter, and that `->>` is not a lambda.
- **Rewrite:** 7 forms, including the alias, nested fields, subscripts,
a double-quoted string, and inside `NOT`, `AND` and another function
call. 9 error cases, each checked for a message that says what to
change.
- **Dataset**, on #10901's fixture:
- three lambda cases: the basic form, the alias with a subscript, and
`NOT` combined with an indexed column. Each is checked against a
reference evaluation with and without the scalar index, and through
`count_rows`.
    - two rejection cases, through the scanner and `count_rows`.

## Docs

A paragraph on the lambda form in the "Filtering on elements of a list
of structs" section of the read and write guide.

Part of #10873.

Lint: `cargo fmt --all`, and `cargo clippy --no-deps -p lance-datafusion
-p lance --features lance-datafusion/substrait --tests -- -D warnings`.
With dependencies included, clippy on arm64 currently fails in
`lance-encoding` (`unreachable_code` in `byte_stream_split.rs`, from
#10905). That code isn't touched here, and x86 CI doesn't hit it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
BubbleCal pushed a commit that referenced this pull request Nov 12, 2026
…ental) (#10949)

Add the persisted contract of the `listelement` scalar index, which
indexes fields inside the elements of a `list<struct>` column and
answers `any_element` filters (#10901). It is marked experimental.
Design discussion: #10948. Issue: #10900.

- **Details:** `ListElementIndexDetails` has these fields:
- `keys`: direct children of the element struct, at least one, no
repeats.
- `key_types`: Lance logical types. A reader declines the index when a
key field is gone or its type changed.
- `key_encoding`: an enum. `ARROW_ROW_V1` is the only defined value, and
UNSPECIFIED must not be used.
- `target_details` and `target_index_version`: the details and version
of the inner BTREE.

  All segments of one index share keys, types and encoding.
- **Files:** none of its own. The files are a standard BTREE over
`Binary`, given as PyArrow schemas, with one row per list element:
  - A null element is an all-null key tuple.
  - A null list is a single null key.
  - An empty list has no rows.

  The posting is the row address.
- **Key encoding:** Arrow row format, every key ascending, nulls first.
The admitted key types are the same as the `arrow_row` v1 set in #10358.
The byte layout is spelled out for fixed-width and variable-width types,
with a worked example, `("car", 0.5)`, that an implementation must
reproduce.
- **Queries:**
- **What the index can answer:** `=`, `IN` or `IS NULL` on the first
key, then equalities on further keys in order, then one range on the
next key.
- **Exact or rechecked:** the answer is exact when the index covers
every condition. Otherwise it's a superset that the scan rechecks with
`any_element`.
  - **NULL rows:** they are found for `NOT`.
- **Row addresses:** the index stores row addresses, so it joins the
row-address and eager-remap lists. On stable-row-ID tables the #10352
writer fence applies.

Library edits are limited to the generated protobuf source. The
implementation follows in a separate PR.

**Experimental:**
- **Forward compatible:** readers that don't know the type ignore the
index and scan.
- **Backward compatible:** nothing existing changes.
- **Droppable:** dropping the index never rewrites data.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
BubbleCal pushed a commit that referenced this pull request Nov 12, 2026
… elements (#10950)

## Summary

Adds `listelement`, an experimental built-in scalar index over fields
inside the elements of a `list<struct>` column. It answers `any_element`
filters (#10901) from the index, with every condition on the same
element:

```python
dataset.create_scalar_index(
    "detections",
    IndexConfig(index_type="listelement", parameters={"keys": ["label", "confidence"]}),
)
dataset.to_table(filter="any_element(detections, 'label = ''car'' AND confidence > 0.9')")
```

This is the second part of #10900. The format is specified in #10949,
and the design discussion is #10948.

**Depends on #10949.** This PR carries the identical
`protos/index.proto` change and generated source so that it compiles.
Those changes drop out when this branch is rebased after #10949 merges.

## Design

- **Training:** one entry per element.
- The key is the element's `keys` fields as a tuple, encoded with
Arrow's row format (ascending, nulls first), so the bytes sort like the
tuples.
    - The posting is the row address.
- Entries are sorted with spilling, and an ordinary BTREE is trained
over the `Binary` keys. The index wraps the BTREE the way the JSON index
wraps its target.
- **Search:** `visit_scalar_function` claims `any_element(<indexed
column>, '<literal>')`. The predicate is planned exactly as
`any_element` plans it, then with the tuple planner
(`plan_tuple_predicate`) over the keys.
- **Seeks:** an `=`, `IN` or `IS NULL` prefix, then one range on the
next key, becomes byte-range seeks in the BTREE.
- **Superset and recheck:** conditions the keys can't express, such as a
field that isn't a key, make the answer a superset. The scan then
rechecks it with `any_element`.
- **No first key, no index:** without a condition on the first key, the
index declines.
- **NULLs:** NULL lists, and elements on which the predicate is NULL,
are tracked, so `NOT` is exact.
- **Maintenance:** update encodes the new fragments the same way, then
defers to the BTREE. Remap defers to the BTREE.
- **Row addresses:** in `lance-table`, the index joins the row-address
and eager-remap lists. On stable-row-ID tables, the #10352 writer fence
applies and compaction remaps the index.
- **`lance-datafusion` API:** it exports `ANY_ELEMENT`,
`any_element_predicate` and `plan_element_predicate`, so the index plans
the same expression the scan evaluates. `lance-index` now depends on
`lance-datafusion` as a normal dependency; there's no cycle.

## Fix included

On a stable-row-ID table, `optimize_indices` dropped old entries of a
row-address index outside fragment 0. The generic update arm in
`merge_scalar_indices` only treated the JSON index as storing row
addresses, so it filtered row addresses against row IDs. That arm now
also covers this index. JSON behavior is unchanged.

## Tests

- **Index unit tests** (13):
- same-element trap, every range operator, `IN`, label-only prefix,
recheck;
    - NULL rows for `NOT`;
    - shapes the index declines;
- details round trip, and invalid parameters (no keys, unknown key,
repeated key, nested key type, unknown parameter, non-struct list);
- segment key mismatch, an all-null column, and the spec's encoding
bytes.
- **`lance-table`:** row-address and eager-remap classification.
- **Dataset tests:** #10901's fixture is extended rather than
duplicated.
- Every filter case, plus the edge-row and invalid-predicate tests, runs
with and without the index, checking the plan and whether it rechecks.
- New: declining when the first key isn't constrained; `fast_search`
plus `optimize_indices`; delete plus compaction remap, with and without
stable row IDs.

## Docs

The read and write guide covers creating the index and which filters it
answers, and the scalar indexing guide has a row for it. Both mark it
experimental.

## Not in this PR

- **Training memory:** there's no explicit budget. Like the JSON index,
training uses the default spill pool. At 100M elements the prototype
needed `LANCE_MEM_POOL_SIZE=8GiB`.
- **Merging segments** for distributed builds.
- **Fragment reuse index:** batch row-ID remapping isn't supported. Like
JSON, the index is reported incompatible on stable-row-ID tables that
use a fragment reuse index.

Closes #10900.

This conflicts with #10947 in the dataset scanner tests and the guide.
Whichever merges second will rebase.

Lint: `cargo fmt --all`, and `cargo clippy --no-deps -p lance-datafusion
-p lance-index -p lance-table -p lance --tests --benches --features
lance-datafusion/substrait -- -D warnings`. With dependencies included,
clippy on arm64 currently fails in `lance-encoding` (`unreachable_code`
from #10905), which this PR doesn't touch.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-docs Documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants