Quick revision
The short answer
We annotate a Product class with @Document(indexName = "products") and its fields with @Field, using FieldType.Text for words people search in and FieldType.Keyword for exact values such as SKUs and categories, then query through an ElasticsearchRepository or, for full control, ElasticsearchOperations. Search is near real time: a new document becomes visible after the next refresh, about one second by default. Elasticsearch is usually not the primary store because it has no multi-document transactions or relational constraints, so the source of truth stays in a database and the index is built from it, with explicit mappings rather than dynamic ones.
What to remember
In this answer, we mapped a Product with @Document and @Field, choosing Text for searchable words and Keyword for exact values, indexed it through ElasticsearchRepository, and built a scored search with filters through ElasticsearchOperations. We saw that search is near real time, with documents visible after a refresh of about one second, and that Elasticsearch lacks multi-document transactions and relational constraints, so it serves as a rebuildable search view while the database stays the source of truth. We also defined mappings explicitly instead of relying on dynamic mapping.
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.
We annotate a Product class with @Document(indexName = "products") and its fields with @Field, using FieldType.Text for words people search in and FieldType.Keyword for exact values such as SKUs and categories, then query through an ElasticsearchRepository or, for full control, ElasticsearchOperations. Search is near real time: a new document becomes visible after the next refresh, about one second by default. Elasticsearch is usually not the primary store because it has no multi-document transactions or relational constraints, so the source of truth stays in a database and the index is built from it, with explicit mappings rather than dynamic ones.
Why this question is asked
Product search is the textbook reason to add Elasticsearch to a Spring service: users type "red desk lamp" and expect relevant results in milliseconds, with typos forgiven and filters applied. A SQL LIKE query cannot do that well. Interviewers ask this question to check two things: that we can map and query documents with Spring Data Elasticsearch, and that we understand what Elasticsearch does not give us, which decides how it fits into the architecture. In this answer, we will recap how a search engine stores text, map the Product class, index and query it, look at near real time search, and explain why the database stays the source of truth.
1A Quick Recap: How Elasticsearch Finds Text
Elasticsearch is a search engine built on Apache Lucene. Data is stored as JSON documents in an index, roughly like rows in a table. For every text field, Elasticsearch builds an inverted index, a map from each word to the list of documents containing it, much like the index at the back of a book. Before words go into it, an analyzer processes the text: it splits it into tokens, lowercases them, and can remove common words or reduce words to their stem, so that "Lamps" and "lamp" match.
That is why the field type matters so much. A text field is analyzed and is good for full-text search with relevance scoring. A keyword field is stored as one exact value, which is what we need for filters, sorting and aggregations such as counting products per brand.
| Field and type | Stored terms for "Desk Lamp LED" | Good for |
|---|---|---|
| name, Text | desk, lamp, led | full-text search, relevance |
| brand, Keyword | "Desk Lamp LED" as one term | exact filter, sort, aggregation |
2Mapping the Product Class
With Spring Data Elasticsearch, the mapping lives on the entity class.
Notice that we reuse the database id as the document id. That makes indexing idempotent: writing the same product twice replaces the document instead of creating a duplicate. The english analyzer stems words, so a search for lamps finds lamp. The sku and category are keywords, because nobody wants a SKU split into tokens. When a repository for this class starts, Spring Data Elasticsearch by default creates the index with these mappings if it does not exist; check the createIndex attribute of @Document for your version and decide whether index creation should rather be part of deployment.
3Indexing and Querying
A repository gives us save, delete and derived queries, just like other Spring Data modules. For searches with scoring, filters and boosts, ElasticsearchOperations with a native query is clearer.
The must clause scores documents by how well they match the words, with name counting three times as much as description through the ^3 boost. The filter clause only includes or excludes documents and does not affect the score, which also lets Elasticsearch cache it. This split between scoring and filtering is the core of most product searches.
4Near Real Time: Why a Saved Product Is Not Found Immediately
When we index a document, Elasticsearch writes it to an in-memory buffer and a transaction log, but searches only see segments that have been refreshed, meaning written into a new searchable Lucene segment. By default, a refresh happens every second (index.refresh_interval), although an index that has not been searched for a while may delay refreshes until the next search. So a search immediately after save may not find the product. This is called near real time.
Tests often stumble over this. We can refresh explicitly with operations.indexOps(Product.class).refresh() in tests, or index with refresh policy wait_for when a request really must see its own write, but forcing refreshes in production on every write costs a lot of indexing throughput.
5Why Elasticsearch Is Usually Not the Primary Store
Elasticsearch offers per-document versioning and optimistic concurrency, but no transactions across documents, no foreign keys, no unique constraints beyond the document id, and no joins in the relational sense. A product with stock, prices per market and orders referencing it needs exactly those guarantees. Elasticsearch also expects that some changes, such as a new analyzer or a changed field type, require reindexing all data into a new index, which is only easy if the data can be read again from somewhere else.
So the usual architecture keeps the source of truth in a database such as PostgreSQL and treats the index as a derived, rebuildable view built for search. Writes go to the database, a change is published, and an indexer updates Elasticsearch. If the index is lost or must change, we rebuild it from the database.
6Define Mappings Explicitly
If we index a document without a mapping, Elasticsearch guesses one, which is called dynamic mapping. A string becomes a text field with a keyword sub-field, a number that first arrives as 10 becomes a long so 10.5 later fails or is truncated depending on settings, and a date string in an unusual format becomes text. Once a field's type is set, it cannot be changed in place. So we define mappings explicitly through annotations or a mapping file, and we can set dynamic to strict on the index so unknown fields are rejected rather than silently mapped.
7Follow-up questions
What is the difference between a match query and a term query?
A match query runs the search text through the field's analyzer and looks for the resulting tokens, which is right for text fields. A term query looks for the exact value without analysis, which is right for keyword fields. A term query for Lamp on an analyzed text field finds nothing, because the stored token is lamp.
Should the Spring repository create the index automatically?
It is convenient in development. In production, many teams prefer to create indexes and aliases as part of a deployment step, so mapping changes are deliberate and reindexing can be planned instead of happening implicitly at startup.
How do we keep the index in sync with the database?
Through an outbox table or change data capture feeding an indexer that writes idempotently, rather than writing to both stores from the request. That way a failed index write is retried instead of leaving the two stores permanently different.
8Conclusion
In this answer, we mapped a Product with @Document and @Field, choosing Text for searchable words and Keyword for exact values, indexed it through ElasticsearchRepository, and built a scored search with filters through ElasticsearchOperations. We saw that search is near real time, with documents visible after a refresh of about one second, and that Elasticsearch lacks multi-document transactions and relational constraints, so it serves as a rebuildable search view while the database stays the source of truth. We also defined mappings explicitly instead of relying on dynamic mapping.
Open with
I would annotate a Product class with @Document and the index name products, reuse the database id as the document id so reindexing is idempotent, and map each field explicitly with @Field.
Then, if they want more
Words people search in, like name and description, are FieldType.Text with an analyzer such as english, so lamps matches lamp. Exact values like SKU, category or brand are Keyword, which is what filters, sorting and aggregations need.
For simple cases I use an ElasticsearchRepository with derived methods, and for real product search I use ElasticsearchOperations with a native bool query: a multi-match in must for scoring, with a boost on name, and term filters for category or price that don't affect the score. Two things to know.
Search is near real time: a document is visible only after a refresh, every second by default, so a search right after save can miss it, and tests need an explicit refresh. And Elasticsearch is usually not the primary store.
It has no multi-document transactions, foreign keys or unique constraints, and mapping changes often require a full reindex, which only works if the data lives somewhere else. So PostgreSQL stays the source of truth and the index is a derived view, kept in sync through an outbox or change data capture.
And I define mappings explicitly, even set dynamic to strict, because dynamic mapping guesses types that can't be changed later.
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 reference
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 "How do you use Spring Data Elasticsearch to index and search products, and why is...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/1a192da813/