2 * Copyright (c) 2007 Yahoo! Inc. All rights reserved.
3 * See accompanying LICENSE file.
5 package com
.yahoo
.pig
.builtin
;
7 import java
.io
.IOException
;
8 import java
.util
.Iterator
;
10 import com
.yahoo
.pig
.AlgebraicAtomEvalFunc
;
11 import com
.yahoo
.pig
.AtomEvalFunc
;
12 import com
.yahoo
.pig
.TupleEvalFunc
;
13 import com
.yahoo
.pig
.data
.DataAtom
;
14 import com
.yahoo
.pig
.data
.DataBag
;
15 import com
.yahoo
.pig
.data
.Tuple
;
16 import com
.yahoo
.pig
.impl
.logicalLayer
.schema
.SchemaField
;
17 import com
.yahoo
.pig
.impl
.logicalLayer
.schema
.SchemaItem
;
18 import com
.yahoo
.pig
.impl
.logicalLayer
.schema
.SchemaItemList
;
21 * Generates the sum of the values of the first field of a tuple.
23 public class SUM
extends AlgebraicAtomEvalFunc
{
26 public void exec(Tuple input
, DataAtom output
) throws IOException
{
27 output
.setValue(sum(input
));
30 public TupleEvalFunc
getInitial() {
34 public TupleEvalFunc
getIntermed() {
38 public AtomEvalFunc
getFinal() {
42 static public class Initial
extends TupleEvalFunc
{
43 public void exec(Tuple input
, Tuple output
) throws IOException
{
44 output
.appendField(new DataAtom(sum(input
)));
47 static public class Final
extends AtomEvalFunc
{
48 public void exec(Tuple input
, DataAtom output
) throws IOException
{
49 output
.setValue(sum(input
));
53 static protected double sum(Tuple input
) throws IOException
{
54 DataBag values
= input
.getBagField(0);
57 for (Iterator it
= values
.content(); it
.hasNext();) {
58 Tuple t
= (Tuple
) it
.next();
60 sum
+= t
.getAtomField(0).numval();
61 }catch(RuntimeException exp
) {
62 throw new RuntimeException(exp
.getMessage() + " error processing: " + t
.toString());
69 public SchemaItem
outputSchema() {
70 return new SchemaField("sum");