# Python With Quixote and PyArrow installed, run `examples/getting_started.py` to filter a nullable Arrow column, compute a total and stream the selected values. ``` """Run with an installed Quixote wheel and the optional PyArrow consumer.""" import pyarrow as pa import quixote as qe def run(): data = pa.record_batch({"x": pa.array([1, 2, None, 600, 3], type=pa.int64())}) with qe.Runtime(cpu_threads=2, io_threads=1, memory_limit="4 MiB") as runtime: with qe.Session(runtime, query_memory_limit="1 MiB") as session: query = session.from_arrow(data).filter(qe.col("x") < 512).select( (qe.col("x") + 10).alias("value")) print(query.explain()) result = query.select(qe.col("value").sum().alias("total"), qe.count_rows().alias("rows")).collect() with query.stream() as stream: retained = pa.RecordBatchReader.from_stream(stream).read_all() assert retained.to_pydict() == {"value": [11, 12, 13]} table = pa.table(result) assert table.to_pydict() == {"total": [36], "rows": [3]} return table if __name__ == "__main__": print(run()) ``` The filter keeps 1, 2 and 3. Adding 10 gives 11, 12 and 13, for a total of 36. The example reads the result after the session and runtime close. ## Group and sort To find the two regions with the highest average sale, group by region and sort the averages. The second sort key breaks ties by region name. ``` """Find the two regions with the highest average sale.""" import pyarrow as pa import quixote as qe sales = pa.record_batch({ "region": ["west", "east", "east", "west", "north"], "amount": [12.0, 5.0, 15.0, None, 7.0], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: averages = session.from_arrow(sales).group_by("region").agg( qe.col("amount").avg().alias("mean_sale") ) ranked = averages.sort("mean_sale", "region", descending=[True, False]).limit(2) result = ranked.collect() table = pa.table(result) assert table.to_pydict() == {"region": ["west", "east"], "mean_sale": [12.0, 10.0]} print(table) ``` Use `qe.col("sale").stddev_samp()` or `.var_samp()` for a sample. Use `.stddev_pop()` or `.var_pop()` for the whole population. To keep an arbitrary non-null label per group, include `qe.col("label").any_value()` in `agg()`. You can also filter, select or aggregate again after grouping. Operations run in their written order. Filtering before a limit can give a different result from limiting before the filter. To page through sales by amount, choose a fallback for missing payments, round the amount, then skip the first row in sort order. ``` """Show the second sale by amount, with its calendar day and rounded magnitude.""" from datetime import datetime import pyarrow as pa import quixote as qe sales = pa.record_batch({ "sold": pa.array([datetime(1969, 12, 31, 22), datetime(2025, 1, 4, 15)], pa.timestamp("us")), "paid": pa.array([None, -12.25], pa.float64()), "quoted": [15.75, 18.00], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: amount = qe.coalesce(qe.col("paid"), qe.col("quoted")) query = session.from_arrow(sales).select( qe.col("sold").date_trunc("day").alias("day"), amount.abs().round(1).alias("amount"), ) page = pa.table(query.sort("amount", descending=True).limit(1, offset=1).collect()) assert page.to_pydict() == {"day": [datetime(2025, 1, 4)], "amount": [12.3]} print(page) ``` ## Profile a query See [Profile a query](<../profiling/index.md>) for operator timings, memory use and execution traces. ## Build and run a query - Use `session.from_arrow()` with an Arrow C Array or C Stream producer. A PyArrow RecordBatch can run repeatedly. Import a PyArrow Table again for a separate execution because it supplies a single-use stream. - Pass names or expressions to `select()`. Use `qe.col("amount")` to refer to a column and `.alias("name")` to name an output. Use `datetime.date` and `decimal.Decimal` for date and exact decimal literals. Pass `bytes` to `qe.lit()` for Binary. A naive or UTC `datetime.datetime` creates a microsecond timestamp. Use `qe.float32` in casts and `qe.lit_float32(1.5)` for a single-precision literal. A Python float passed to `qe.lit` uses Float64. A Python integer passed to `qe.lit` uses Int64. Use typed literals such as `qe.lit_int8(-128)` and `qe.lit_uint64(2**64 - 1)`. Cast with descriptors such as `qe.uint16`. Integer membership lists accept the full UInt64 range. Use `qe.Type.date64()`, `qe.Type.large_utf8()`, `qe.Type.large_binary()`, `qe.Type.binary()`, `qe.Type.timestamp("us")` or `qe.Type.timestamp("us", tz="UTC")` to compare schema descriptors. - Use `qe.col("ordered").date_add_days(7)` to add a week and `qe.col("shipped").date_diff_days(qe.col("ordered"))` to count elapsed days. Extract calendar parts with `.month()` and `.day()`. - Use `qe.col("name").trim().lower()` to remove surrounding spaces and lowercase ASCII letters. Chain `.concat(other)` to append another string. Use `.replace(old, new)` to replace literal text and `.split_part("/", -1)` to take the last field of a path. To extract the digits from a label such as `"item-42"`, use `qe.col("label").regexp_extract(r"item-(\d+)", 1)`. See [Behavior and limits](<../semantics/index.md>) for whitespace and length rules. - Use `qe.null_if(qe.col("amount"), 0)` to treat zero as missing. Use `qe.col("amount") % 10` to compute a remainder. - Combine parenthesized comparisons with `&`, `|` and `~`. - Read `query.schema` or call `query.explain()` to inspect a plan before execution. Call `collect()` or `stream()` to read results. Use `sink_parquet(path)` or `write_parquet(path)` to write them to a file. - Read a collected result with `pa.table(result)` or `polars.from_arrow(result)`. To read incrementally, use `with query.stream() as stream:` and pass each batch to `pa.record_batch(batch)`. The context manager closes the stream even if you stop early. Set `memory_limit` on an execution to override the session's query budget. Byte limits accept integers or strings such as `"64 MiB"`. Set `max_contexts=1` to run with one execution context. The wheel includes typed Python signatures. Read `runtime.stats()` after collection to see how much memory the query used. `peak_working_bytes`, `peak_reserved_bytes` and `peak_held_bytes` give the maximum working, reserved and caller-held bytes over the runtime's lifetime. Use a fresh runtime to measure one query. ## Window functions Rank sales within each region and show the cumulative total on every sale. The two sales tied for first place both include the full tie in their total. ``` """Rank sales and keep a running total within each region.""" import pyarrow as pa import quixote as qe sales = pa.record_batch({ "region": ["east", "west", "east", "east"], "amount": [10, 8, 10, 5], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: query = session.from_arrow(sales).window( qe.rank().alias("place"), qe.col("amount").sum().alias("total"), partition_by="region", order_by=qe.SortKey("amount", descending=True), ) result = pa.table(query.sort("region", "place").collect()) assert result["place"].to_pylist() == [1, 1, 3, 1] assert result["total"].to_pylist() == [20, 20, 25, 8] print(result) ``` Use `qe.col("amount").lag(default=0)` to read the preceding sale in the same region. Chain another `window()` to change the partition or ordering. ## Disk spilling Pass `spill_directory` to `Runtime` to let sorts, grouped aggregates and set operations write temporary runs. For example, `Runtime(spill_directory=path, max_spill_bytes="16 GiB")` caps live runs across queries. ## Compare two query results Use `left.intersect(right)` for rows in both queries and `left.except_(right)` for rows found only on the left. To compare counts as well, pass `all=True`. For example, `actual.except_(expected, all=True)` returns the extra copies in `actual`. ## Count distinct values Use `distinct()` to keep one copy of each row. Use `count_distinct()` to count different non-null values in a group. Omit the keys in `group_by().agg(...)` to count across the whole input. ``` """Count suppliers per part, including parts with no known supplier.""" import pyarrow as pa import quixote as qe offers = pa.record_batch({"part": [1, 1, 1, 2], "supplier": ["A", "A", "B", None]}) with qe.Runtime() as runtime, qe.Session(runtime) as session: query = session.from_arrow(offers) assert query.distinct().collect().num_rows == 3 counts = query.group_by("part").agg(qe.col("supplier").count_distinct().alias("suppliers")) result = pa.table(counts.sort("part").collect()) assert result.to_pydict() == {"part": [1, 2], "suppliers": [2, 0]} print(result) ``` ## Nested Arrow columns Use `qe.col("order").struct_field("items")` to select a struct field. List expressions support `list_length()`, `list_element(index)` and `list_contains(value)`. Build a struct with ordered keyword arguments, such as `qe.struct_(id=qe.col("id"), items=qe.col("items"))`. Inspect child descriptors through `type.fields`, `list_type.value_field` and `list_type.value_type`. Construct them with `qe.Type.struct([qe.Field("id", qe.Type.int64)])`, `qe.Type.list_(item)` and `qe.Type.large_list(item)`. Declare a map with `qe.Type.map_(key_type, value_type, keys_sorted=True)`. Inspect `key_field`, `item_field` and `keys_sorted` on the type. Use `qe.col("labels").map_get("region")` to look up a value. Use `map_keys()`, `map_values()` or `list_length()` to get the keys, values or entry count.