I want to count the quantity of bought products in all orders for a special product but only get 3 back as the result in an appscript. Doesnt matter which product I use. That is the codesnippet I am using:
{% set criteria = {
'associations': {
'lineItems': {
'productId': page.product.id
}
},
'aggregations': [{
"name": "count-lineItems-quantity",
"type": "count",
"field": "order.lineItems.quantity"
}]
}
%}
{% set orders = services.repository.search('order', criteria) %}
{% do debug.dump(orders.getAggregations.get('count-lineItems-quantity')) %}
Maybe someone can point me in the right direction and can show me what I am doing wrong.
Cheers,
Danny
You probably currently are only getting the count of unique line items, not the sum of quantities for each line item.
First, I would use the order_line_item
repository, unless you need order specific data. I assume you're trying to filter the results by page.product.id
? Then I would use a filter aggregation to only get line items belonging to a specific product. Then you could have a nested aggregation to sum all the quantity
fields of occurrences of line items with that referencedId
.
{
"aggregations": [
{
"name": "my-filter",
"type": "filter",
"filter": [
{
"type": "equals",
"field": "referencedId",
"value": "7594ed63b27345d39f61c82f0b4d4e52" // page.product.id
}
],
"aggregation": {
"name": "total-quantity",
"type": "sum",
"field": "quantity"
}
}
]
}
If you want the sums for all products, you could have a nested terms aggregation so you get buckets of quantity
sums per referencedId
{
"aggregations": [
{
"name": "my-filter",
"type": "filter",
"filter": [
{
"type": "equals",
"field": "type",
"value": "product"
}
],
"aggregation": {
"name": "per-line-item",
"type": "terms",
"field": "referencedId",
"aggregation": {
"name": "total-quantity",
"type": "sum",
"field": "quantity"
}
}
}
]
}