Esc
ZeroIndex
GuidesAPI referenceSDKsChangelogOverviewBuy ZeroIndex

Faceted search

View as MarkdownThe page as plain text

Show counts for each category, brand or price range next to the results, and let people narrow down with one click.

Facets are the lists of filters you see beside search results in a shop, each with a count: Audio (24), Lighting (9). ZeroIndex returns these counts in the same request as the results.

Ask for facets

Any field in filterableAttributes can be a facet. Pass the ones you want to count.

curl https://api.zeroindex.test/v1/indexes/products/search \
  -H "Authorization: Bearer $ZEROINDEX_KEY" \
  -d '{ "q": "wireless", "facets": ["category", "brand"] }'
const { hits, facetDistribution } = await client.index("products").search("wireless", {
  facets: ["category", "brand"],
});
results = client.index("products").search("wireless", {"facets": ["category", "brand"]})

The response counts how many matching documents have each value:

{
  "facetDistribution": {
    "category": { "Audio": 24, "Accessories": 11, "Lighting": 3 },
    "brand": { "Vesterlund": 17, "Casa Bruna": 12, "Tarnelli": 9 }
  }
}

Narrow down

When someone ticks a value, add it to the filter and search again. Values in the same facet are joined with OR, and different facets with AND.

const selected = { category: ["Audio"], brand: ["Vesterlund", "Tarnelli"] };

const filter = Object.entries(selected)
  .map(([field, values]) => `${field} IN [${values.map((value) => `"${value}"`).join(", ")}]`)
  .join(" AND ");

await client.index("products").search("wireless", { filter, facets: ["category", "brand"] });

Price ranges

Number fields return their lowest and highest value in facetStats. Use them to set the ends of a price slider, then filter with price 40 TO 120.

{
  "facetStats": {
    "price": { "min": 19, "max": 349 }
  }
}