Customers that bought a specific product

How to use the Metrics API to get the total number of customers that bought a specific product or bundle

The problem

You want to get the total number of customers that bought a specific SKU (or bundle — identified by their code) from your catalog, over a selected date and time range.

The solution

Query

You need to perform a stats query setting the required query keys as follows and adding the optional ones based on your needs:

Since the query is on the order resource and each order is associated with a customer, to get the total number of unique customers you need to use the cardinality operator. Using value_count would lead to wrong results, counting one different customer for each order (e.g. let's assume you have 2 customers that placed 3 and 7 orders — the cardinality computation would be 2, while the value_count one would be 10). Please remember that the cardinality operator gives just estimated results.

Filter

Set the desired date and time range using the date_from and date_to keys and add an additional filter on the line items field to restrict the related computation to the selected SKU or bundle code only:

As shown in the example below, use placed_at as the date_field in the date filter if you want the results to count all the orders that were placed in the selected date and time range (read more about this).

Example

The following request uses the Metrics API to get the total number of customers that bought a specific SKU:

curl -g -X POST \
  'https://{{your_domain}}.commercelayer.io/metrics/orders/stats' \
  -H 'Accept: application/vnd.api.v1+json' \
  -H 'Content-Type: application/vnd.api+json' \
  -H 'Authorization: Bearer {{your_access_token}}' \
  -d '{
    "stats": {
      "field": "customer.email",
      "operator": "cardinality"
    },
    "filter": {
      "order": {
        "date_from": "2021-01-01T00:00:00Z",
        "date_to": "2021-12-31T23:59:00Z",
        "date_field": "placed_at"
      },
      "line_items": {
        "codes": {
          "in": [ "TSHIRT01" ]
        }
      }
    }
  }'

Similar cases

Just changing a couple of query keys and/or filter parameters you can address lots of very similar use cases, such as:

Last updated