Facet Index
Index in-memory data by field values, and count the results for each value.
import {FacetIndex} from "@qualcomm-ui/utils/facet-index"Overview
Picture a laptop store with two filters, Processor and Operating System. Each option shows how many laptops match it. Select Snapdragon X Elite below:
- 1: Windows, AMD Ryzen 9
- 2: Linux, AMD Ryzen 9
- 3: macOS, Apple M-series
- 4: macOS, Apple M-series
- 5: macOS, Apple M-series
- 6: Windows, Intel Core i9
- 7: Linux, Intel Core i9
- 8: Windows, Snapdragon X Elite
- 9: Linux, Snapdragon X Elite
import {type ReactElement, useState} from "react"
import {getFacetFilterSetProps} from "@qualcomm-ui/core/filter-set"
import {
defineFilters,
type FilterValues,
listFilter,
} from "@qualcomm-ui/core/filters"
import {FilterPanel} from "@qualcomm-ui/react/filter-panel"
import {CheckboxGroupFilter} from "@qualcomm-ui/react/filters"
import {ListCollection} from "@qualcomm-ui/utils/collection"
import {FacetIndex} from "@qualcomm-ui/utils/facet-index"
const laptops = [
{id: "1", os: "Windows", processor: "AMD Ryzen 9"},
{id: "2", os: "Linux", processor: "AMD Ryzen 9"},
{id: "3", os: "macOS", processor: "Apple M-series"},
{id: "4", os: "macOS", processor: "Apple M-series"},
{id: "5", os: "macOS", processor: "Apple M-series"},
{id: "6", os: "Windows", processor: "Intel Core i9"},
{id: "7", os: "Linux", processor: "Intel Core i9"},
{id: "8", os: "Windows", processor: "Snapdragon X Elite"},
{id: "9", os: "Linux", processor: "Snapdragon X Elite"},
]
const filters = defineFilters({
os: listFilter({
collection: new ListCollection({items: ["Windows", "macOS", "Linux"]}),
label: "Operating system",
}),
processor: listFilter({
collection: new ListCollection({
items: [
"AMD Ryzen 9",
"Apple M-series",
"Intel Core i9",
"Snapdragon X Elite",
],
}),
label: "Processor",
}),
})
const facetIndex = new FacetIndex(laptops, {
fields: {os: {}, processor: {}},
})
type LaptopFilters = FilterValues<typeof filters>
const facetProps = getFacetFilterSetProps<typeof filters>(facetIndex)
export function FacetIndexOverviewDemo(): ReactElement {
const [value, setValue] = useState<LaptopFilters>({})
const {ids} = facetIndex.filter({
selections: {os: value.os ?? [], processor: value.processor ?? []},
})
return (
<div className="flex w-full max-w-3xl flex-wrap items-start gap-6">
<FilterPanel.Root
className="w-72"
filters={filters}
onValueChange={setValue}
value={value}
{...facetProps}
>
<FilterPanel.Filter filter={filters.processor}>
<CheckboxGroupFilter />
</FilterPanel.Filter>
<FilterPanel.Filter filter={filters.os}>
<CheckboxGroupFilter />
</FilterPanel.Filter>
</FilterPanel.Root>
<ul className="text-neutral-primary font-body-md min-w-60 flex-1">
{laptops
.filter((laptop) => ids.includes(laptop.id))
.map((laptop) => (
<li key={laptop.id}>
{laptop.id}: {laptop.os}, {laptop.processor}
</li>
))}
</ul>
</div>
)
}The Operating System counts updated to match your selection, so you can see which options have results before you pick one.
This is called faceted search. We provide a FacetIndex utility class to enable this type of search in your applications.
Usage
FacetIndex indexes a list of items by the fields you configure. Each of your items must have a unique string identifier. This defaults to id, but can be changed with the idField option.
const builds = [
{buildId: "1", platform: ["android", "linux"], status: "Failed"},
{buildId: "2", platform: ["windows"], status: "Passed"},
{buildId: "3", platform: ["linux"], status: "Passed"},
]
const facetIndex = new FacetIndex(builds, {
fields: {platform: {}, status: {}},
idField: "buildId",
})Each call to filter returns the ids of the matching items, and a result count for every value of every field.
const {facets, ids} = facetIndex.filter({
selections: {platform: ["linux"]},
})// result:
{
"ids": ["1", "3"],
"facets": {
"platform": [
{"docCount": 1, "key": "android", "selected": false},
{"docCount": 2, "key": "linux", "selected": true},
{"docCount": 1, "key": "windows", "selected": false}
],
"status": [
{"docCount": 1, "key": "Failed", "selected": false},
{"docCount": 1, "key": "Passed", "selected": false}
]
}
}Counts
Each field has a bucket for every value in the items. The above example has two buckets for status, one for each possible value. A bucket's docCount is the number of items with its value, filtered by the other fields.
Selections in different fields combine with AND. In the example above, linux is selected, so each status count includes only Linux builds:
// facets.status:
[
{"docCount": 1, "key": "Failed", "selected": false},
{"docCount": 1, "key": "Passed", "selected": false},
]By default, selections in the same field combine with OR. Selecting windows as well adds build 2 instead of removing builds, so the platform counts ignore the linux selection:
// facets.platform:
[
{"docCount": 1, "key": "android", "selected": false},
{"docCount": 2, "key": "linux", "selected": true},
{"docCount": 1, "key": "windows", "selected": true},
]Matching All Values
Set match to "all" to require every selected value.
const devices = [
{id: "1", features: ["5g", "wifi-7"]},
{id: "2", features: ["5g"]},
{id: "3", features: ["bluetooth", "wifi-7"]},
]
const facetIndex = new FacetIndex(devices, {
fields: {features: {match: "all"}},
})
facetIndex.filter({selections: {features: ["5g"]}})// result:
{
"ids": ["1", "2"],
"facets": {
"features": [
{"docCount": 2, "key": "5g", "selected": true},
{"docCount": 0, "key": "bluetooth", "selected": false},
{"docCount": 1, "key": "wifi-7", "selected": false}
]
}
}Counts follow the same rule. A value's count is the number of results for the current selections plus that value.
Nested Values
Set path to read a nested property.
const builds = [
{id: "1", target: {devices: [{chip: "SM8650"}, {chip: "SM8550"}]}},
{id: "2", target: {devices: [{chip: "SM8550"}]}},
]
const facetIndex = new FacetIndex(builds, {
fields: {chip: {path: "target.devices.chip"}},
})
facetIndex.getValues("chip")
// ["SM8550", "SM8650"]Arrays along the path are flattened, so this field holds the chip of every device.
Narrowing the Candidates
FacetIndex only matches field values. To combine it with another filter, like a text search, pass that filter's matches as ids. They limit both the results and the counts.
const hits = builds
.filter((build) => build.name.includes(query))
.map((build) => build.id)
const {facets, ids} = facetIndex.filter({
ids: hits,
selections: {status: ["Passed"]},
})Results keep the order of ids, so ranked results retain their order. Unknown ids are skipped.
Performance
Large datasets are supported, but we recommend a web worker for datasets exceeding 100k items.
These results were recorded on an M4 Max with 64GB of RAM. Each item had five fields, including arrays, nested paths, and a field with 1,000 values.
| Items | Build | Index size (in memory) | Bytes per item |
|---|---|---|---|
| 1k | 535 µs | 182 KiB | 186 |
| 10k | 4.15 ms | 1.13 MiB | 118 |
| 100k | 36.3 ms | 9.68 MiB | 102 |
| 300k | 113 ms | 32.4 MiB | 113 |
| 500k | 180 ms | 44.6 MiB | 93.5 |
| 1M | 360 ms | 89.1 MiB | 93.4 |
Each filter call took:
| Selections | 1k | 10k | 100k | 300k | 500k | 1M |
|---|---|---|---|---|---|---|
| None | 32.4 µs | 451 µs | 4.05 ms | 13.9 ms | 43.1 ms | 108 ms |
| 1 field, 1 value | 18.4 µs | 177 µs | 1.54 ms | 5.28 ms | 9.18 ms | 24.7 ms |
| 1 field, 3 values | 30.9 µs | 465 µs | 4.36 ms | 14.2 ms | 24.6 ms | 51.7 ms |
| Match all, 2 values | 13.2 µs | 136 µs | 1.37 ms | 4.14 ms | 6.95 ms | 14.3 ms |
| 3 fields | 23.3 µs | 276 µs | 3.05 ms | 9.27 ms | 15.9 ms | 35.6 ms |
| 10% candidate ids | 7.36 µs | 57.6 µs | 655 µs | 3.27 ms | 7.20 ms | 32.7 ms |
API
FacetIndexConfig
The constructor accepts the items and a config.
FacetIndexConfig<Key extends string = 'id'>
Record<
string,
FacetFieldConfig
>
KeyFacetIndex
match setting.Bucket counts are disjunctive: for
"any" fields, each bucket ignores the
field's own selections so that sibling values report how many results they
would add. For "all" fields, each bucket counts the current selections plus
that value.Field values are indexed once on construction. Each filter pass then visits every candidate once, so its cost grows with the number of candidates and their values rather than with the number of distinct values per field.
FacetIndex<
Item extends Record<Key, string>,
Key extends string = 'id',
>
readonly string[]
(input?: {
ids?: readonly string[]
selections?: Record<
string,
readonly string[]
>
}) => {
facets: Record<
string,
FacetBucket[]
>
ids: string[]
}
(
name: string,
) => readonly string[]
FacetFieldConfig
'any' | 'all'
"any" matches items that
have at least one selected value, "all" matches items that have every
selected value.string// item: {target: {os: "linux"}}
path: "target.os" // values: ["linux"]
// item: {devices: [{chip: "SM8650"}, {chip: "SM8550"}]}
path: "devices.chip" // values: ["SM8650", "SM8550"]
// item: {targets: [{os: ["android", "linux"]}, {os: "windows"}]}
path: "targets.os" // values: ["android", "linux", "windows"]
FacetIndexInput
readonly string[]
Record<
string,
readonly string[]
>
FacetIndexResult
Record<
string,
FacetBucket[]
>
docCount of 0.string[]
FacetBucket
getFacetFilterSetProps
Accepts a FacetIndex and these options.
FacetFilterSetOptions<
TDefs extends FilterDefinitions = FilterDefinitions,
>
(
values: FilterValues<TDefs>,
) =>
| readonly string[]
| undefined
FacetIndex can't
apply, such as text, range, and date filters, or a separate text search.
Called with the same values as the counts. Return undefined to include
every item.FacetSelections
Record<
string,
readonly string[]
>