Skip to content

Commit

Permalink
datastore: fix the accumulator 'sum' in MongoDB facets, #TASK-7151, #…
Browse files Browse the repository at this point in the history
…TASK-7134
  • Loading branch information
jtarraga committed Dec 12, 2024
1 parent e8159f3 commit 005c45e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,7 @@ private static Facet getMongoDBFacet(String field, Accumulator accumulator, List
break;
}
case sum: {
facet = new Facet(field + SUM_SUFFIX, Arrays.asList(Aggregates.group(id, Accumulators.sum(sum.name(), id))));
facet = new Facet(field + SUM_SUFFIX, Arrays.asList(Aggregates.group(field, Accumulators.sum(sum.name(), id))));
break;
}
case avg: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,46 @@ public void testFacetMaxDotNotationAndList() {
}
}

@Test
public void testFacetSumAccumulator() {
Document match = new Document("age", new BasicDBObject("$gt", 2));
DataResult<Document> matchedResults = mongoDBCollection.find(match, null);
int total = 0;
String fieldName = "number";
for (Document result : matchedResults.getResults()) {
System.out.println("result = " + result);
total += result.getLong(fieldName);
}
double avg = total / matchedResults.getNumResults();

List<Bson> facets = MongoDBQueryUtils.createFacet(match, "avg(" + fieldName + ")");
MongoDBDocumentToFacetFieldsConverter converter = new MongoDBDocumentToFacetFieldsConverter();
DataResult<List<FacetField>> aggregate = mongoDBCollection.aggregate(facets, converter, null);
for (List<FacetField> result : aggregate.getResults()) {
Assert.assertEquals(1, result.size());
for (FacetField facetField : result) {
Assert.assertTrue(facetField.getCount() == null);
Assert.assertEquals(Accumulator.avg.name(), facetField.getAggregationName());
Assert.assertEquals(avg, facetField.getAggregationValues().get(0), 0.5);
// for (int i = 0; i < facetField.getAggregationValues().size() ; i++) {
// Assert.assertEquals(maxValues.get(i), facetField.getAggregationValues().get(i), 0.0001);
// }
}
}


facets = MongoDBQueryUtils.createFacet(match, "sum(" + fieldName + ")");
aggregate = mongoDBCollection.aggregate(facets, converter, null);
for (List<FacetField> result : aggregate.getResults()) {
Assert.assertEquals(1, result.size());
for (FacetField facetField : result) {
Assert.assertTrue(facetField.getCount() == null);
Assert.assertEquals(Accumulator.sum.name(), facetField.getAggregationName());
Assert.assertEquals(total, facetField.getAggregationValues().get(0), 0.0001);
}
}
}

@Test(expected = IllegalArgumentException.class)
public void testFacetInvalidAccumulator() {
Document match = new Document("age", new BasicDBObject("$gt", 2));
Expand Down

0 comments on commit 005c45e

Please sign in to comment.