How do I count unique values within variant arrays?
In this example we want to know how many sofas in our collection have a 1.5 seater option available.
If the records in our collection looked like this:
{
"id": "6890532208798",
"name": "blue sofa",
"variant_sizes": [
"3-Seater (Queen)",
"2.5-Seater (Double)",
"1.5-Seater (Single)",
]
},
{
"id": "3892532108799",
"name": "red sofa",
"variant_sizes": [
"2.5-Seater (Double)",
"1.5-Seater (Single)",
]
},
{
"id": "88925325668797",
"name": "green sofa",
"variant_sizes": [
"3-Seater (Queen)",
"2.5-Seater (Double)",
]
},
Then running a query with a filter like the example below would return the records for the blue and red sofa which both have 1.5 seater options i.e. 2 sofas come in this size option.
Example of query:
{
"q": "",
"filter": "variant_sizes ~ ['1.5-Seater (Single)']"
}
An alternative option is to run a query with a count on variant_sizes
like the example below. The response would return all 3 records regardless of their seating options, but the count
within the response would also identify that 2
sofas have 1.5-Seater (Single)
options.
Example of query:
{
"q": "",
"count": "variant_sizes"
}
Example of response:
"variant_sizes":{
"count": {
"3-Seater (Queen)": 2,
"2.5-Seater (Double)": 3,
"1.5-Seater (Single)": 2
}
}
In the example below the elements within "variant_sizes"
represent the in-stock size options so there are repeated entries i.e. the blue sofa has three 1.5-Seater options in stock
{
"id": "6890532208798",
"name": "blue sofa",
"variant_sizes": [
"3-Seater (Queen)",
"2.5-Seater (Double)",
"1.5-Seater (Single)",
"1.5-Seater (Single)",
"1.5-Seater (Single)",
]
},
{
"id": "3892532108799",
"name": "red sofa",
"variant_sizes": [
"2.5-Seater (Double)",
"2.5-Seater (Double)",
"1.5-Seater (Single)",
]
},
{
"id": "88925325668797",
"name": "green sofa",
"variant_sizes": [
"3-Seater (Queen)",
"2.5-Seater (Double)",
"2.5-Seater (Double)",
]
},
Running a query with the same filter
we ran before will still return the records for the blue and red sofa i.e. 2 records, however running a query with the same count
as we did before will now return "1.5-Seater (Single)": 4
which tells us the stock availability of the 1.5-Seater
not how many sofas have 1.5 seater options