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 69 70 71 72 73 74 75 76 77 | |
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 | |
replace
¶
replace(**overrides: Any) -> LanceScanOptions
Return a copy with overrides applied.
Source code in src/polars_pylance/_options.py
62 63 64 65 66 67 68 69 | |
to_scan_kwargs
¶
Render as scanner() keyword arguments, omitting unset fields.
Source code in src/polars_pylance/_options.py
71 72 73 74 75 76 77 | |
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
126 127 128 129 130 131 132 133 134 135 136 137 138 | |
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: prefilter has already been lowered
to a Lance SQL string, and fragment_ids is the resolved list that
fragments selected.
Source code in src/polars_pylance/_scan.py
50 51 52 53 54 55 56 57 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 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 | |
arrow_schema
¶
arrow_schema(dataset: LanceDataset | None = None) -> Schema
Full output schema, including any Lance-generated columns.
Source code in src/polars_pylance/_scan.py
121 122 123 124 | |
iter_frames
¶
iter_frames(dataset: LanceDataset, *, projection: Sequence[str] | None = None, filter: str | None = None, limit: 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
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 | |
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. Used to drop a promotion the
schema shows is a no-op, since a |
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)
>>> to_lance_filter(
... pl.col("cat").str.extract(r"(\d+)").is_null() & (pl.col("id") > 3)
... )
LanceFilter(sql='(`id` > 3)', exact=False)
>>> to_lance_filter(pl.col("id").hash() > 3) is None
True
Source code in src/polars_pylance/_predicate.py
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 | |
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 is_in, string functions, arithmetic,
temporal parts and list or struct access reach the scanner, none of which a PyArrow
expression can carry. A predicate that only partly translates is pushed as far as it
goes and finished in Polars. to_lance_filter
shows what a given 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
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | |
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.
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
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
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
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | |
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
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 | |
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
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
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
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |