Custom table

If data lives in your own table of the site database (stock per warehouse, ratings, relations), it can become a filter without code. The easiest way — Sources tab → "Custom table": pick the table and columns, press "Test", then "Add to set". The same in the set JSON:

"sql": {
    "stock_ny": {
        "table": "shop_stock",
        "link": "product_id",
        "value": "qty",
        "kind": "number",
        "agg": "sum",
        "where": {"warehouse": "ny"},
        "label": "Stock in New York"
    },
    "badge": {
        "table": "shop_badges", "link": "resource_id", "value": "badge_id",
        "labels": {"table": "shop_badge_names", "id": "id", "name": "name"},
        "label": "Badges"
    }
},
"numbers": {"sql:stock_ny": {}},
"facets":  {"sql:badge": {}}
tabletable without the site table prefix (for a full name add "prefix": false)
linkcolumn with the product (resource) id
valuevalue column
kindtext, number, date (timestamp or date string), bool
aggif a product has several rows: list — all values (default for text), sum, min, max, first (default for numbers and dates)
where"column = value" conditions
orderrow order column (for first)
labelscaption dictionary: the filter shows names instead of ids

Your own PHP source

For computed data (discount percent, external API data, complex relations) write a source class. It returns a field list and values for a batch of products in one query:

 ['label' => 'Discount, %', 'kind' => 'number']];
    }

    /** Values for a batch of products: [id => [field => value]] */
    public function load(array $ids, array $fields): array
    {
        $out = [];
        $sql = 'SELECT id, price, old_price FROM ' . $this->table('ms3_products')
            . ' WHERE id IN (' . self::in($ids) . ') AND old_price > price';
        foreach ($this->rows($sql) as $r) {
            $out[(int)$r['id']]['discount'] = round(($r['old_price'] - $r['price']) / $r['old_price'] * 100);
        }
        return $out;
    }
}

In the set (JSON tab):

"providers": [{"class": "MyShop\\BitFacet\\DiscountProvider", "options": {}}],
"numbers": {"calc:discount": {"label": "Discount, %"}}

Reporting changes from your code

An import or script changes products directly in the database — tell BitFacet, and the changes reach the filter without a full rebuild:

$bf = $modx->services->get('BitFacet');

// these products changed — to the change journal (visible from the next request)
$bf->queueChanged([15, 16, 42]);

// everything changed (large import) — mark indexes outdated and rebuild
$bf->queueStale();

The queue is processed at the end of the request (in php-fpm — after the response). Rebuild a set right away:

$info = $modx->services->get('BitFacet')->updater('catalog')->rebuild();
// ['n' => products, 'vn' => variants, …] or null if a build is already running

Querying the index from PHP

The index can be used without the snippet — for example, for a "Similar products" block or your own API:

use BitFacet\Index\Query;

$index = $modx->services->get('BitFacet')->store('catalog')->open();
$res = (new Query($index))->run([
    'maps'    => ['live'],                              // published only
    'base'    => ['section' => [5]],                    // section 5 with subsections
    'filters' => ['ms:color' => ['red', 'blue'],        // OR inside a filter, AND between filters
                  'ms:vendor' => ['nike']],
    'ranges'  => ['ms:price' => [1000, null]],          // from 1000, no upper bound
    'counts'  => ['ms:size'],                           // value counts
    'stats'   => ['ms:price'],                          // min/max
    'sort'    => 'price', 'dir' => 'asc',
    'limit'   => 12, 'offset' => 0,
]);
// $res['total'], $res['ids'], $res['counts']['ms:size'] = [value => count], $res['stats']['ms:price']

Values in filters are index keys: as on the Values tab (lowercase).

Where things are

core/components/bitfacet/
    data/sets/        filter sets (*.json)
    data/index/       indexes, error log, turbo socket
    src/Index/        core: bitmaps, building, queries
    src/Provider/     sources: resources, TVs, MiniShop3, custom tables
    src/Front/        site filter and turbo mode
    cli/rebuild.php   rebuild from the console and cron
    cli/turbo.php     turbo mode process
assets/components/bitfacet/
    js/web/bitfacet.js        filter without page reloads
    publicConnector.php       filter endpoint