polars_pylance
polars_pylance
¶
Lazy, streaming Lance <-> Polars integration.
Reading gives a real LazyFrame: the optimizer pushes column
projections, filters and row limits into Lance, and batches are pulled only as
the streaming engine consumes them. Writing streams a query into Lance batch by
batch, so neither direction holds the dataset (or a whole fragment) in RAM.
>>> import polars as pl
>>> import polars_pylance as pll
>>> lf = pll.scan_lance("data.lance") # doctest: +SKIP
>>> pll.sink_lance(
... lf.filter(pl.col("score") > 0.9), "filtered.lance"
... ) # doctest: +SKIP
LanceScanOptions
dataclass
¶
Per-scan Lance reader tuning. Immutable and picklable.
Every field maps to the identically named argument of
lance.LanceDataset.scanner. None means "leave it to Lance".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int | None
|
Rows per record batch handed to Polars. |
25000
|
batch_readahead
|
int | None
|
Batches decoded ahead of the consumer, per fragment. |
1
|
fragment_readahead
|
int | None
|
Fragments read concurrently. |
1
|
io_buffer_size
|
int | None
|
Size of the Lance IO buffer, in bytes. This is the single biggest lever on peak memory; Lance's own default is 2 GiB. |
32 * MIB
|
scan_in_order
|
bool | None
|
Yield fragments in order. Out-of-order scanning is faster but lets more data accumulate in flight. |
True
|
use_scalar_index
|
bool | None
|
Whether pushed-down predicates may use scalar indices. |
None
|
late_materialization
|
bool | list[str] | None
|
Defer loading of large columns until after filtering. Either a bool for all columns or a list of column names. |
None
|
Source code in src/polars_pylance/_options.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
throughput
classmethod
¶
throughput(**overrides: Any) -> LanceScanOptions
Restore Lance's own aggressive read-ahead, for when RAM is plentiful.
Roughly 1.6x the peak memory of the defaults on a large-payload scan, in exchange for more IO parallelism.
Source code in src/polars_pylance/_options.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
to_scan_kwargs
¶
Render as scanner() keyword arguments, omitting unset fields.
Source code in src/polars_pylance/_options.py
62 63 64 65 66 67 68 | |
LanceFilter
dataclass
¶
A Lance SQL filter lowered from a Polars predicate.
Attributes:
| Name | Type | Description |
|---|---|---|
sql |
str
|
The filter string, ready for |
exact |
bool
|
True when the filter keeps exactly the rows the predicate keeps. False when part of the predicate was dropped, leaving a superset; the caller must then keep evaluating the predicate. |
Source code in src/polars_pylance/_predicate.py
130 131 132 133 134 135 136 137 138 139 140 141 142 | |
LanceScanSpec
dataclass
¶
Everything needed to reproduce a scan, and nothing that cannot be pickled.
Holding a URI rather than an open lance.LanceDataset is what lets a
scan be serialized into a query plan and executed elsewhere, which is the
prerequisite for Polars Cloud.
The fields are the arguments of scan_lance, which
documents them, with two differences: a Polars-expression prefilter is held
serialized in prefilter_expr, and fragment_ids is the resolved list that
fragments selected.
Source code in src/polars_pylance/_scan.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
is_search
property
¶
is_search: bool
Whether the scan ranks the dataset rather than reading it in order.
polars_schema
¶
polars_schema(dataset: LanceDataset | None = None) -> Schema
Full output schema, including any Lance-generated columns.
Source code in src/polars_pylance/_scan.py
138 139 140 141 142 143 | |
iter_frames
¶
iter_frames(dataset: LanceDataset, *, projection: Sequence[str] | None = None, filter: str | None = None, limit: int | None = None, offset: int | None = None, prefilter: bool = False) -> Iterator[DataFrame]
Stream projection out of Lance as Polars frames.
Lazy by construction: nothing is read until the consumer pulls, and dropping the generator early stops the scan.
Source code in src/polars_pylance/_scan.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
to_lance_filter
¶
to_lance_filter(predicate: Expr, *, max_in_list: int = MAX_IN_LIST, schema: Schema | None = None) -> LanceFilter | None
Lower predicate to a Lance SQL filter, or None if nothing can be pushed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicate
|
Expr
|
Any boolean Polars expression, however deeply nested. |
required |
max_in_list
|
int
|
Largest |
MAX_IN_LIST
|
schema
|
Schema | None
|
The scanned schema, when the caller has it. Column types, down to
struct fields and list elements, decide whether a literal is compared as
a float and of which width, and whether Without one, a column may be a float of either width, so numeric predicates decline. |
None
|
Examples:
>>> import polars as pl
>>> from polars_pylance import to_lance_filter
>>> to_lance_filter(pl.col("cat").str.starts_with("b"))
LanceFilter(sql="starts_with(`cat`, 'b')", exact=True)
>>> schema = pl.Schema({"cat": pl.String, "id": pl.Int64})
>>> to_lance_filter(
... pl.col("cat").str.extract(r"(\d+)").is_null() & (pl.col("id") > 3),
... schema=schema,
... )
LanceFilter(sql='(`id` > 3)', exact=False)
>>> to_lance_filter(pl.col("id") > 3) is None
True
>>> to_lance_filter(pl.col("id").hash() > 3) is None
True
Source code in src/polars_pylance/_predicate.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
scan_lance
¶
scan_lance(source: str | Path | LanceDataset, *, version: int | str | None = None, storage_options: dict[str, str] | None = None, options: LanceScanOptions | None = None, nearest: dict[str, Any] | None = None, full_text_query: str | dict[str, Any] | None = None, prefilter: str | Expr | None = None, with_row_id: bool = False, with_row_address: bool = False, fragments: Sequence[int] | None = None, predicate_pushdown: bool = True) -> LazyFrame
Lazily read a Lance dataset as a Polars LazyFrame.
Nothing is read when this returns. Column projections, filters and row
limits are pushed into Lance; batches are pulled only as the query consumes
them, so .head() stops the scan early. Use engine="streaming" when
collecting: the in-memory engine materialises the whole result and gives up
the memory advantage.
The filter becomes a Lance SQL filter, so string functions, arithmetic, temporal
parts, long is_in lists and list or struct access reach the scanner, none of which
Polars' own PyArrow lowering passes on. A predicate that only partly translates is
pushed as far as it goes and finished in Polars.
to_lance_filter shows what one lowers to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | LanceDataset
|
Dataset URI, path, or an open |
required |
version
|
int | str | None
|
Read a specific version (or tag) instead of the latest. |
None
|
storage_options
|
dict[str, str] | None
|
Object-store credentials and settings, passed to Lance. |
None
|
options
|
LanceScanOptions | None
|
Reader tuning; see
|
None
|
nearest
|
dict[str, Any] | None
|
Lance vector-search specification, e.g. |
None
|
full_text_query
|
str | dict[str, Any] | None
|
Lance full-text search query. Adds a |
None
|
prefilter
|
str | Expr | None
|
Restrict which rows |
None
|
with_row_id
|
bool
|
Include Lance's stable |
False
|
with_row_address
|
bool
|
Include Lance's physical |
False
|
fragments
|
Sequence[int] | None
|
Restrict the scan to these fragment ids. See
|
None
|
predicate_pushdown
|
bool
|
Set to False to keep filtering entirely in Polars. Worth trying if you depend on Polars' null comparison semantics, which differ from SQL's. |
True
|
Examples:
>>> lf = scan_lance("s3://bucket/data.lance")
>>> lf.filter(pl.col("label").is_in([3, 7])).select("id", "score").collect(
... engine="streaming"
... )
Source code in src/polars_pylance/_scan.py
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
scan_lance_fragments
¶
scan_lance_fragments(source: str | Path | LanceDataset, *, n_shards: int | None = None, **kwargs: Any) -> list[LazyFrame]
Return one LazyFrame per fragment (or per shard) of a Lance dataset.
Lance fragments are the natural unit of parallelism: each is a self-contained set of
files. Use this to fan a scan out over threads, processes or workers, then recombine
with polars.concat. Also the manual parallelisation route if a
distributed planner refuses a Python scan node.
Fragment ids only mean something within one version, so every shard is pinned to
the version the ids were read from, which is the latest (or version) at the time
of this call. A later write then cannot hand a shard another version's fragment
under the same id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | LanceDataset
|
Dataset URI, path, or an open |
required |
n_shards
|
int | None
|
Group the fragments into this many LazyFrames instead of returning one each. Fragments are dealt round-robin, so shards stay even when the last fragment is a short one. Asking for more shards than there are fragments yields one fragment per shard, not empty shards. |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Examples:
>>> shards = scan_lance_fragments("data.lance", n_shards=4)
>>> pl.concat(shards).collect(engine="streaming")
Source code in src/polars_pylance/_scan.py
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 | |
commit_lance_fragments
¶
commit_lance_fragments(uri: str, fragments: list[Any], *, schema: Schema, mode: Literal['create', 'overwrite', 'append'] = 'create', storage_options: dict[str, str] | None = None) -> LanceDataset
Publish already-written fragments as one dataset version.
The second half of a distributed write: the fragments' data files are on storage but
no manifest references them, so nothing has been published yet. This is the single
commit that makes them a version, whether they were written by threads
(write_lance_fragments) or by Polars Cloud
workers (sink_lance_remote).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Destination dataset URI or path. |
required |
fragments
|
list[Any]
|
The |
required |
schema
|
Schema
|
Schema to install on the new version. Used by |
required |
mode
|
Literal['create', 'overwrite', 'append']
|
|
'create'
|
storage_options
|
dict[str, str] | None
|
Object-store credentials and settings, passed to Lance. |
None
|
Returns:
| Type | Description |
|---|---|
LanceDataset
|
lance.LanceDataset: The dataset at the version this commit created. |
Source code in src/polars_pylance/_sink.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
sink_lance
¶
sink_lance(lf: LazyFrame | DataFrame, target: str | Path | LanceDataset, *, mode: WriteMode = 'create', on: str | list[str] | None = None, chunk_size: int = DEFAULT_CHUNK_SIZE, engine: EngineType = 'streaming', lazy: bool = False, **lance_write_kwargs: Any) -> LanceDataset | LazyFrame
Write a Polars DataFrame or stream a LazyFrame into a Lance dataset.
A LazyFrame query is executed in batches and handed to Lance as it goes, so its result is never materialised in full. A DataFrame is accepted for convenience, but is already materialised before this function is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lf
|
LazyFrame | DataFrame
|
The eager DataFrame or lazy query to write. |
required |
target
|
str | Path | LanceDataset
|
Destination URI, path, or an existing |
required |
mode
|
WriteMode
|
|
'create'
|
on
|
str | list[str] | None
|
Join key(s) for |
None
|
chunk_size
|
int
|
Rows buffered per batch handed to Lance. |
DEFAULT_CHUNK_SIZE
|
engine
|
EngineType
|
Polars engine. Leave at |
'streaming'
|
lazy
|
bool
|
Return a LazyFrame that performs the write when collected, instead of writing immediately, so the Lance write can sit inside a larger deferred plan. Collecting it yields a one-row summary of what was written. |
False
|
**lance_write_kwargs
|
Any
|
Passed through to |
{}
|
Returns:
| Type | Description |
|---|---|
LanceDataset | LazyFrame
|
The written |
LanceDataset | LazyFrame
|
|
Examples:
>>> query = lf.filter(pl.col("ok"))
>>> sink_lance(query, "out.lance", mode="overwrite")
Source code in src/polars_pylance/_sink.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
write_lance_fragments
¶
write_lance_fragments(lazyframes: Iterable[LazyFrame], target: str | Path, *, mode: Literal['create', 'overwrite', 'append'] = 'create', max_workers: int | None = None, chunk_size: int = DEFAULT_CHUNK_SIZE, engine: EngineType = 'streaming', arrow_schema: Schema | None = None, **lance_write_kwargs: Any) -> LanceDataset
Write several LazyFrames as Lance fragments in parallel, then commit once.
This is the distributed write shape: every shard streams into its own fragment files
independently, and a single commit at the end makes them one dataset version. Pair
with scan_lance_fragments to get the
shards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lazyframes
|
Iterable[LazyFrame]
|
One query per shard. All must produce the same schema. |
required |
target
|
str | Path
|
Destination URI or path. |
required |
mode
|
Literal['create', 'overwrite', 'append']
|
|
'create'
|
max_workers
|
int | None
|
Threads used to write shards. Defaults to one per shard. |
None
|
chunk_size
|
int
|
Rows buffered per batch handed to Lance. |
DEFAULT_CHUNK_SIZE
|
engine
|
EngineType
|
Polars engine. Leave at |
'streaming'
|
arrow_schema
|
Schema | None
|
Schema to write. Inferred from the first shard when omitted. |
None
|
**lance_write_kwargs
|
Any
|
Passed to |
{}
|
Examples:
>>> shards = scan_lance_fragments("in.lance")
>>> write_lance_fragments(
... [s.filter(pl.col("ok")) for s in shards], "out.lance"
... )
Source code in src/polars_pylance/_sink.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
write_lance_shard
¶
write_lance_shard(shard: LazyFrame, target: str | Path, *, mode: Literal['create', 'overwrite', 'append'] = 'create', chunk_size: int = DEFAULT_CHUNK_SIZE, engine: EngineType = 'streaming', arrow_schema: Schema | None = None, **lance_write_kwargs: Any) -> list[FragmentMetadata]
Write one LazyFrame as Lance fragment files, without committing.
The single-shard primitive behind
write_lance_fragments, factored out
so distributed workers can call the same code the threaded path calls. It
streams the query into fragment files and returns their metadata, publishing
nothing: the caller commits with
commit_lance_fragments once every
shard is done.
Everything it takes is small and picklable -- a lazy query, a URI, a schema -- so a scheduler ships kilobytes per shard while the data itself moves only between the worker and Lance storage. The returned metadata is likewise small enough to send back to the coordinator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shard
|
LazyFrame
|
The query to write. All shards committed together must produce the same schema. |
required |
target
|
str | Path
|
Destination URI or path. Workers writing to the same dataset must address it identically. |
required |
mode
|
Literal['create', 'overwrite', 'append']
|
|
'create'
|
chunk_size
|
int
|
Rows buffered per batch handed to Lance. |
DEFAULT_CHUNK_SIZE
|
engine
|
EngineType
|
Polars engine. Leave at |
'streaming'
|
arrow_schema
|
Schema | None
|
Schema to write. Inferred from the shard when omitted; pass the coordinator's schema so every worker writes identically. |
None
|
**lance_write_kwargs
|
Any
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
list[FragmentMetadata]
|
The |
Examples:
>>> shards = scan_lance_fragments("in.lance")
>>> write_lance_shard(
... shards[0].filter(pl.col("ok")), "out.lance"
... )
Source code in src/polars_pylance/_sink.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |