Quick revision
The short answer
I would not build it on the Criteria API alone. Criteria can express 25 optional filters, but over several joined tables it tends to produce duplicates, plans that are poor for most filter combinations and code that is hard to maintain, and the real limit is indexing: no set of indexes serves thousands of users combining 25 filters freely. For free-form, many-filter search I would feed a search engine such as Elasticsearch or OpenSearch from the database; if we must stay in SQL, I would query a read model or materialized view shaped for search, and in both cases measure the plans of the most common filter combinations before deciding.
What to remember
In this answer, we decided how to build a 25-filter search over joined tables for thousands of users. The Criteria API can express it, but the direct approach produces duplicates, poor plans for many combinations and hard code, and the real constraint is that no set of relational indexes serves every combination. For free-form, many-filter search we would feed a search engine from the database; to stay in SQL, we would query a read model or materialized view shaped for search; and we would base the choice on measured plans for the most common filter combinations.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would not build it on the Criteria API alone. Criteria can express 25 optional filters, but over several joined tables it tends to produce duplicates, plans that are poor for most filter combinations and code that is hard to maintain, and the real limit is indexing: no set of indexes serves thousands of users combining 25 filters freely. For free-form, many-filter search I would feed a search engine such as Elasticsearch or OpenSearch from the database; if we must stay in SQL, I would query a read model or materialized view shaped for search, and in both cases measure the plans of the most common filter combinations before deciding.
Why this question is asked
Advanced search screens look like a query-building problem, so teams reach for a query builder. But at 25 filters over several tables and thousands of users, the hard part is not writing the query; it is making every combination fast and correct. Interviewers ask this design question to see whether we look past the API to indexes, data shape and usage patterns. In this answer, we will see what goes wrong with a straightforward Criteria implementation, why indexing is the real constraint, how a search engine changes the picture, what a SQL read model looks like if we stay relational, and how measurement of real filter combinations drives the decision.
1What Goes Wrong With the Direct Approach
The direct approach builds one Criteria query: the root entity, joins to each related table a filter needs, and a predicate per filled-in filter. It works on the first demo. Then three problems appear.
Duplicates come first. Filtering on a to-many association, such as orders with a line for a given product, joins the collection, so an order with three matching lines appears three times. We add distinct, which makes the database sort or hash the whole result, and the count query for paging becomes expensive too. Exists subqueries fix correctness but make the generated SQL more complex.
Then the plans. The database plans each combination of filters as a different query. Some combinations hit a good index, many do not, and with optional joins the planner may join large tables before it filters them. Users notice that searching by customer is fast and searching by date range and status is slow. Finally, the code: 25 filters, each with join handling and edge cases, become hard to maintain, as we saw in many Criteria codebases.
2Why Index Design Matters More Than the Query Builder
Whatever builds the SQL, the database can only be fast when an index supports the filters used. A B-tree index on (status, created_at) serves filters on status, or status and date, but not date alone efficiently, and not region and price. With 25 optional filters there are millions of possible combinations, and we cannot create an index for each; every index also slows down writes and uses storage.
Relational databases have partial answers. PostgreSQL can combine several single-column indexes with bitmap scans, GIN indexes handle arrays and JSON attributes, and trigram indexes help with substring text search. These work well for a few filters with selective values. They struggle with many low-selectivity filters combined, free text with ranking, and facet counts, which is exactly what an advanced search screen tends to need.
| Filter shape | Relational support | Search engine support |
|---|---|---|
| Exact match on 1-3 known columns | composite B-tree, very good | good |
| Many optional filters, any combination | bitmap scans, degrades with count | inverted indexes, designed for it |
| Free text with typos and ranking | trigram or full-text, limited ranking | native, with relevance scoring |
| Facet counts per filter value | a group by per facet, expensive | aggregations, built in |
| Strong consistency with writes | yes | near real time, seconds behind |
3Option 1: A Search Engine Fed From the Database
For free-form search with many filters, a search engine such as Elasticsearch or OpenSearch fits better. It stores a denormalised document per searchable item, for example an order with its customer name, country, status, totals and product ids all in one document, so no joins are needed at query time. Its inverted indexes make any combination of filters cheap, and it provides relevance ranking, typo tolerance and facet aggregations natively.
The database stays the source of truth. Changes flow into the index through events from the service or through change data capture, and the index is rebuilt from the database when its mapping changes. The cost is a second system to run and monitor, and eventual consistency: a new order appears in search a second or two after it is saved. For most search screens that is acceptable; for a screen that must show a record immediately after saving it, the application can read that record from the database directly.
6 messages in order. Play them, or step through them one at a time.
The database remains the source of truth; the index is a read model a second or two behind.
4Option 2: A Read Model in SQL
If adding a search engine is not possible, for example because the team cannot operate one or the data cannot leave the database, we should at least stop querying the normalised tables directly. A read model is a table or materialized view shaped for search: one row per searchable item with the columns users filter on, denormalised from the joined tables, with indexes chosen for the most common filter combinations.
Queries now filter one table without joins or duplicates, so the query code, with Criteria, Specifications or plain SQL, becomes simple. The cost is freshness: a materialized view is only as current as its last refresh, so for frequently changing data we maintain a regular table updated from events instead.
5Measuring the Common Combinations
The decision should rest on evidence about how users actually search. If the screen exists, we log which filters each search uses, without the values, and count combinations over a few weeks. Typically a handful of combinations cover most searches, for example status plus date range in 40 percent and customer name in 25 percent. We then run EXPLAIN (ANALYZE, BUFFERS) for those top combinations on production-sized data, against the normalised tables and against the read model, and check latency at realistic concurrency.
If the top combinations are served well by a few indexes and text search is minor, the SQL read model is enough. If users spread across many combinations, rely on free text or want facets, the search engine pays for itself. Either way, the Criteria API is at most the tool that builds the query, not the design.
- Log filter combinations usedcounts only, no values
- Explain the top combinationsproduction-sized data, realistic load
- Free text, facets or many spread-out combinations?YesSearch engine fed from the databaseNoStay in SQL
- SQL read model or materialized viewindexes for the top combinations
- Re-measure after launchwatch p95 latency per combination
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Could we keep Criteria for the query and still be fast?
Yes, if the query runs against a read model with the right indexes. The Criteria API is not slow itself; the slow part is filtering many joined normalised tables. Against a denormalised table, Criteria or Specifications build simple, fast queries.
How do you handle deep paging on the search screen?
Offset paging gets slower as the offset grows in both databases and search engines. Limit the maximum page, or use keyset paging, which continues from the last seen sort key, such as created_at and id, so every page costs about the same.
What about access control in search results?
Put the fields needed for authorisation, such as tenant id or region, into the index or read model and add them as mandatory filters on every query, built by the server, never taken from the client.
7Conclusion
In this answer, we decided how to build a 25-filter search over joined tables for thousands of users. The Criteria API can express it, but the direct approach produces duplicates, poor plans for many combinations and hard code, and the real constraint is that no set of relational indexes serves every combination. For free-form, many-filter search we would feed a search engine from the database; to stay in SQL, we would query a read model or materialized view shaped for search; and we would base the choice on measured plans for the most common filter combinations.
Open with
I would not decide based on the query builder, because the hard part is not building the SQL, it is making every filter combination fast. The Criteria API can express 25 optional filters, but over several joined tables you get duplicates from to-many joins, so distinct or exists subqueries, poor plans for many combinations, and code that is hard to maintain.
Then, if they want more
The real constraint is indexing: with 25 optional filters there are too many combinations for B-tree indexes, and every extra index slows writes. So first I would measure how people search: log which filters each search uses and explain the top combinations on production-sized data.
If users combine many filters freely, use free text or want facet counts, I would feed Elasticsearch or OpenSearch from the database through an outbox or change data capture, with one denormalised document per item, accepting a second or two of lag and keeping the database as the source of truth.
If the usage is concentrated on a few combinations and we need to stay relational, I would build a read model, a denormalised table or materialized view with indexes for the top combinations, and query that with Specifications or SQL. Either way I would add keyset paging, server-side access filters, and re-measure latency per combination after launch.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your product needs an advanced search screen with 25 optional filters over several...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/439ddd2aa1/