Faceted Search Implementation for Web Application

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Implementing Faceted Search for Web Applications

Faceted search is a filtering interface where users progressively narrow results across multiple dimensions (facets): category, price range, brand, rating, attributes. Each selected filter updates counts in other facets, showing how many results remain with further refinement. This dynamic counter behavior distinguishes faceted search from regular filtering.

Architecture: Where to Compute Facets

The key question — where aggregation happens:

Elasticsearch / OpenSearch — the right choice for thousands of items and above. Aggregations run on the engine side, no SQL queries needed.

PostgreSQL with jsonb + gin indexes — for tens of thousands of items, if Elasticsearch is overkill. Slower, but avoids additional infrastructure.

Typesense / Meilisearch — self-hosted alternatives with native facet support, simpler operations than Elasticsearch.

On frontend (client-side) — only for small datasets (up to 10,000 records) loaded entirely in the browser. Use Fuse.js or Lunr.js libraries.

Elasticsearch: Aggregations

POST /products/_search
{
  "query": {
    "bool": {
      "filter": [
        { "term": { "category": "laptops" } },
        { "range": { "price": { "gte": 50000, "lte": 150000 } } }
      ]
    }
  },
  "aggs": {
    "brands": {
      "terms": {
        "field": "brand.keyword",
        "size": 20,
        "min_doc_count": 1
      }
    },
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "key": "budget", "to": 50000 },
          { "key": "mid", "from": 50000, "to": 100000 },
          { "key": "premium", "from": 100000 }
        ]
      }
    },
    "rating": {
      "terms": {
        "field": "rating",
        "size": 5
      }
    },
    "has_stock": {
      "filter": { "term": { "in_stock": true } },
      "aggs": {
        "count": { "value_count": { "field": "id" } }
      }
    }
  },
  "size": 20,
  "from": 0
}

A special aspect of faceted search: when selecting a brand filter, the brand facet counts should show results excluding that filter (otherwise other brands show 0). This is solved via post_filter + global aggregation:

{
  "query": { "match_all": {} },
  "post_filter": {
    "term": { "brand.keyword": "Apple" }
  },
  "aggs": {
    "all_brands": {
      "global": {},
      "aggs": {
        "brands": {
          "terms": { "field": "brand.keyword", "size": 20 }
        }
      }
    },
    "filtered_price": {
      "filter": { "term": { "brand.keyword": "Apple" } },
      "aggs": {
        "price_stats": { "stats": { "field": "price" } }
      }
    }
  }
}

URL Schema for Filter State

Faceted search state must live in the URL — this enables sharing links to specific selections and preserves the back button:

/catalog?category=laptops&brand=apple,samsung&price=50000-150000&page=2

Parsing and serialization:

type FacetState = {
  category?: string;
  brand?: string[];
  price?: { min: number; max: number };
  rating?: number[];
  inStock?: boolean;
  page: number;
  sort: 'relevance' | 'price_asc' | 'price_desc' | 'rating';
};

function parseFacetState(searchParams: URLSearchParams): FacetState {
  const price = searchParams.get('price');
  const [priceMin, priceMax] = price ? price.split('-').map(Number) : [undefined, undefined];

  return {
    category: searchParams.get('category') ?? undefined,
    brand: searchParams.get('brand')?.split(',').filter(Boolean),
    price: priceMin && priceMax ? { min: priceMin, max: priceMax } : undefined,
    rating: searchParams.get('rating')?.split(',').map(Number),
    inStock: searchParams.get('inStock') === 'true',
    page: Number(searchParams.get('page') ?? 1),
    sort: (searchParams.get('sort') as FacetState['sort']) ?? 'relevance',
  };
}

function serializeFacetState(state: FacetState): URLSearchParams {
  const params = new URLSearchParams();
  if (state.category) params.set('category', state.category);
  if (state.brand?.length) params.set('brand', state.brand.join(','));
  if (state.price) params.set('price', `${state.price.min}-${state.price.max}`);
  if (state.rating?.length) params.set('rating', state.rating.join(','));
  if (state.inStock) params.set('inStock', 'true');
  if (state.page > 1) params.set('page', String(state.page));
  if (state.sort !== 'relevance') params.set('sort', state.sort);
  return params;
}

React: Faceted Search Components

Hook for state management with debounce:

import { useCallback, useMemo, useTransition } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useDebouncedCallback } from 'use-debounce';

export function useFacetSearch() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const state = useMemo(
    () => parseFacetState(searchParams),
    [searchParams]
  );

  const updateFilter = useCallback(
    (updates: Partial<FacetState>) => {
      const newState = { ...state, ...updates, page: 1 };
      const params = serializeFacetState(newState);
      startTransition(() => {
        router.push(`?${params.toString()}`, { scroll: false });
      });
    },
    [state, router]
  );

  const debouncedPriceUpdate = useDebouncedCallback(
    (min: number, max: number) => updateFilter({ price: { min, max } }),
    400
  );

  return { state, updateFilter, debouncedPriceUpdate, isPending };
}

