Quick revision
The short answer
To index, we open a Directory with FSDirectory.open, create an IndexWriter with an IndexWriterConfig and an Analyzer such as StandardAnalyzer, add Document objects with a TextField for the title and a StringField for the id, and call commit(). To search, we open a DirectoryReader, wrap it in an IndexSearcher, run a Query from QueryParser or a TermQuery, and read the TopDocs and their ScoreDoc entries, loading stored fields through searcher.storedFields(); a long-running service uses SearcherManager to refresh. We embed Lucene for single-node, low-operations needs and choose Elasticsearch or OpenSearch when we need distribution, replication and an HTTP API.
What to remember
In this answer, we used Lucene directly: FSDirectory for storage, IndexWriter with IndexWriterConfig and StandardAnalyzer for indexing, TextField for searchable titles and StringField for exact ids, and commit() to make changes durable. On the read side, DirectoryReader, IndexSearcher and a Query from QueryParser or TermQuery return TopDocs of ScoreDoc entries, with stored fields loaded through storedFields(), and SearcherManager keeps a long-running service fresh. Embedded Lucene suits single-node, low-operations needs, while Elasticsearch or OpenSearch is the choice for distribution, replication and APIs.
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.
To index, we open a Directory with FSDirectory.open, create an IndexWriter with an IndexWriterConfig and an Analyzer such as StandardAnalyzer, add Document objects with a TextField for the title and a StringField for the id, and call commit(). To search, we open a DirectoryReader, wrap it in an IndexSearcher, run a Query from QueryParser or a TermQuery, and read the TopDocs and their ScoreDoc entries, loading stored fields through searcher.storedFields(); a long-running service uses SearcherManager to refresh. We embed Lucene for single-node, low-operations needs and choose Elasticsearch or OpenSearch when we need distribution, replication and an HTTP API.
Why this question is asked
Most Java developers meet Lucene only through Elasticsearch or OpenSearch, but Lucene is an ordinary Java library we can use directly. Knowing its API helps us understand what the server engines do for us, and sometimes it is the right tool by itself: a desktop application, a command-line tool, or a small service with a few million documents. Interviewers ask this to see whether we know the core classes and their roles. In this answer, we will set up the project, write the indexing code, write the search code, keep a long-running service fresh with SearcherManager, and finish with when embedding Lucene makes sense.
1A Quick Recap of the Pieces
A Lucene index lives in a Directory, an abstraction over where the files are stored; FSDirectory stores them in a folder on disk. Text is turned into searchable terms by an Analyzer. StandardAnalyzer splits text into words and lowercases them, so 'Lucene in Practice' becomes the terms lucene, in and practice. A Document is a set of fields. A TextField is analysed, which is right for a title we want to search by words. A StringField is indexed as one exact term without analysis, which is right for ids, codes and tags.
IndexWriter writes; a DirectoryReader, a point-in-time view, and an IndexSearcher read. The examples below use Lucene 10, which needs Java 21 or later; Lucene 9 is very similar, with differences noted where they matter. The core classes are in lucene-core, StandardAnalyzer is in lucene-analysis-common, and QueryParser is in lucene-queryparser.
2Indexing Documents
We open the directory, create the writer and add two books. Field.Store.YES tells Lucene to keep the original value as a stored field so we can show it in results; the index alone only holds terms.
Notice that updateDocument takes a Term on the id field. That is why the id must be a StringField: an analysed id could be split into several terms and the update would not find the right document. commit() writes the segments and a commit point to disk, so a reader opened afterwards sees the documents and a crash after this line loses nothing. Commits are expensive, so a real indexer commits every few seconds or every few thousand documents, not after each one.
3Searching for a Term
Now we open a reader on the same directory and search the title field. QueryParser turns a query string into a Query using the same analyzer we used for indexing, which matters: if indexing lowercased 'Lucene' to lucene, the query must be lowercased too.
- IndexWriter + IndexWriterConfig
addDocument,updateDocument, commit - Analyzer (StandardAnalyzer)turns title text into terms
- Directory (FSDirectory)segment files on disk
- DirectoryReaderpoint-in-time view of the segments
- IndexSearcher + Queryreturns
TopDocsofScoreDocentries
5 layers, from the top down. Step through them one at a time.
The analyzer is shared: the same rules must apply when indexing and when parsing queries.
TopDocs holds the total hit count and an array of ScoreDoc entries, each with an internal doc id and a score, sorted by score. The doc id is only meaningful inside this reader. To get the stored values we call searcher.storedFields().document(id); this StoredFields API arrived in Lucene 9.5 and replaced the older searcher.doc(id), which was removed in Lucene 10. A TermQuery skips analysis completely, so it is the right choice for exact fields such as the id, while QueryParser is convenient for user input.
4Keeping a Long-Running Service Fresh
A DirectoryReader is a snapshot. In a service that keeps indexing, a reader opened at startup never sees new documents. Opening a new reader for every request is far too slow. SearcherManager solves this: it holds the current IndexSearcher, hands it out to requests, and on maybeRefresh() opens a new one only if the index has changed, reusing unchanged segments. Because it can be built on the IndexWriter itself, it can also see documents that are not yet committed, which is called near-real-time search.
The acquire and release pair is a reference count: an old searcher is closed only when the last request using it has released it. Forgetting release() leaks old readers and keeps deleted segment files on disk. This one-second refresh loop is essentially what Elasticsearch's refresh_interval does for us.
5When to Embed Lucene and When Not To
Embedding Lucene makes sense when the data fits on one machine and we want no extra servers. A desktop application with local search, a command-line tool that indexes log files, a small service with a few million documents and modest traffic, or a component that needs custom scoring or analysis at a low level are all good fits. We get excellent speed, no network hop, and nothing to operate beyond a folder of files.
Elasticsearch and OpenSearch add what Lucene deliberately leaves out: sharding across nodes, replication and failover, a REST API usable from any language, a translog for durability between commits, aggregations at scale, cluster management, security and snapshots. Once we need more than one node, high availability, or access from several services, building those ourselves around Lucene costs far more than running a search server.
6Follow-up questions
What is the difference between TextField and StringField?
A TextField runs its value through the analyzer, so 'Lucene in Practice' becomes several lowercased terms and can be found by any of the words. A StringField indexes the whole value as one term exactly as given, so it only matches the full exact value. We use TextField for prose and StringField for ids, codes and keywords.
How do we sort or aggregate on a field?
We add a doc values field next to the indexed one, for example a NumericDocValuesField for a price or a SortedDocValuesField for a keyword, and then pass a Sort to IndexSearcher.search. Doc values are Lucene's column-oriented storage for exactly this purpose; the inverted index is not suited to it.
7Conclusion
In this answer, we used Lucene directly: FSDirectory for storage, IndexWriter with IndexWriterConfig and StandardAnalyzer for indexing, TextField for searchable titles and StringField for exact ids, and commit() to make changes durable. On the read side, DirectoryReader, IndexSearcher and a Query from QueryParser or TermQuery return TopDocs of ScoreDoc entries, with stored fields loaded through storedFields(), and SearcherManager keeps a long-running service fresh. Embedded Lucene suits single-node, low-operations needs, while Elasticsearch or OpenSearch is the choice for distribution, replication and APIs.
Open with
With the Lucene API, I open a Directory with FSDirectory.open on a folder, then create an IndexWriter with an IndexWriterConfig that holds the analyzer, typically StandardAnalyzer. For each record I build a Document with a StringField for the id, so it is indexed as one exact term, and a TextField for the title, so it is analysed into words, both with Field.Store.YES if I want to display them.
Then, if they want more
I call addDocument, or updateDocument with a Term on the id to replace a document, and commit to make the changes durable and visible to new readers.
To search, I open a DirectoryReader, wrap it in an IndexSearcher, and build a Query, either with QueryParser using the same analyzer for user input, or with a TermQuery for exact fields like the id. search returns TopDocs with ScoreDoc entries holding the internal doc id and score, and I load the stored fields through searcher.storedFields().document(id).
In a long-running service I would not reopen readers manually; I use SearcherManager built on the writer, call maybeRefresh every second or so, and acquire and release searchers per request. I would embed Lucene when the data fits on one node and I want no extra infrastructure, like a desktop app, a CLI tool or a small service.
When I need sharding, replication, failover, an HTTP API or aggregations across machines, I would use Elasticsearch or OpenSearch instead.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- 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
- Elasticsearch documentation
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 "Using the Lucene Java API directly, outline the code to index documents with a title and...": https://scrivio-interview-library.netlify.app/databases/search-engines/a6a9514654/