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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# /// script
|
2 |
+
# requires-python = ">=3.8"
|
3 |
+
# dependencies = [
|
4 |
+
# "marimo",
|
5 |
+
# "faker==37.1.0",
|
6 |
+
# "scipy==1.13.1",
|
7 |
+
# "numpy==2.0.2",
|
8 |
+
# "numba==0.60.0",
|
9 |
+
# "polars==1.26.0",
|
10 |
+
# "matplotlib==3.9.4",
|
11 |
+
# "statsmodels",
|
12 |
+
# "pandas==2.2.3",
|
13 |
+
# ]
|
14 |
+
# ///
|
15 |
+
|
16 |
+
import marimo
|
17 |
+
|
18 |
+
__generated_with = "0.12.6"
|
19 |
+
app = marimo.App(width="medium")
|
20 |
+
|
21 |
+
|
22 |
+
@app.cell(hide_code=True)
|
23 |
+
def _(mo):
|
24 |
+
mo.md(
|
25 |
+
r"""
|
26 |
+
# Lazy Execution (a.k.a. the Lazy API)
|
27 |
+
|
28 |
+
Author: [Deb Debnath](https://github.com/debajyotid2)
|
29 |
+
"""
|
30 |
+
)
|
31 |
+
return
|
32 |
+
|
33 |
+
|
34 |
+
@app.cell(hide_code=True)
|
35 |
+
def _():
|
36 |
+
import random
|
37 |
+
import re
|
38 |
+
import time
|
39 |
+
from datetime import datetime, timedelta, timezone
|
40 |
+
from typing import Generator
|
41 |
+
import numba
|
42 |
+
import numpy as np
|
43 |
+
import polars as pl
|
44 |
+
import pandas as pd
|
45 |
+
import scipy.special as spl
|
46 |
+
import scipy.stats as st
|
47 |
+
import matplotlib.pyplot as plt
|
48 |
+
from faker import Faker
|
49 |
+
return (
|
50 |
+
Faker,
|
51 |
+
Generator,
|
52 |
+
datetime,
|
53 |
+
np,
|
54 |
+
numba,
|
55 |
+
pd,
|
56 |
+
pl,
|
57 |
+
plt,
|
58 |
+
random,
|
59 |
+
re,
|
60 |
+
spl,
|
61 |
+
st,
|
62 |
+
time,
|
63 |
+
timedelta,
|
64 |
+
timezone,
|
65 |
+
)
|
66 |
+
|
67 |
+
|
68 |
+
@app.cell(hide_code=True)
|
69 |
+
def _(mo):
|
70 |
+
mo.md(
|
71 |
+
r"""
|
72 |
+
We saw the benefits of lazy evaluation when we learned about the Expressions API in Polars. Lazy execution is further extended as a philosophy by the Lazy API. It offers significant performance enhancements over eager (immediate) execution of queries and is one of the reasons why Polars is faster at working with large (GB scale) datasets than other libraries. The lazy API optimizes the full query pipeline instead of executing individual queries optimally, unlike eager execution. Some of the advantages of using the Lazy API over eager execution include
|
73 |
+
|
74 |
+
- automatic query optimization with the query optimizer.
|
75 |
+
- ability to process datasets larger than memory using streaming.
|
76 |
+
- ability to catch schema errors before data processing.
|
77 |
+
"""
|
78 |
+
)
|
79 |
+
return
|
80 |
+
|
81 |
+
|
82 |
+
@app.cell(hide_code=True)
|
83 |
+
def _(mo):
|
84 |
+
mo.md(
|
85 |
+
r"""
|
86 |
+
## Setup
|
87 |
+
|
88 |
+
For this notebook, we are going to work with logs from an Apache/Nginx web server - these logs contain useful information that can be utilized for performance optimization, security monitoring, etc. Such logs comprise of entries that look something like this:
|
89 |
+
|
90 |
+
```
|
91 |
+
10.23.97.15 - - [05/Jul/2024:11:35:05 +0000] "GET /index.html HTTP/1.1" 200 1342 "https://www.example.com" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/528.32 (KHTML, like Gecko) Chrome/19.0.1220.985 Safari/528.32" "-"
|
92 |
+
```
|
93 |
+
|
94 |
+
Different parts of the entry mean different things:
|
95 |
+
|
96 |
+
- `10.23.97.15` is the client IP address.
|
97 |
+
- `- -` represent identity and username of the client, respectively and are typically unused.
|
98 |
+
- `05/Jul/2024:11:35:05 +0000` indicates the timestamp for the request.
|
99 |
+
- `"GET /index.html HTTP/1.1"` represents the HTTP method, requested resource and the protocol version for HTTP, respectively.
|
100 |
+
- `200 1342` mean the response status code and size of the response in bytes, respectively
|
101 |
+
- `"https://www.example.com"` is the "referer", or the webpage URL that brought the client to the resource.
|
102 |
+
- `"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/528.32 (KHTML, like Gecko) Chrome/19.0.1220.985 Safari/528.32"` is the "User agent" or the details of the client device making the request (including browser version, operating system, etc.)
|
103 |
+
|
104 |
+
Normally, you would get your log files from a server that you have access to. In our case, we will generate fake data to simulate log records. We will simulate 7 days of server activity with 90,000 recorded lines.
|
105 |
+
|
106 |
+
///Note
|
107 |
+
1. If you are interested in the process of generating fake log entries, unhide the code cells immediately below the next one.
|
108 |
+
2. You can adjust the size of the dataset by resetting the `num_log_lines` variables to a size of your choice. It may be helpful if the data takes a long time to generate.
|
109 |
+
"""
|
110 |
+
)
|
111 |
+
return
|
112 |
+
|
113 |
+
|
114 |
+
@app.cell
|
115 |
+
def _():
|
116 |
+
num_log_lines = 90_000 # Number of log entries to simulate
|
117 |
+
return (num_log_lines,)
|
118 |
+
|
119 |
+
|
120 |
+
@app.cell(hide_code=True)
|
121 |
+
def _(Faker, datetime, np, random, timedelta, timezone):
|
122 |
+
def generate_log_line(*,
|
123 |
+
faker: Faker,
|
124 |
+
tz: timezone,
|
125 |
+
sleep: int,
|
126 |
+
otime: datetime,
|
127 |
+
rng: np.random.Generator,
|
128 |
+
resources: list[str],
|
129 |
+
user_agents: dict[str, float],
|
130 |
+
responses: dict[str, float],
|
131 |
+
verbs: dict[str, float]) -> str:
|
132 |
+
""""""
|
133 |
+
otime += timedelta(seconds=sleep) if sleep > 0 else timedelta(seconds=random.randint(30, 300))
|
134 |
+
dt = otime.strftime('%d/%b/%Y:%H:%M:%S')
|
135 |
+
|
136 |
+
ip, referer = faker.ipv4(), faker.uri()
|
137 |
+
vrb = rng.choice(list(verbs.keys()), p=list(verbs.values()))
|
138 |
+
|
139 |
+
uri = rng.choice(resources)
|
140 |
+
if uri.find("apps") > 0:
|
141 |
+
uri += str(rng.integers(1000, 10000))
|
142 |
+
|
143 |
+
resp = rng.choice(list(responses.keys()), p=list(responses.values()))
|
144 |
+
byte_size = int(rng.normal(5000, 50))
|
145 |
+
useragent = rng.choice(list(user_agents.keys()), p=list(user_agents.values()))()
|
146 |
+
latency = rng.lognormal(-3, 0.8) + 0.5 * rng.uniform()
|
147 |
+
|
148 |
+
return f'{ip} - - [{dt} {tz}] "{vrb} {uri} HTTP/1.0" {resp} {byte_size} {latency:.3f} "{referer}" "{useragent}"'
|
149 |
+
return (generate_log_line,)
|
150 |
+
|
151 |
+
|
152 |
+
@app.cell(hide_code=True)
|
153 |
+
def _(Faker, datetime, np, num_log_lines, time):
|
154 |
+
tz = datetime.now().strftime('%z')
|
155 |
+
|
156 |
+
faker = Faker()
|
157 |
+
|
158 |
+
timestr = time.strftime("%Y%m%d-%H%M%S")
|
159 |
+
otime = datetime.now()
|
160 |
+
|
161 |
+
responses = dict(zip(["200", "404", "500", "301", "403", "502"],
|
162 |
+
[0.82, 0.04, 0.02, 0.04, 0.05, 0.03]))
|
163 |
+
|
164 |
+
verbs = dict(zip(["GET", "POST", "DELETE", "PUT"], [0.6, 0.1, 0.1, 0.2]))
|
165 |
+
|
166 |
+
resources = ["/list", "/wp-content", "/wp-admin", "/explore", "/search/tag/list", "/app/main/posts",
|
167 |
+
"/posts/posts/explore", "/apps/cart.jsp?appID="]
|
168 |
+
|
169 |
+
user_agents = dict(zip([faker.firefox, faker.chrome, faker.safari, faker.internet_explorer, faker.opera],
|
170 |
+
[0.5, 0.3, 0.1, 0.05, 0.05]))
|
171 |
+
|
172 |
+
sleep = 7 * 24 * 60 * 60 // num_log_lines # Set interval for 7 days of log data
|
173 |
+
|
174 |
+
rng = np.random.default_rng(seed=int(time.time()))
|
175 |
+
return (
|
176 |
+
faker,
|
177 |
+
otime,
|
178 |
+
resources,
|
179 |
+
responses,
|
180 |
+
rng,
|
181 |
+
sleep,
|
182 |
+
timestr,
|
183 |
+
tz,
|
184 |
+
user_agents,
|
185 |
+
verbs,
|
186 |
+
)
|
187 |
+
|
188 |
+
|
189 |
+
@app.cell(hide_code=True)
|
190 |
+
def _(
|
191 |
+
Generator,
|
192 |
+
faker,
|
193 |
+
generate_log_line,
|
194 |
+
otime,
|
195 |
+
re,
|
196 |
+
resources,
|
197 |
+
responses,
|
198 |
+
rng,
|
199 |
+
sleep,
|
200 |
+
tz,
|
201 |
+
user_agents,
|
202 |
+
verbs,
|
203 |
+
):
|
204 |
+
pattern = (
|
205 |
+
r'^(\S+)' # IP address
|
206 |
+
r' - [\S+]'
|
207 |
+
r' \[([^\]]+)\]' # timestamp
|
208 |
+
r' "([A-Z]+)' # HTTP request code
|
209 |
+
r' ([^"]+)' # HTTP request resource
|
210 |
+
r' HTTP/[^"]+"'
|
211 |
+
r' (\d{3})' # Status code (3 digits)
|
212 |
+
r' (\S+)' # Response size
|
213 |
+
r' (\S+)' # Latency
|
214 |
+
r' "([^"]*)"' # Referrer
|
215 |
+
r' "([^"]*)"' # User agent
|
216 |
+
)
|
217 |
+
|
218 |
+
def generator(log_lines: int) -> \
|
219 |
+
Generator[list[str], int, None]:
|
220 |
+
for idx in range(log_lines):
|
221 |
+
log_line = generate_log_line(tz=tz, sleep=idx*sleep, otime=otime,
|
222 |
+
faker=faker, rng=rng, resources=resources,
|
223 |
+
user_agents=user_agents, responses=responses, verbs=verbs)
|
224 |
+
yield list(re.findall(pattern, log_line)[0])
|
225 |
+
return generator, pattern
|
226 |
+
|
227 |
+
|
228 |
+
@app.cell(hide_code=True)
|
229 |
+
def _(mo):
|
230 |
+
mo.md(
|
231 |
+
r"""
|
232 |
+
Since we are generating data using a Python generator, we create a `pl.LazyFrame` directly, but we can start with either a file or an existing `DataFrame`. When using a file, the functions beginning with `pl.scan_` from the Polars API can be used, while in the case of an existing `pl.DataFrame`, we can simply call `.lazy()` to convert it to a `pl.LazyFrame`.
|
233 |
+
|
234 |
+
///Note
|
235 |
+
Depending on your machine, the following cell may take some time to execute.
|
236 |
+
"""
|
237 |
+
)
|
238 |
+
return
|
239 |
+
|
240 |
+
|
241 |
+
@app.cell
|
242 |
+
def _(generator, num_log_lines, pl):
|
243 |
+
log_data = pl.LazyFrame(generator(num_log_lines),
|
244 |
+
schema=["ip", "time", "request_code",
|
245 |
+
"request_resource", "status", "size",
|
246 |
+
"latency", "referer", "agent"])
|
247 |
+
return (log_data,)
|
248 |
+
|
249 |
+
|
250 |
+
@app.cell(hide_code=True)
|
251 |
+
def _(mo):
|
252 |
+
mo.md(
|
253 |
+
r"""
|
254 |
+
## Schema
|
255 |
+
|
256 |
+
A schema denotes the names and respective datatypes of columns in a DataFrame or LazyFrame. It can be specified when a DataFrame or LazyFrame is generated (as you may have noticed in the cell creating the LazyFrame above).
|
257 |
+
|
258 |
+
You can see the schema with the .collect_schema method on a DataFrame or LazyFrame.
|
259 |
+
"""
|
260 |
+
)
|
261 |
+
return
|
262 |
+
|
263 |
+
|
264 |
+
@app.cell
|
265 |
+
def _(log_data):
|
266 |
+
print(log_data.collect_schema())
|
267 |
+
return
|
268 |
+
|
269 |
+
|
270 |
+
@app.cell(hide_code=True)
|
271 |
+
def _(mo):
|
272 |
+
mo.md(
|
273 |
+
r"""
|
274 |
+
Unless specified, Polars defaults to the `pl.String` datatype for all data. This, however, is not the most space or computation efficient form of data storage, so we would like to convert the datatypes of some of the columns in our LazyFrame.
|
275 |
+
|
276 |
+
///Note
|
277 |
+
The data type conversion can also be done by specifying it in the schema when creating the LazyFrame or DataFrame. We are skipping doing this for demonstration.
|
278 |
+
"""
|
279 |
+
)
|
280 |
+
return
|
281 |
+
|
282 |
+
|
283 |
+
@app.cell(hide_code=True)
|
284 |
+
def _(mo):
|
285 |
+
mo.md(r"""The Lazy API validates a query pipeline end-to-end for schema consistency and correctness. The checks make sure that if there is a mistake in your query, you can correct it before the data gets processed.""")
|
286 |
+
return
|
287 |
+
|
288 |
+
|
289 |
+
@app.cell(hide_code=True)
|
290 |
+
def _(mo):
|
291 |
+
mo.md(r"""The `log_data_erroneous` query below throws an `InvalidOperationError` because Polars finds inconsistencies between the timestamps we parsed from the logs and the timestamp format specified. It turns out that the time stamps in string format still have trailing whitespace which leads to errors during conversion to `datetime[μs]` objects.""")
|
292 |
+
return
|
293 |
+
|
294 |
+
|
295 |
+
@app.cell
|
296 |
+
def _(log_data, pl):
|
297 |
+
log_data_erroneous = log_data.with_columns(
|
298 |
+
pl.col("time").str.to_datetime("%d/%b/%Y:%H:%M:%S"),
|
299 |
+
pl.col("status").cast(pl.Int16),
|
300 |
+
pl.col("size").cast(pl.Int32),
|
301 |
+
pl.col("latency").cast(pl.Float32)
|
302 |
+
)
|
303 |
+
return (log_data_erroneous,)
|
304 |
+
|
305 |
+
|
306 |
+
@app.cell
|
307 |
+
def _(log_data_erroneous):
|
308 |
+
log_data_erroneous.collect()
|
309 |
+
return
|
310 |
+
|
311 |
+
|
312 |
+
@app.cell(hide_code=True)
|
313 |
+
def _(mo):
|
314 |
+
mo.md(
|
315 |
+
r"""
|
316 |
+
Polars uses a **query optimizer** to make sure that a query pipeline is executed with the least computational cost (more on this later). In order to be able to do the optimization, the optimizer must know the schema for each step of the pipeline (query plan). For example, if you have a `.pivot` operation somewhere in your pipeline, you are generating new columns based on the data. This is new information unknown to the query optimizer that it cannot work with, and so the lazy API does not support `.pivot` operations.
|
317 |
+
|
318 |
+
For example, suppose you would like to know how many requests of each kind were received at a given time that were not "POST" requests. For this we would want to create a pivot table as follows, except that it throws an error as the lazy API does not support pivot operations.
|
319 |
+
"""
|
320 |
+
)
|
321 |
+
return
|
322 |
+
|
323 |
+
|
324 |
+
@app.cell
|
325 |
+
def _(log_data, pl):
|
326 |
+
(
|
327 |
+
log_data.pivot(index="time", on="request_code",
|
328 |
+
values="status", aggregate_function="len")
|
329 |
+
.filter(pl.col("POST").is_null())
|
330 |
+
.collect()
|
331 |
+
)
|
332 |
+
return
|
333 |
+
|
334 |
+
|
335 |
+
@app.cell(hide_code=True)
|
336 |
+
def _(mo):
|
337 |
+
mo.md(
|
338 |
+
r"""
|
339 |
+
As a workaround, we can jump between "lazy mode" and "eager mode" by converting a LazyFrame to a DataFrame just before the unsupported operation (e.g. `.pivot`). We can do this by calling `.collect()` on the LazyFrame. Once done with the "eager mode" operations, we can jump back to "lazy mode" by calling ".lazy()" on the DataFrame!
|
340 |
+
|
341 |
+
As an example, see the fix to the query in the previous cell below:
|
342 |
+
"""
|
343 |
+
)
|
344 |
+
return
|
345 |
+
|
346 |
+
|
347 |
+
@app.cell
|
348 |
+
def _(log_data, pl):
|
349 |
+
(
|
350 |
+
log_data
|
351 |
+
.collect()
|
352 |
+
.pivot(index="time", on="request_code",
|
353 |
+
values="status", aggregate_function="len")
|
354 |
+
.lazy()
|
355 |
+
.filter(pl.col("POST").is_null())
|
356 |
+
.collect()
|
357 |
+
)
|
358 |
+
return
|
359 |
+
|
360 |
+
|
361 |
+
@app.cell(hide_code=True)
|
362 |
+
def _(mo):
|
363 |
+
mo.md(r"""## Query plan""")
|
364 |
+
return
|
365 |
+
|
366 |
+
|
367 |
+
@app.cell(hide_code=True)
|
368 |
+
def _(mo):
|
369 |
+
mo.md(
|
370 |
+
r"""
|
371 |
+
Polars has a query optimizer that works on a "query plan" to create a computationally efficient query pipeline. It builds the query plan/query graph from the user-specified lazy operations.
|
372 |
+
|
373 |
+
We can understand query graphs with visualization and by printing them as text.
|
374 |
+
|
375 |
+
Say we want to convert the data in our log dataset from `pl.String` more space efficient data types. We also would like to view all "GET" requests that resulted in errors (client side). We build our query first, and then we visualize the query graph using `.show_graph()` and print it using `.request_code()`.
|
376 |
+
"""
|
377 |
+
)
|
378 |
+
return
|
379 |
+
|
380 |
+
|
381 |
+
@app.cell
|
382 |
+
def _(log_data, pl):
|
383 |
+
a_query = (
|
384 |
+
log_data
|
385 |
+
.with_columns(pl.col("status").cast(pl.Int16))
|
386 |
+
.with_columns(pl.col("size").cast(pl.Int32))
|
387 |
+
.with_columns(pl.col("latency").cast(pl.Float32))
|
388 |
+
.with_columns(
|
389 |
+
pl.col("time")
|
390 |
+
.str.strip_chars()
|
391 |
+
.str.to_datetime("%d/%b/%Y:%H:%M:%S"),
|
392 |
+
)
|
393 |
+
.filter((pl.col("status") >= 400) & (pl.col("request_code") == "GET"))
|
394 |
+
)
|
395 |
+
return (a_query,)
|
396 |
+
|
397 |
+
|
398 |
+
@app.cell
|
399 |
+
def _(a_query):
|
400 |
+
a_query.show_graph()
|
401 |
+
return
|
402 |
+
|
403 |
+
|
404 |
+
@app.cell
|
405 |
+
def _(a_query):
|
406 |
+
print(a_query.explain())
|
407 |
+
return
|
408 |
+
|
409 |
+
|
410 |
+
@app.cell(hide_code=True)
|
411 |
+
def _(mo):
|
412 |
+
mo.md(r"""## Execution""")
|
413 |
+
return
|
414 |
+
|
415 |
+
|
416 |
+
@app.cell(hide_code=True)
|
417 |
+
def _(mo):
|
418 |
+
mo.md(
|
419 |
+
r"""
|
420 |
+
As mentioned before, Polars builds a query graph by going lazy operation by operation and then optimizes it by running a query optimizer on the graph. This optimized graph is run by default.
|
421 |
+
|
422 |
+
We can execute our query on the full dataset by calling the .collect method on the query. But since this option processes all data in one batch, it is not memory efficient, and can crash if the size of the data exceeds the amount of memory your query can support.
|
423 |
+
|
424 |
+
For fast iterative development running `.collect` on the entire dataset is not a good idea due to slow runtimes. If your dataset is partitioned, you can use a few of them for testing. Another option is to use `.head` to limit the number of records processed, and `.collect` as few times as possible and toward the end of your query, as shown below.
|
425 |
+
"""
|
426 |
+
)
|
427 |
+
return
|
428 |
+
|
429 |
+
|
430 |
+
@app.cell(hide_code=True)
|
431 |
+
def _(mo):
|
432 |
+
mo.md(r""" """)
|
433 |
+
return
|
434 |
+
|
435 |
+
|
436 |
+
@app.cell
|
437 |
+
def _(log_data, pl):
|
438 |
+
(
|
439 |
+
log_data
|
440 |
+
.head(n=100)
|
441 |
+
.with_columns(pl.col("status").cast(pl.Int16))
|
442 |
+
.with_columns(pl.col("size").cast(pl.Int32))
|
443 |
+
.with_columns(pl.col("latency").cast(pl.Float32))
|
444 |
+
.with_columns(
|
445 |
+
pl.col("time")
|
446 |
+
.str.strip_chars()
|
447 |
+
.str.to_datetime("%d/%b/%Y:%H:%M:%S"),
|
448 |
+
)
|
449 |
+
.filter((pl.col("status") >= 400) & (pl.col("request_code") == "GET"))
|
450 |
+
.collect()
|
451 |
+
)
|
452 |
+
return
|
453 |
+
|
454 |
+
|
455 |
+
@app.cell(hide_code=True)
|
456 |
+
def _(mo):
|
457 |
+
mo.md(r"""For large datasets Polars supports streaming mode by collecting data in batches. Streaming mode can be used by passing the keyword `engine="streaming"` into the `collect` method.""")
|
458 |
+
return
|
459 |
+
|
460 |
+
|
461 |
+
@app.cell
|
462 |
+
def _(a_query):
|
463 |
+
a_query.collect(engine="streaming")
|
464 |
+
return
|
465 |
+
|
466 |
+
|
467 |
+
@app.cell(hide_code=True)
|
468 |
+
def _(mo):
|
469 |
+
mo.md(
|
470 |
+
r"""
|
471 |
+
## Optimizations
|
472 |
+
|
473 |
+
The lazy API runs a query optimizer on every Polars query. To do this, first it builds a non-optimized plan with the set of steps in the order they were specified by the user. Then it checks for optimization opportunities within the plan and reorders operations following specific rules to create an optimized query plan. Some of them are executed up front, others are determined just in time as the materialized data comes in. For the query that we built before and saw the query graph, we can view the unoptimized and optimized versions below.
|
474 |
+
"""
|
475 |
+
)
|
476 |
+
return
|
477 |
+
|
478 |
+
|
479 |
+
@app.cell
|
480 |
+
def _(a_query):
|
481 |
+
a_query.show_graph(optimized=False)
|
482 |
+
return
|
483 |
+
|
484 |
+
|
485 |
+
@app.cell
|
486 |
+
def _(a_query):
|
487 |
+
a_query.show_graph()
|
488 |
+
return
|
489 |
+
|
490 |
+
|
491 |
+
@app.cell(hide_code=True)
|
492 |
+
def _(mo):
|
493 |
+
mo.md(r"""One difference between the optimized and the unoptimized versions above is that all of the datatype cast operations except for the conversion of the `"status"` column to `pl.Int16` are performed at the end together. Also, the `filter()` operation is "pushed down" the graph, but after the datatype cast operation for `"status"`. This is called **predicate pushdown**, and the lazy API optimizes the query graph for filters to be performed as early as possible. Since the datatype coercion makes the filter operation more efficient, the graph preserves its order to be before the filter.""")
|
494 |
+
return
|
495 |
+
|
496 |
+
|
497 |
+
@app.cell(hide_code=True)
|
498 |
+
def _(mo):
|
499 |
+
mo.md(r"""## Sources and Sinks""")
|
500 |
+
return
|
501 |
+
|
502 |
+
|
503 |
+
@app.cell(hide_code=True)
|
504 |
+
def _(mo):
|
505 |
+
mo.md(r"""For data sources like Parquets, CSVs, etc, the lazy API provides `scan_*` (`scan_parquet`, `scan_csv`, etc.) to lazily read in the data into LazyFrames. If queries are chained to the `scan_*` method, Polars will run the usual query optimizations and delay execution until the query is collected. An added benefit of chaining queries to `scan_*` operations is that the "scanners" can skip reading columns and rows that aren't required. This is helpful when streaming large datasets as well, as rows are processed in batches before the entire file is read.""")
|
506 |
+
return
|
507 |
+
|
508 |
+
|
509 |
+
@app.cell(hide_code=True)
|
510 |
+
def _(mo):
|
511 |
+
mo.md(r"""The results of a query from a lazyframe can be saved in streaming mode using `sink_*` (e.g. `sink_parquet`) functions. Sinks support saving data to disk or cloud, and are especially helpful with large datasets. The data being sunk can also be partitioned into multiple files if needed, after specifying a suitable partitioning strategy, as shown below.""")
|
512 |
+
return
|
513 |
+
|
514 |
+
|
515 |
+
@app.cell
|
516 |
+
def _(a_query, pl):
|
517 |
+
(
|
518 |
+
a_query
|
519 |
+
.sink_parquet(
|
520 |
+
pl.PartitionMaxSize(
|
521 |
+
"log_data_filtered_{part}.parquet",
|
522 |
+
max_size=1_000
|
523 |
+
)
|
524 |
+
)
|
525 |
+
)
|
526 |
+
return
|
527 |
+
|
528 |
+
|
529 |
+
@app.cell(hide_code=True)
|
530 |
+
def _(mo):
|
531 |
+
mo.md(r"""We can also write to multiple sinks at the same time. We just need to specify two separate lazy sinks and combine them by calling `pl.collect_all` and mentioning both sinks.""")
|
532 |
+
return
|
533 |
+
|
534 |
+
|
535 |
+
@app.cell
|
536 |
+
def _(a_query, pl):
|
537 |
+
_q1 = a_query.sink_parquet("log_data_filtered.parquet", lazy=True)
|
538 |
+
_q2 = a_query.sink_ipc("log_data_filtered.ipc", lazy=True)
|
539 |
+
pl.collect_all([_q1, _q2])
|
540 |
+
return
|
541 |
+
|
542 |
+
|
543 |
+
@app.cell(hide_code=True)
|
544 |
+
def _(mo):
|
545 |
+
mo.md(
|
546 |
+
r"""
|
547 |
+
## References
|
548 |
+
|
549 |
+
1. Polars [documentation](https://docs.pola.rs/user-guide/lazy/)
|
550 |
+
"""
|
551 |
+
)
|
552 |
+
return
|
553 |
+
|
554 |
+
|
555 |
+
@app.cell(hide_code=True)
|
556 |
+
def _():
|
557 |
+
import marimo as mo
|
558 |
+
return (mo,)
|
559 |
+
|
560 |
+
|
561 |
+
if __name__ == "__main__":
|
562 |
+
app.run()
|