use of org.apache.jena.sparql.expr.aggregate.Accumulator in project jena by apache.
the class QueryIterGroup method calc.
private static Iterator<Binding> calc(final QueryIterator iter, final VarExprList groupVarExpr, final List<ExprAggregator> aggregators, final ExecutionContext execCxt) {
return new IteratorDelayedInitialization<Binding>() {
@Override
protected Iterator<Binding> initializeIterator() {
boolean noAggregators = (aggregators == null || aggregators.isEmpty());
// Phase 1 : assign bindings to buckets by key and pump through the aggregators.
Multimap<Binding, Pair<Var, Accumulator>> accumulators = HashMultimap.create();
while (iter.hasNext()) {
Binding b = iter.nextBinding();
Binding key = genKey(groupVarExpr, b, execCxt);
if (noAggregators) {
// Put in a dummy to remember the input.
accumulators.put(key, placeholder);
continue;
}
// Create if does not exist.
if (!accumulators.containsKey(key)) {
for (ExprAggregator agg : aggregators) {
Accumulator x = agg.getAggregator().createAccumulator();
Var v = agg.getVar();
accumulators.put(key, Pair.create(v, x));
}
}
// Do the per-accumulator calculation.
for (Pair<Var, Accumulator> pair : accumulators.get(key)) pair.getRight().accumulate(b, execCxt);
}
if (accumulators.isEmpty()) {
if (noAggregators) {
// ==> No result rows.
return Iter.nullIterator();
}
BindingMap binding = BindingFactory.create();
for (ExprAggregator agg : aggregators) {
Var v = agg.getVar();
Node value = agg.getAggregator().getValueEmpty();
if (value != null) {
binding.add(v, value);
}
}
if (binding == null)
// This does not happen if there are any aggregators.
return Iter.nullIterator();
// cast to get the static type inference to work.
return Iter.singletonIter((Binding) binding);
}
if (noAggregators)
// We used placeholder so there are always the key.
return accumulators.keySet().iterator();
List<Binding> results = new ArrayList<>();
for (Binding k : accumulators.keySet()) {
Collection<Pair<Var, Accumulator>> accs = accumulators.get(k);
BindingMap b = BindingFactory.create(k);
for (Pair<Var, Accumulator> pair : accs) {
Var v = pair.getLeft();
NodeValue value = pair.getRight().getValue();
Node n = (value == null) ? null : value.asNode();
if (v == null || n == null) {
} else
b.add(v, n);
}
results.add(b);
}
return results.iterator();
}
};
}
Aggregations