andygrove commented on code in PR #2890:
URL: 
https://github.com/apache/datafusion-ballista/pull/2890#discussion_r4643005540


##########
examples/README.md:
##########
@@ -32,6 +32,14 @@ cargo run --example standalone_sql
 
 Source: 
[`examples/examples/standalone-sql.rs`](https://github.com/apache/datafusion-ballista/blob/main/examples/examples/standalone-sql.rs)
 
+`DataFrame::cache()` in staged and pipelined modes:
+
+```bash
+cargo run --example standalone_dataframe_cache
+```
+
+Source: 
[`examples/examples/standalone-dataframe-cache.rs`](https://github.com/apache/datafusion-ballista/blob/main/examples/examples/standalone-dataframe-cache.rs)

Review Comment:
   The substrait command right after this block has no intro line, so it now 
looks like part of the cache example. Could you move the cache entry below 
substrait, or add a one-line intro for substrait?



##########
docs/source/user-guide/pipelined-execution.md:
##########
@@ -137,6 +137,15 @@ does not work.
   executors more memory, use fewer partitions, or run such queries in staged
   mode.
 
+## Queries over a cached DataFrame
+
+`DataFrame::cache()` works in a pipelined session. A cache is always built by
+an ordinary staged job, run by the first query that reads it; later queries

Review Comment:
   Small wording thought here. "later queries read the cached result pipelined" 
reads a bit like the first query runs staged too. As I understand it, only the 
build job is staged, and the first query then reads the cache pipelined like 
the rest. Maybe something like "The build always runs as a staged job. Every 
query over the cache, including the first, then reads it in pipelined mode"?



##########
examples/examples/standalone-dataframe-cache.rs:
##########
@@ -0,0 +1,153 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! `DataFrame::cache()` keeps a DataFrame's result on the executors, so 
queries
+//! over it read the stored result instead of computing it again.
+//!
+//! This example:
+//! 1. turns caching on (it is off by default),
+//! 2. caches a prepared DataFrame (nothing runs yet),
+//! 3. builds the cache with the first query and reads it with the next ones,
+//!    in staged mode,
+//! 4. switches the session to pipelined mode, which reads the same cache,
+//! 5. runs three pipelined queries in parallel, printing rows as they arrive.
+//!
+//! Good to know: a cache belongs to its session and is not evicted yet, so
+//! cache only what you reuse. Cached data lost with an executor is rebuilt, 
and
+//! `EXPLAIN` never builds a cache. See the tuning guide for details.
+
+use ballista::datafusion::{
+    arrow::{record_batch::RecordBatch, util::pretty::pretty_format_batches},
+    common::Result,
+    execution::{SessionStateBuilder, options::CsvReadOptions},
+    functions_aggregate::expr_fn::{count, sum},
+    prelude::{DataFrame, SessionConfig, SessionContext, col, lit},
+};
+use ballista::prelude::{SessionConfigExt, SessionContextExt};
+use ballista_examples::test_util;
+use futures::StreamExt;
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    // 1. A standalone cluster, with caching turned on. Queries start staged.
+    let ctx = standalone().await?;
+
+    // 2. The DataFrame the queries start from. Nothing runs here: `cache()`
+    //    only marks it to be kept. In an application this is the expensive
+    //    part, such as scans, joins and aggregations.
+    let path = format!("{}/aggregate_test_100.csv", 
test_util::examples_test_data());
+    let sales = ctx
+        .read_csv(path, CsvReadOptions::new())
+        .await?
+        .select(vec![
+            col("c1").alias("category"),
+            col("c2").alias("store"),
+            col("c4").alias("amount"),
+        ])?
+        .filter(col("amount").gt(lit(0)))?
+        .cache()
+        .await?;
+
+    // 3. Staged: the first query builds the cache, as a staged job, and then
+    //    reads it. Later queries, and DataFrames derived from `sales`, read 
it.
+    println!("== staged: the first query builds the cache ==");
+    println!("{} sales", sales.clone().count().await?);
+
+    println!("== staged: later queries read the cache ==");
+    let staged = by_category(sales.clone())?.collect().await?;
+    println!("{}", pretty_format_batches(&staged)?);
+
+    // 4. Pipelined: one SET. A DataFrame keeps the settings of the session it
+    //    came from, so rebuild it from the session's state to pick up the new
+    //    mode. The plan, and the cache it reads, are the same.
+    ctx.sql("SET ballista.execution.mode = 'pipelined'").await?;
+    let sales = DataFrame::new(ctx.state(), sales.into_unoptimized_plan());
+
+    // 5. Three queries in parallel, each streaming its rows from the cache as
+    //    they are produced. Read every stream you start, and keep the queries
+    //    running at once within the cluster: each holds the vcores of its
+    //    widest stage until it ends, here 8 vcores / 2 partitions = 4 at once.
+    println!("== pipelined: three queries in parallel ==");
+    let (pipelined, _, _) = tokio::try_join!(
+        stream("by category", by_category(sales.clone())?),
+        stream(
+            "sales per store",
+            sales
+                .clone()
+                .aggregate(vec![col("store")], 
vec![count(lit(1)).alias("sales")])?
+        ),
+        stream(
+            "top 5 amounts",
+            sales
+                .clone()
+                .sort(vec![col("amount").sort(false, false)])?
+                .limit(0, Some(5))?
+        ),
+    )?;
+
+    // The cache gives the same result in either mode.
+    assert_eq!(

Review Comment:
   Nice touch asserting that staged and pipelined give the same result. 
Examples aren't run in CI though, so if this one breaks later nobody will 
notice. Not required for this PR, just a thought for later.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to