-
Push‐down Filter & Prune Columns
• Always filter as early as possible in Spark (so you only scan the one user_id partition).
• Don’t pull every column if you only need a few.
user_id = "25f03412-7c3c-4ea8-a823-b6fe7795d681"
small_df = (tbl
.where(col("user_id") == user_id) # push-down filter
.select("user_id", "created_at", "event") # only the cols you actually need
)
display(small_df)
-
Partition or Z-Order by user_id
If tbl is a Delta table, you can partition or cluster it by user_id so scans for a single id become blazing fast.
● Partition
CREATE TABLE events_p
USING DELTA
PARTITIONED BY (user_id)
AS SELECT * FROM events;
● Z-Order (better for high-cardinality keys)
OPTIMIZE events
ZORDER BY (user_id);
Once the data on disk is co-located by user_id, your where clause will only touch a tiny fraction of files.
-
Cache the Hot Table (or Hot Partition)
If you’re repeatedly querying this table/partition during your session:
spark.catalog.clearCache()
tbl.cache() # or tbl.where(...).cache() for just that user_id
tbl.count() # trigger the cache
display(tbl.where(col("user_id")==user_id))
Subsequent calls read from memory, not disk.
-
Use LIMIT for sanity checks
If you’re just sampling or debugging, don’t pull every row—even if it’s “only one user.”
display(
tbl.where(col("user_id")==user_id)
.limit(1000) # you rarely need more than “a few rows” to inspect
)
-
SQL Shortcut (sometimes faster UI path)
%sql
SELECT *
FROM events
WHERE user_id = '25f03412-7c3c-4ea8-a823-b6fe7795d681'
LIMIT 1000;
Databricks’ SQL optimizer + Photon engine can outright skip unneeded data.