Filtering & Facets

Combining filters

Compose facet, price, collection scope, exclusion, and in-stock filters into a single Kelp request.

Real storefronts combine several filter types on every request: a collection scope, user-selected facets (brand, colour, size), a price range, an in-stock gate, and exclusion rules that hide unavailable or hidden products.

All filter clauses live in one flat filters array. Every clause is ANDed, so the result set must satisfy all of them simultaneously.

Clause types

PurposeOperatorField exampleNotes
Collection scope=collectionsScope results to one collection page
Facet refinement (OR)=vendor, productCategoryMulti-value IN-list; one clause per facet
Facet refinement (AND)=tagsOne clause per value, each must match
Price range (both bounds)rangepriceOne clause with [min, max]
Price lower bound only>=priceUsed when max is not set
Price upper bound only<=priceUsed when min is not set
In-stock gate>variantInventoryTotalvalues: ['0']
Exclusion!=productType, tagsHide gift cards, hidden products, etc.
Collection-scoped exclusion!=tagsApplied only for specific collection pages

Filter builder pattern

A clean way to keep this manageable is a set of small builder functions, each returning KelpFilter[], that you spread into the final array:

import type { KelpFilter } from '@kelpclick/client';

/** Scope to a collection page. */
function toCollectionFilter(field: string, handle?: string): KelpFilter[] {
  if (!handle) return [];
  return [{ field, op: '=', values: [handle] }];
}

/** Facet refinements - OR within each facet, AND across facets. */
function toFacetFilters(
  refinements: Record<string, string[]>,
): KelpFilter[] {
  return Object.entries(refinements)
    .filter(([, values]) => values.length > 0)
    .map(([field, values]) => ({ field, op: '=' as const, values }));
}

/** Price range from optional min/max. */
function toPriceFilters(
  field: string,
  min?: number,
  max?: number,
): KelpFilter[] {
  const validMin = Number.isFinite(min) ? min : undefined;
  const validMax = Number.isFinite(max) ? max : undefined;
  if (validMin !== undefined && validMax !== undefined && validMin > validMax) {
    return [];
  }
  if (validMin !== undefined && validMax !== undefined) {
    return [{ field, op: 'range', values: [String(validMin), String(validMax)] }];
  }
  const out: KelpFilter[] = [];
  if (validMin !== undefined) out.push({ field, op: '>=', values: [String(validMin)] });
  if (validMax !== undefined) out.push({ field, op: '<=', values: [String(validMax)] });
  return out;
}

/** In-stock gate. */
function toInStockFilter(requireInStock: boolean): KelpFilter[] {
  if (!requireInStock) return [];
  return [{ field: 'variantInventoryTotal', op: '>', values: ['0'] }];
}

/** Exclusions - hide product types or tagged products. */
function toExclusionFilters(
  excludeProductTypes: string[],
  excludeTags: string[],
): KelpFilter[] {
  const out: KelpFilter[] = [];
  if (excludeProductTypes.length) {
    out.push({ field: 'productType', op: '!=', values: excludeProductTypes });
  }
  for (const tag of excludeTags) {
    out.push({ field: 'tags', op: '!=', values: [tag] });
  }
  return out;
}

Composing a full filter set

With those builders, assembling the final filters array is a single spread:

import { createKelpClient } from '@kelpclick/client';

const kelp = createKelpClient({
  searchUrl: 'https://{TENANT_ID}-search.kelp.click',
  analyticsUrl: 'https://{TENANT_ID}-events.kelp.click',
  apiKey: 'kelp_...',
});

// User state (from URL params / UI)
const collectionHandle = 'summer-sale';
const refinements = {
  vendor: ['globex', 'initech'],
  productCategory: ['footwear'],
};
const priceMin = 50;
const priceMax = 150;
const requireInStock = true;

// Static config
const excludeProductTypes = ['Gift Card'];
const excludeTags: string[] = [];

const filters = [
  ...toCollectionFilter('collections', collectionHandle),
  ...toFacetFilters(refinements),
  ...toPriceFilters('price', priceMin, priceMax),
  ...toInStockFilter(requireInStock),
  ...toExclusionFilters(excludeProductTypes, excludeTags),
];

// filters = [
//   { field: 'collections',         op: '=',     values: ['summer-sale'] },
//   { field: 'vendor',              op: '=',     values: ['globex', 'initech'] },
//   { field: 'productCategory',     op: '=',     values: ['footwear'] },
//   { field: 'price',               op: 'range', values: ['50', '150'] },
//   { field: 'variantInventoryTotal', op: '>',   values: ['0'] },
//   { field: 'productType',         op: '!=',    values: ['Gift Card'] },
// ]

const res = await kelp.browse('products', {
  filters,
  facets: ['vendor', 'productCategory', 'collections'],
  sort: [{ field: 'variantsInStockPercentage', direction: 'desc' }],
  perPage: 24,
});

Builder functions that return [] when their inputs are absent mean the spread is always safe - no conditional spreading needed at the call site.

Collection-scoped exclusions

Some exclusion rules should only apply when browsing a specific collection - for example, hiding a product tagged sale-only on every page except the sale collection itself. Handle this by checking the active handle before adding the clause:

interface CollectionScopedExclusion {
  tag: string;
  exceptCollections: string[];
}

function toScopedExclusionFilters(
  rules: CollectionScopedExclusion[],
  collectionHandle?: string,
): KelpFilter[] {
  return rules
    .filter((rule) => !rule.exceptCollections.includes(collectionHandle ?? ''))
    .map((rule) => ({ field: 'tags', op: '!=' as const, values: [rule.tag] }));
}

Search vs browse

The same filters array works identically on both search and browse. The only difference is that search requires a q string:

await kelp.browse('products', {
  filters,
  facets: ['vendor', 'productCategory'],
  sort: [{ field: 'price', direction: 'asc' }],
  perPage: 24,
});

Order of clauses

The Kelp backend ANDs all clauses regardless of the order they appear in the array, so the order does not affect results. However, keeping a consistent order (collection scope, facets, price, in-stock, exclusions) makes filter arrays easier to read and debug.

On this page