QuestionQ16

VerifiedTroubleshooting and Tuning Apache Spark DataFrame API Applications.

A data engineer is working with a dataset that contains 2 billion rows spread across 10 Spark partitions. The engineer must compute the approximate count of distinct users by the user_id field and also calculate the average transaction_amount. Both calculations must occur in a single transformation step to minimize shuffling.

Which set of Spark code accomplishes this goal while maintaining performance?

Explanation

approx_count_distinct("user_id") estimates the number of unique user IDs, and avg("transaction_amount") calculates the mean transaction amount. Passing both expressions to df.agg(...) computes the two global aggregates together in one aggregation operation, avoiding separate distinct-count and average workflows. Apache Spark documents approx_count_distinct as an aggregate that estimates distinct cardinality and DataFrame.agg as aggregation across the whole DataFrame.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!