AlgoViz

API search and filtering

easy 25 min

A list API lets the caller narrow, order and search.

Video lesson · Chapter 1 of 6

Apply filters consistently

0:00 / 3:48

Filter, sort and search in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A list endpoint usually serves many screens, and each needs a different part of the list. Filtering keeps the rows whose fields match, sorting puts them in order, and searching finds rows by words that people type. Together with pagination they decide what one request returns.

Filters work on fields with exact meanings: price below 100, in stock. Search works on text and ranks by how well it matches. They look alike in a URL, but they use different indexes and often different systems.

Why it exists

Someone wants wireless headphones under 100 with four stars. Without server-side filters the client must download everything and look for itself: slow, wasteful and impossible on a phone.

Once callers can ask questions, they can also ask very expensive or harmful ones. An API therefore offers a list of fields and operators, checks every value, and puts a limit on the work. Freedom inside a fence.

A short history

  1. January 2005

    RFC 3986 defines the URI syntax, including the query part and which characters must be percent-encoded.

  2. February 2008

    PostgreSQL 8.3 moves full-text search into the core database.

  3. May 2015

    JSON:API 1.0 gives conventions for sort, sparse fieldsets and a reserved filter family of parameters.

  4. June 2026

    RFC 10008 defines the HTTP QUERY method: a safe, repeatable request with the question in its body.

Words to know

Filter
A condition on a field, such as price below 100.
Operator
How to compare: eq, gt, in and so on.
Allowlist
The fields and operators callers may use. Everything else is refused.
Sparse fieldset
Returning only the fields that were asked for.
Full-text search
Finding documents by words and ranking them.
Inverted index
A map from each word to the documents that contain it.
Stemming
Reducing word forms to one, such as headphones to headphone.
Relevance
A score for how well a document fits the query.

How it works

Step through the idea, or press Play.

Step 1 of 3

Parse and check. Only known fields and operators, right types, sensible limits

Understand it

Start here

The lost umbrella

Imagine the lost property office of a station. Twelve umbrellas hang there. You could look through all of them, or tell the clerk what you know: the colour, the size, the day. Or you just say what you would call it.

Lost property
123456789101112Here are all 12All twelveLOST PROPERTY

The clerk does the looking, and only answers the questions on the card.

Why

On the server, not on the phone

Server-side: GET /products?search=wireless&price_lt=100&rating_gte=4&limit=20

  • Sends only what is needed: 20 items, about 40 KB
  • The database does the heavy work
  • Works with pagination
  • Keeps working with millions of rows

Client-side: GET /products, then filter in the browser

  • Sends 10,000 items, about 20 MB
  • Slow on mobile connections
  • Uses a lot of memory
  • Pagination brings nothing

The download

10,000×2 KB=20 MB=160 Mbit;⇒;1605=32 s20×2 KB=40 KB⇒0.064 s10{,}000 \times 2\ \text{KB} = 20\ \text{MB} = 160\ \text{Mbit} ;\Rightarrow; \frac{160}{5} = 32\ \text{s} \qquad 20 \times 2\ \text{KB} = 40\ \text{KB} \Rightarrow 0.064\ \text{s}
Assuming 2 KB per item and 5 Mbit/s. The ratio, 500 to 1, does not depend on the connection.

Three tools

  • Filtering

    Narrow by field values: equal, greater, less, contains. ?category=electronics&price_lt=100

  • Sorting

    Order by one or more fields, up or down. ?sort=price:asc,rating:desc

  • Full-text search

    Words as people type them, ranked, with typos forgiven. ?q=wireless+noise+cancelling

Filtering

Operators

Comparison operators

OperatorMeaningExampleIn SQL
eqEqualstatus_eq=activestatus = 'active'
neNot equalstatus_ne=deletedstatus <> 'deleted'
gtGreater thanprice_gt=100price > 100
gteGreater or equalrating_gte=4rating >= 4
ltLess thanprice_lt=50price < 50
lteLess or equalquantity_lte=10quantity <= 10
inAny of a liststatus_in=active,pendingstatus IN (...)
ninNone of a listcategory_nin=deleted,archivedcategory NOT IN (...)
likePatternname_like=wirelessname ILIKE '%wireless%'
Others: contains and all for arrays, starts and ends for text. Leave regular expressions out of public APIs: one bad pattern can be very slow. NOT IN finds nothing when its list holds a null.