Individual facet component:

type FacetOption = {
  value: string;
  label: string;
  count: number;
};

interface CheckboxFacetProps {
  title: string;
  options: FacetOption[];
  selected: string[];
  onChange: (values: string[]) => void;
  showMore?: boolean;
}

export function CheckboxFacet({
  title,
  options,
  selected,
  onChange,
  showMore = false,
}: CheckboxFacetProps) {
  const [expanded, setExpanded] = useState(false);
  const visible = expanded || !showMore ? options : options.slice(0, 5);

  const toggle = (value: string) => {
    const next = selected.includes(value)
      ? selected.filter((v) => v !== value)
      : [...selected, value];
    onChange(next);
  };

  return (
    <div className="facet">
      <h3 className="facet__title">{title}</h3>
      <ul className="facet__options">
        {visible.map((opt) => (
          <li key={opt.value}>
            <label className={opt.count === 0 ? 'facet__option--disabled' : ''}>
              <input
                type="checkbox"
                checked={selected.includes(opt.value)}
                onChange={() => toggle(opt.value)}
                disabled={opt.count === 0}
              />
              <span>{opt.label}</span>
              <span className="facet__count">{opt.count}</span>
            </label>
          </li>
        ))}
      </ul>
      {showMore && options.length > 5 && (
        <button onClick={() => setExpanded(!expanded)}>
          {expanded ? 'Hide' : `Show ${options.length - 5} more`}
        </button>
      )}
    </div>
  );
}

Price Slider

import * as Slider from '@radix-ui/react-slider';

interface PriceRangeProps {
  min: number;
  max: number;
  value: [number, number];
  onChange: (value: [number, number]) => void;
}

export function PriceRange({ min, max, value, onChange }: PriceRangeProps) {
  return (
    <div className="price-range">
      <div className="price-range__inputs">
        <input
          type="number"
          value={value[0]}
          min={min}
          max={value[1]}
          onChange={(e) => onChange([Number(e.target.value), value[1]])}
        />
        <span>—</span>
        <input
          type="number"
          value={value[1]}
          min={value[0]}
          max={max}
          onChange={(e) => onChange([value[0], Number(e.target.value)])}
        />
      </div>
      <Slider.Root
        min={min}
        max={max}
        value={value}
        onValueChange={onChange as (v: number[]) => void}
        step={1000}
      >
        <Slider.Track>
          <Slider.Range />
        </Slider.Track>
        <Slider.Thumb />
        <Slider.Thumb />
      </Slider.Root>
    </div>
  );
}

Typesense: Elasticsearch Alternative

For projects where Elasticsearch is overkill:

import Typesense from 'typesense';

const client = new Typesense.Client({
  nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }],
  apiKey: 'xyz',
  connectionTimeoutSeconds: 2,
});

const results = await client.collections('products').documents().search({
  q: query || '*',
  query_by: 'name,description',
  filter_by: buildTypesenseFilter(state),
  facet_by: 'brand,category,rating',
  max_facet_values: 20,
  page: state.page,
  per_page: 20,
  sort_by: sortMap[state.sort],
});

function buildTypesenseFilter(state: FacetState): string {
  const filters: string[] = [];
  if (state.brand?.length) filters.push(`brand:=[${state.brand.join(',')}]`);
  if (state.price) filters.push(`price:>=${state.price.min} && price:<=${state.price.max}`);
  if (state.rating?.length) filters.push(`rating:=[${state.rating.join(',')}]`);
  if (state.inStock) filters.push('in_stock:=true');
  return filters.join(' && ');
}

SEO for Faceted Search

Faceted URLs with filters create duplicate content. Strategy:

  • Index category pages without filters and most popular combinations (brand + category)
  • noindex on pages with price filters, sorting, multiple filters
  • canonical to base category page
  • rel="nofollow" on pagination links deeper than page 3
// In Next.js App Router
export async function generateMetadata({ searchParams }) {
  const state = parseFacetState(new URLSearchParams(searchParams));
  const hasComplexFilters = (state.brand?.length ?? 0) > 1
    || state.price
    || state.page > 1;

  return {
    robots: hasComplexFilters ? 'noindex,follow' : 'index,follow',
  };
}

Timeline

  • Simple faceted search (PostgreSQL, up to 5 facets, no counts): 3–5 days
  • Full-featured with Elasticsearch/Typesense (aggregations, counts, post_filter, URL state, SEO): 2–3 weeks
  • With custom price slider, instant search, mobile slide-out menu: another 3–5 days