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.

ItemsBuildIndex size (in memory)Bytes per item
1k535 µs182 KiB186
10k4.15 ms1.13 MiB118
100k36.3 ms9.68 MiB102
300k113 ms32.4 MiB113
500k180 ms44.6 MiB93.5
1M360 ms89.1 MiB93.4

Each filter call took:

Selections1k10k100k300k500k1M
None32.4 µs451 µs4.05 ms13.9 ms43.1 ms108 ms
1 field, 1 value18.4 µs177 µs1.54 ms5.28 ms9.18 ms24.7 ms
1 field, 3 values30.9 µs465 µs4.36 ms14.2 ms24.6 ms51.7 ms
Match all, 2 values13.2 µs136 µs1.37 ms4.14 ms6.95 ms14.3 ms
3 fields23.3 µs276 µs3.05 ms9.27 ms15.9 ms35.6 ms
10% candidate ids7.36 µs57.6 µs655 µs3.27 ms7.20 ms32.7 ms

API

FacetIndexConfig

The constructor accepts the items and a config.

Defines the fields available for faceted filtering.
FacetIndexConfig<Key extends string = 'id'>
PropTypeDefault
Facet fields keyed by name. The name is used as the key in FacetSelections and FacetIndexResult.facets, and as the value path when FacetFieldConfig.path is omitted.
Record<
string,
FacetFieldConfig
>
Key of each item's unique string identifier, used for FacetIndexInput.ids and returned in FacetIndexResult.ids.
Key
"id"
Type
Record<
string,
FacetFieldConfig
>
Description
Facet fields keyed by name. The name is used as the key in FacetSelections and FacetIndexResult.facets, and as the value path when FacetFieldConfig.path is omitted.
Type
Key
Description
Key of each item's unique string identifier, used for FacetIndexInput.ids and returned in FacetIndexResult.ids.

FacetIndex

In-memory faceted filtering. Fields combine with AND. Values within a field combine according to the field's 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',
>
PropType
The configured field names.
readonly string[]
Returns the matching item IDs and the bucket counts for every field.
(input?: {
ids?: readonly string[]
selections?: Record<
string,
readonly string[]
>
}) => {
facets: Record<
string,
FacetBucket[]
>
ids: string[]
}
Returns every value of a field across all items, sorted. Returns an empty array for unconfigured fields.
(
name: string,
) => readonly string[]
Type
readonly string[]
Description
The configured field names.
Type
(input?: {
ids?: readonly string[]
selections?: Record<
string,
readonly string[]
>
}) => {
facets: Record<
string,
FacetBucket[]
>
ids: string[]
}
Description
Returns the matching item IDs and the bucket counts for every field.
Type
(
name: string,
) => readonly string[]
Description
Returns every value of a field across all items, sorted. Returns an empty array for unconfigured fields.

FacetFieldConfig

Configures how a field is read and matched.
PropTypeDefault
How selected values within this field combine. "any" matches items that have at least one selected value, "all" matches items that have every selected value.
'any' | 'all'
"any"
Dot-separated path to the item's values for this field. Arrays along the path are flattened. Defaults to the field name.
string
Type
'any' | 'all'
Description
How selected values within this field combine. "any" matches items that have at least one selected value, "all" matches items that have every selected value.
Type
string
Description
Dot-separated path to the item's values for this field. Arrays along the path are flattened. Defaults to the field name.

FacetIndexInput

Selections and optional candidate IDs for a filter pass.
PropType
Restricts both the results and the bucket counts to these items, e.g. the hits from a preceding text search.
readonly string[]
Selected values keyed by field name. Fields with no selected values do not filter.
Record<
string,
readonly string[]
>
Type
readonly string[]
Description
Restricts both the results and the bucket counts to these items, e.g. the hits from a preceding text search.
Type
Record<
string,
readonly string[]
>
Description
Selected values keyed by field name. Fields with no selected values do not filter.

FacetIndexResult

Matching item IDs and facet buckets.
PropType
Buckets for every configured field, keyed by field name. Each field lists every value found in the full item set, sorted by key, including values with a docCount of 0.
Record<
string,
FacetBucket[]
>
IDs of the candidate items that match all selections, in candidate order.
string[]
Type
Record<
string,
FacetBucket[]
>
Description
Buckets for every configured field, keyed by field name. Each field lists every value found in the full item set, sorted by key, including values with a docCount of 0.
Type
string[]
Description
IDs of the candidate items that match all selections, in candidate order.

FacetBucket

A facet value and its result count.
PropType
Number of candidate items that would match if this value were selected, given the selections in every other field.
number
The facet value.
string
Whether this value is in the field's current selections.
boolean
Type
number
Description
Number of candidate items that would match if this value were selected, given the selections in every other field.
Type
string
Description
The facet value.
Type
boolean
Description
Whether this value is in the field's current selections.

getFacetFilterSetProps

Accepts a FacetIndex and these options.

FacetFilterSetOptions<
TDefs extends FilterDefinitions = FilterDefinitions,
>
PropType
Returns the ids of the items that pass the filters 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.
    (
    values: FilterValues<TDefs>,
    ) =>
    | readonly string[]
    | undefined
    Type
    (
    values: FilterValues<TDefs>,
    ) =>
    | readonly string[]
    | undefined
    Description
    Returns the ids of the items that pass the filters 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[]
      >
      Updated by Ryan Bower