Search in sources :

Example 1 with CountSum

use of org.apache.beam.sdk.transforms.Mean.CountSum in project beam by apache.

the class ParDoTest method testCombiningState.

@Test
@Category({ ValidatesRunner.class, UsesStatefulParDo.class })
public void testCombiningState() {
    final String stateId = "foo";
    DoFn<KV<String, Double>, String> fn = new DoFn<KV<String, Double>, String>() {

        private static final double EPSILON = 0.0001;

        @StateId(stateId)
        private final StateSpec<CombiningState<Double, CountSum<Double>, Double>> combiningState = StateSpecs.combining(new Mean.CountSumCoder<Double>(), Mean.<Double>of());

        @ProcessElement
        public void processElement(ProcessContext c, @StateId(stateId) CombiningState<Double, CountSum<Double>, Double> state) {
            state.add(c.element().getValue());
            Double currentValue = state.read();
            if (Math.abs(currentValue - 0.5) < EPSILON) {
                c.output("right on");
            }
        }
    };
    PCollection<String> output = pipeline.apply(Create.of(KV.of("hello", 0.3), KV.of("hello", 0.6), KV.of("hello", 0.6))).apply(ParDo.of(fn));
    // There should only be one moment at which the average is exactly 0.5
    PAssert.that(output).containsInAnyOrder("right on");
    pipeline.run();
}
Also used : StateSpec(org.apache.beam.sdk.state.StateSpec) CountSum(org.apache.beam.sdk.transforms.Mean.CountSum) CombiningState(org.apache.beam.sdk.state.CombiningState) StringUtils.byteArrayToJsonString(org.apache.beam.sdk.util.StringUtils.byteArrayToJsonString) Matchers.containsString(org.hamcrest.Matchers.containsString) KV(org.apache.beam.sdk.values.KV) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Aggregations

CombiningState (org.apache.beam.sdk.state.CombiningState)1 StateSpec (org.apache.beam.sdk.state.StateSpec)1 CountSum (org.apache.beam.sdk.transforms.Mean.CountSum)1 StringUtils.byteArrayToJsonString (org.apache.beam.sdk.util.StringUtils.byteArrayToJsonString)1 KV (org.apache.beam.sdk.values.KV)1 Matchers.containsString (org.hamcrest.Matchers.containsString)1 Test (org.junit.Test)1 Category (org.junit.experimental.categories.Category)1