Special values

KindExampleRule
Several filterscategory=electronics&price_gte=50&price_lte=200&in_stock=trueJoined by AND
Several valuescategory=electronics,accessoriesAny of them, OR
Array holds a valuetags_contains=wirelessThe list includes it
True or falsein_stock=true, featured=falseAccept true and false, perhaps 1 and 0. Refuse the rest
Nulldeleted_at_is_null=true, parent_id_exists=falseNull needs its own operator: equals never matches it
Datescreated_after=2024-01-01ISO 8601 with a time zone, and say whether the border day is included

Syntax

How to write a filter in a URL

PatternExampleForAgainst
Flat suffixprice_gte=100&price_lte=500&category_in=a,bEasy to read and write, works everywhereThe operator is part of the name: what about a field called price_in?
Bracket operatorprice[gte]=100&price[lte]=500Field and operator are separate; several per field. Stripe uses it for datesBrackets should be percent-encoded
Filter namespacefilter[status]=active&filter[price][gte]=100Keeps filters apart from page and sort; can nest. JSON:API reserves filterLong
Value prefixprice=gte:100ShortA value may contain a colon
Expressionfilter=price >= 100 AND in_stock = trueAny logic. Google AIP-160 and OData work this wayNeeds a parser and strict limits
The first bracket form is often called LHS brackets, because the operator stands left of the equals sign, and the prefix form RHS colon. JSON:API reserves the word filter but leaves the strategy to you. Choose one and keep it.
HTTP
# (status = active OR status = pending) AND category = electronicsGET /products?status[in]=active,pending&category=electronics# price < 50 OR rating > 4.5: different fields, so AND is not enoughGET /products?filter={"or":[{"price":{"lt":50}},{"rating":{"gt":4.5}}]}     (percent-encoded in reality)GET /products?or[0][price_lt]=50&or[1][rating_gt]=4.5# A long question: in the body, with a safe and repeatable methodQUERY /productsContent-Type: application/json{"or": [{"price": {"lt": 50}}, {"rating": {"gt": 4.5}}], "sort": "-rating", "limit": 20}
URLs have limits. RFC 9110 recommends supporting at least 8,000 octets, but some tools accept less. QUERY is new; where it is not supported, use POST /products/search.

Callers often want only some fields: ?fields=id,name,price,rating returns four. JSON:API writes fields[products]=name,price. Allow only documented names: never expose internal column names.

Sorting

Order

Three ways to write it

StyleExampleNote
Colonsort=price:ascClear, long
Minus signsort=-price and sort=priceShort, used by JSON:API. Do not use a plus: in a query string it means a space
Two parameterssort_by=price&sort_order=descSimple, but only one field

sort=category:asc,price:desc

ProductCategory, upPrice, downPlace
Laptop Standaccessories$59.991st
Cable Kitaccessories$19.992nd
Keyboardelectronics$149.993rd
Mouseelectronics$49.994th
The first field decides, the next only breaks ties. sort=-rating,price,-created_at means best rated, then cheapest, then newest. Add the id at the end so that the order is always the same.

Safety

From the URL to the database

One request

Values become parameters. Names come from our own list, because SQL cannot bind a column name.

Do

  • Choose one syntax
  • Document every operator
  • Check and convert all inputs
  • Set defaults, such as limit 20
  • Limit the number of conditions
  • Build indexes for the common questions

Do not

  • Mix syntaxes
  • Put input into SQL or NoSQL text
  • Expose internal field names
  • Allow unlimited results
  • Ignore what a question costs
  • Skip validation

May this parameter pass?

Refuse unknown parameters instead of ignoring them. A typo such as prise_lt would otherwise return everything.

Speed

Indexes for filters

A composite index works from left to right. Put the equality columns first, then the column you sort or range by, then the id. An index on (category, price, id) serves category=electronics&price_lt=100&sort=price in one walk.

How much is left

100,000×15×14=5,000 rows100{,}000 \times \tfrac{1}{5} \times \tfrac{1}{4} = 5{,}000 \text{ rows}
Assume one product in five is in the category and one in four of those is cheap enough. With the index the database walks only those 5,000, and with sort=price it stops after the first 20.

