A few days ago I posted about grouping because I wasn’t getting any results. Jens answer solved my problem, but now I’m getting a different, but related issue.
I am now grouping based on a few different criteria, but for now am trying to get a group level of two working, which should aggregate based on item name. The following code is partially working. SaleItems are aggregating, but they’re split up in weird ways, that I’m pretty sure are based on date. For example, I’ll get a group of 200 SaleItems grouped together with an identical name, but then there will be another group with 150 that have the exact same key at group level two, but a different key at group level 1. I’m not sure why it’s aggregating based on the first key at all. My understanding is that it will filter everything in the date-range (key range) I provided for group level 1, and then aggregate based on group level two?
Here is my new map function :
List<Object> keys = new ArrayList<>();
keys.add(document.get("sale_date"));
String name = ((String)((Map<String, Object>)document.get("supply_item_snapshot"))
.get("name")).toLowerCase().trim();
keys.add(name);
String brand = ((String)((Map<String, Object>)document.get("supply_item_snapshot"))
.get("brand")).toLowerCase().trim();
keys.add(name + " " + brand);
String strength = ((String) ((Map<String, Object>)document.get
("supply_item_snapshot")).get("strength")).toLowerCase().trim();
keys.add((name + " " + strength));
keys.add(name + " " + brand + " " + strength);
Map<String, Object> totals = new HashMap<>(3);
totals.put("total_price", new BigDecimal(document.get("total_price").toString()));
totals.put("quantity_sold", document.get("quantity_sold"));
totals.put("supply_item_snapshot", document.get("supply_item_snapshot"));
emitter.emit(keys, totals);
Reduce function:
private static final Reducer mSaleItemsAggregator = new Reducer() {
@Override
public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) {
SaleItemAggregate saleItemAggregate = new SaleItemAggregate();
for (Object value : values) {
LazyJsonObject jsonValue = (LazyJsonObject) value;
if (value != null) {
saleItemAggregate.addValues(jsonValue);
}
}
return saleItemAggregate;
}
};
and query code:
mQuery = SaleItem.getQuery(getMaishaActivity().getDatabase(), SaleItem.AGGREGATE_VIEW);
mQuery.setDescending(true);
mQuery.setGroupLevel(2);
mQuery.setStartKey(Arrays.asList(endDate, new HashMap<>()));
mQuery.setEndKey(Arrays.asList(startDate));