Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import org.apache.spark.sql.catalyst.encoders.{encoderFor, ExpressionEncoder, Ou
import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, CreateStruct}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.execution.QueryExecution
import org.apache.spark.sql.expressions.ReduceAggregator

/**
* :: Experimental ::
Expand Down Expand Up @@ -177,10 +178,13 @@ class KeyValueGroupedDataset[K, V] private[sql](
* @since 1.6.0
*/
def reduceGroups(f: (V, V) => V): Dataset[(K, V)] = {
val func = (key: K, it: Iterator[V]) => Iterator((key, it.reduce(f)))
val vEncoder = encoderFor[V]
val aggregator: TypedColumn[V, V] = new ReduceAggregator[V] {
override def func(a: V, b: V) = f(a, b)
override def encoder = vEncoder
}.toColumn

implicit val resultEncoder = ExpressionEncoder.tuple(kExprEnc, vExprEnc)
flatMapGroups(func)
agg(aggregator)
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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.
*/

package org.apache.spark.sql.expressions

import org.apache.spark.annotation.Experimental
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder

/**
* :: Experimental ::
* An aggregator that uses a single associative and commutative reduce function. This reduce
* function can be used to go through all input values and reduces them to a single value.
* If there is no input, a null value is returned.
*
* @since 2.1.0
*/
@Experimental
abstract class ReduceAggregator[T] extends Aggregator[T, (Boolean, T), T] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i like factoring this class out of the reduce operation instead of making it an anonymous class, but do we expect people to use this directly? does it need to be public?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i mean, i like it to be public but that changes what is important in the design

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you are right -- I will keep it private to begin with.


// Question 1: Should func and encoder be parameters rather than abstract methods?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here are the two questions we need to answer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @koertkuipers what do you think?

// rxin: abstract method has better java compatibility and forces naming the concrete impl,
// whereas parameter has better type inference (infer encoders via context bounds).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i like the parameters better

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

// Question 2: Should finish throw an exception or return null if there is no input?
// rxin: null might be more "SQL" like, whereas exception is more Scala like.

@koertkuipers koertkuipers Aug 10, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideally the class would be:
abstract class ReduceAggregator[T] extends Aggregator[T, (Boolean, T), Option[T]]

for usage inside reduceGroups it doesn't matter how you choose to handle empty input for finish, since the situation should never arise. so i guess throwing an exception would capture that best.

but the question of the behavior of finish does matter if this ReduceAggregator is public and can be used in select statements where input can be empty. so for that reason i prefer to return Option[T] or if thats not possible then null in case of empty input. throwing an exception seems odd now.


/**
* A associative and commutative reduce function.
* @since 2.1.0
*/
def func(a: T, b: T): T

/**
* Encoder for type T.
* @since 2.1.0
*/
def encoder: ExpressionEncoder[T]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be an encoder, not expression encoder.


override def zero: (Boolean, T) = (false, null.asInstanceOf[T])

override def bufferEncoder: Encoder[(Boolean, T)] =
ExpressionEncoder.tuple(ExpressionEncoder[Boolean](), encoder)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Encoders.scalaBoolean?


override def outputEncoder: Encoder[T] = encoder

override def reduce(b: (Boolean, T), a: T): (Boolean, T) = {
if (b._1) {
(true, func(b._2, a))
} else {
(true, a)
}
}

override def merge(b1: (Boolean, T), b2: (Boolean, T)): (Boolean, T) = {
if (!b1._1) {
b2
} else if (!b2._1) {
b1
} else {
(true, func(b1._2, b2._2))
}
}

override def finish(reduction: (Boolean, T)): T = reduction._2

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May reduction._1 be false here? e.g. SELECT count(a) FROM tbl, if tbl is empty, we will return zero. But for the reduce-style aggregate function, should we throw exception for this case?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since it should never happen, how about an assertion?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it can happen

val df = Seq.empty[Int].toDF("i")
df.agg(count($"i"))  // returns 0
df.agg(new ReduceAggregator[Int](_ + _)(intEnc).toColumn)   // what should we do?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, df.agg(avg($"i")) returns null, this logic is defined by Divide, if the divisor is 0, Divide will return null.

@koertkuipers koertkuipers Aug 17, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can not happen since ReduceAggregator is private? as long as it it only used in reduceGroups we should never run into the empty input

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to support reduce group without grouping key, so it may happen in the future. Besides, it's not a lot of work, we just need to decide the expected behaviour.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's possible for us to support that in the future, but we can worry about it when we want to make this public?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then shall we add an assert? Or we may probably forget about it and go with return null for empty relation without grouping key, which is what the current code do.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup I will add it.

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* 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.
*/

package org.apache.spark.sql.expressions

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder

class ReduceAggregatorSuite extends SparkFunSuite {
test("zero value") {
val encoder: ExpressionEncoder[Int] = ExpressionEncoder()
val func = (v1: Int, v2: Int) => v1 + v2
val aggregator: ReduceAggregator[Int] = new ReduceAggregator(func, encoder)
assert(aggregator.zero == (false, null))
}

test("reduce, merge and finish") {
val encoder: ExpressionEncoder[Int] = ExpressionEncoder()
val func = (v1: Int, v2: Int) => v1 + v2
val aggregator: ReduceAggregator[Int] = new ReduceAggregator(func, encoder)

val firstReduce = aggregator.reduce(aggregator.zero, 1)
assert(firstReduce == (true, 1))

val secondReduce = aggregator.reduce(firstReduce, 2)
assert(secondReduce == (true, 3))

val thirdReduce = aggregator.reduce(secondReduce, 3)
assert(thirdReduce == (true, 6))

val mergeWithZero1 = aggregator.merge(aggregator.zero, firstReduce)
assert(mergeWithZero1 == (true, 1))

val mergeWithZero2 = aggregator.merge(secondReduce, aggregator.zero)
assert(mergeWithZero2 == (true, 3))

val mergeTwoReduced = aggregator.merge(firstReduce, secondReduce)
assert(mergeTwoReduced == (true, 4))

assert(aggregator.finish(firstReduce)== 1)
assert(aggregator.finish(secondReduce) == 3)
assert(aggregator.finish(thirdReduce) == 6)
assert(aggregator.finish(mergeWithZero1) == 1)
assert(aggregator.finish(mergeWithZero2) == 3)
assert(aggregator.finish(mergeTwoReduced) == 4)
}
}