When filters multiply

  1. 1

    Cover the common ones

    Read the query log. A few combinations are most of the traffic.

  2. 2

    Let the database combine

    Several single-column indexes can be joined for rarer combinations.

  3. 3

    Move wide search away

    Twenty optional filters, counts per value and free text belong in a search engine.

  4. 4

    Refuse the rest

    Require a selective filter, or limit the date range.

Words

Full-text search

Full-text: ?q=wireless+noise+cancelling

  • Words as people type them
  • Ranked by relevance
  • Ignores case and word forms
  • Searches several fields

Pattern filter: ?name_like=wireless

  • Exact characters
  • No ranking
  • Case handling depends on operator and collation
  • Usually one field; % at the start needs a trigram index

How it works

  1. 1

    Tokenize

    Wireless Noise-Cancelling Headphones becomes wireless, noise, cancelling, headphones.

  2. 2

    Normalise

    Lower case, then stems: running becomes run, headphones becomes headphone. Lemmatization does it with a dictionary.

  3. 3

    Look up

    The inverted index gives the documents of each token.

  4. 4

    Score

    TF-IDF, BM25 or a learned model orders the matches.

An inverted index

WordDocuments
wireless1, 10
mouse1
desk6, 11
pro1, 8
From the names and tags of the twelve products in the visualizer. wireless AND mouse is the overlap: document 1.

Rare words weigh more

idf=ln⁡(1+N−n+0.5n+0.5)N=12:;n=1→2.16,n=2→1.65,n=9→0.31idf = \ln\left(1 + \frac{N - n + 0.5}{n + 0.5}\right) \qquad N=12:; n=1 \to 2.16,\quad n=2 \to 1.65,\quad n=9 \to 0.31
The part of BM25 that weighs a word. N documents, n of them with the word. A word in nine of twelve documents says little.

Extras people expect

FeatureExampleEffect
Typo toleranceq=wireles~Still finds wireless
Phraseq="noise cancelling"The words together, in order
One fieldq=title:headphonesOnly the title
Highlightingq=wireless&highlight=trueMarks the matched words
Facetsfacets=categoryHow many hits per category

Where

Database or search engine?

Filters from the database, words from the search engine

A client asks the products API. Filters without text go to PostgreSQL. Questions with words go to Elasticsearch, which returns ids. Changes flow from PostgreSQL through Kafka and an indexer into Elasticsearch, a moment later.
Blue is the question. Orange dashes are changes on their way into the index, which lags a little.
OptionGood atMind
PostgreSQL full textBuilt in: tsvector and tsquery, no extra system, same transactionRanking and typo handling are basic; good for a medium size
Elasticsearch or OpenSearchLarge amounts, rich query language, facetsA cluster to run; near real time, not instant; must be fed
Algolia, TypesenseTypo tolerance and fast suggestions with little setupAlgolia is a hosted service; Typesense is open source with a hosted option. Cost grows with use

Which one?

Start with the database. Move when relevance or facets, not fashion, require it.

A change reaches the index

Sending both writes from the API instead can leave them different for ever when one fails.

Limits

What may a question cost?

A public search endpoint is the easiest way to load your database. Set limits before somebody finds them for you.

LimitExampleWhy
Page size20, at most 100Bounds the answer
ConditionsAt most 10, lists of at most 50 valuesBounds the plan
Query length200 charactersBounds the parsing
Time2 seconds, then 503Protects everyone else
RateLower than for single readsSearches cost more. See rate limiting
Depth10,000 results, then use a cursor or narrowDeep pages are expensive
Example values. Publish yours, and answer a broken limit with a clear error.

Summary

The whole topic in one minute.

Offer filters, sorting and search as one documented syntax over an allowlist of fields. Turn values into bound parameters, never into SQL text, and end every sort with a unique column.

Filters live in the database with indexes that fit. Words need an inverted index, in the database or in a search engine that is fed by changes and lags a little. Limit how much one question may cost.

  • Filter, sort and search on the server; send one page.
  • One syntax, an allowlist, typed values, bound parameters.
  • End the sort with a unique column; decide where nulls go.
  • Index equality columns first, then range or sort.
  • Words need an inverted index; a search engine lags behind the database.
  • Publish limits for size, conditions, time and depth.

Sources