Apache Lucene Reference
|
This section documents the current Apache Lucene 10.x line — Lucene 10 requires Java 21 — as published
at the Apache Lucene documentation and Javadoc, which is the reference these
pages are written and verified against. No specific patch version is pinned; examples target This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production, as Lucene iterates quickly. This section’s bibliography lists the reference material consulted while preparing these pages. |
Welcome to the Apache Lucene reference. Apache Lucene is an embedded,
in-process Java search library — not a server: you add lucene-core to a JVM application, build an index on a
local Directory of immutable segments, and open a searcher over it in the same process. Elasticsearch,
OpenSearch and Apache Solr are all servers wrapped around this same library; everything they do for text
analysis, the inverted index, query evaluation and scoring is Lucene underneath. This section documents the
current Lucene 10.x line as a Java-developer reference — the index model and storage, the indexing chain, text
analysis, the Query API and parsers, points / BKD range search, BM25 and custom scoring, collectors and
concurrent search, kNN vector search, faceting, highlighting, suggesters, grouping and joins, near-real-time
search and performance tuning — written and verified against
the Apache Lucene documentation and Javadoc.
If you are new to Lucene, read Getting Started first, then Architecture & Data Flow and Documents & Fields, followed by Query Parsers and Core Queries. Everything after that builds on those foundations.
For the search servers built on Lucene and how they compare, see the sibling Elasticsearch Reference and Apache Solr Reference, and this section’s own Lucene vs. Solr vs. Elasticsearch vs. OpenSearch. For the relational and document-database baselines this section contrasts with, see the sibling SQL Reference, MongoDB Reference and Couchbase Reference, which the Lucene pages cross-link rather than restate. For where a dedicated search library or engine fits alongside a primary store, see Choosing the Right Database.
What’s covered
Getting started
-
Getting Started — what Lucene is as an embedded in-process Java search library, adding
lucene-coreand the companion modules to a Maven or Gradle build, and a first end-to-end index-and-search round-trip. -
Architecture & Data Flow — the index model (a
Directoryof immutable segments, generations and commits, the pluggable codec) and the indexing and search class chains that write to and read from it.
Storing & indexing
-
Directories & Storage — the
Directoryabstraction and its implementations (MMapDirectory,NIOFSDirectory,ByteBuffersDirectory),write.lockandLockFactory,IndexInputprefetch andReadAdvice, and why Lucene storage leans on the OS page cache rather than the JVM heap. -
Documents & Fields — the
Documentas a schema-free ordered list ofFieldobjects, the modern field types and what each one enables,FieldTypeandIndexOptions, and a capability matrix for picking searchable vs. stored vs. sortable vs. range vs. vector. -
Indexing & Merge Policies — how
IndexWriteradds, updates, soft-deletes and commits documents, theIndexWriterConfigknobs that shape a segment, and why and how Lucene merges segments (TieredMergePolicyand the other policies, plus the merge schedulers). -
Near-Real-Time Search — making uncommitted
IndexWriterchanges searchable withDirectoryReader.open(writer)andopenIfChanged, managing readers withSearcherManagerandControlledRealTimeReopenThread, stable paging withSearcherLifetimeManager, and the reference-counting rules that keep it safe.
Text analysis
-
Analysis Pipeline — how an
Analyzerturns text into terms: theCharFilter/Tokenizer/TokenFilterchain, theTokenStreamlifecycle and stream reuse, and the attribute API that carries term text, positions and offsets. -
Built-in Analyzers & CustomAnalyzer — the ready-made analyzers in
lucene-analysis-common(StandardAnalyzer,EnglishAnalyzerand the language set),PerFieldAnalyzerWrapper, and building an analyzer from factory names withCustomAnalyzer.builder(). -
Token Filters & Recipes — practical token-filter chains for folding, stop words, synonym graphs, stemming, autocomplete n-grams, shingles, word-delimiter splitting and payloads.
-
Language Analysis — the optional analysis modules for non-Latin scripts and language-specific matching (ICU, Kuromoji, Nori, SmartCN, Stempel, Morfologik, phonetic and OpenNLP).
Querying & scoring
-
Query Parsers — the classic
QueryParsersyntax and its pitfalls,SimpleQueryParser, the flexibleStandardQueryParserframework,ComplexPhraseQueryParser, and when to skip parsing entirely. -
Core Queries — the
org.apache.lucene.searchQueryhierarchy (term, boolean, phrase, multi-term, range, wrapper and set queries), with construction examples and notes onQueryVisitorand rewriting. -
Points & Range Queries — how Lucene indexes numeric and multi-dimensional values as points in a BKD tree, and the
IntPoint/LongPoint/DoublePointqueries,IndexOrDocValuesQuery, doc-values skip lists, and theIntField/LongFieldconvenience types. -
Interval & Span Queries — positional and proximity matching with the modern
Intervals/IntervalQueryAPI (ordered, unordered, maxgaps, containing, containedBy, before, after) and the legacySpanQueryfamily it supersedes. -
Filtering & Faceting — filtering with
BooleanClause.Occur.FILTER,ConstantScoreQueryandTermInSetQuerycached by the searcher’sLRUQueryCache, and thelucene-facetmodule (FacetsConfig, taxonomy vs.SortedSetDocValuescounting, range and value facets, drill-down / drill-sideways). -
Scoring & Similarity —
BM25Similarityas the default ranking model (itsk1andbparameters, field-length norms andSmallFloatquantisation), the alternativeSimilarityimplementations,PerFieldSimilarityWrapper, and theExplanationAPI. -
Function & Custom Scoring — reshaping relevance with
FunctionScoreQueryandDoubleValuesSource,FeatureFieldrelevance signals, thelucene-expressionsmodule, and sorting by field, by script and by score. -
Collectors & Concurrent Search — how Lucene gathers hits: the
CollectorManagermodel that replaces bareCollector, running one query across anExecutor, the total-hits threshold andTotalHits.Relation, early termination, and writing a customCollectorManager. -
Retrieving Results — turning search hits into data: the
StoredFieldsAPI and selective loading withStoredFieldVisitor, reading doc values and term vectors, and paging withsearchAfteragainst a stable searcher.
Vectors & specialized search
-
kNN Vector Search — dense-vector retrieval with
KnnFloatVectorFieldandKnnByteVectorField, the HNSW graph and its quantised codec formats,KnnFloatVectorQuerywith pre-filtering, exact kNN and hybrid lexical + vector search, and the Panama Vector API acceleration. -
Spatial Search —
LatLonPointandLatLonShapeinlucene-core, the prefix-tree and serialized strategies inlucene-spatial-extras, geo3d geometry on the ellipsoid inlucene-spatial3d, and WKT / GeoJSON parsing. -
Highlighting, Suggesters & More — the
lucene-highlighterUnifiedHighlighterand its offset-source requirement, thelucene-suggestLookupand NRT completion APIs, spell checking,MoreLikeThisfromlucene-queries, and thelucene-classificationmodule. -
Grouping & Joins — result grouping with the
lucene-groupingmodule (GroupingSearch, first-pass / second-pass collectors, block grouping) and relating documents with thelucene-joinmodule (query-timeJoinUtiljoins and index-time block joins). -
Monitor / Reverse Search — reverse search with
lucene-monitor: registeringMonitorQueryobjects in aMonitorand matching incoming documents against all of them, with aPresearcherto scale to large query sets andCandidateMatchervariants for the match detail you need.
Operations & tooling
-
Performance Tuning — tuning for indexing throughput (RAM buffer sizing, one shared
IndexWriter, deferred merges,forceMergefor a static index, parallel build withaddIndexes) and for search latency (a reusedIndexSearcherviaSearcherManager, reader warming, the page-cache / heap split forMMapDirectory, theLRUQueryCache, DocValues sorting, capped hit counting), plus how to measure with the nightly benchmarks. -
Testing, Tools & Modules — the
lucene-test-framework(LuceneTestCase,BaseTokenStreamTestCase,newDirectory,RandomIndexWriter, randomized and Nightly testing),CheckIndexfor corruption,IndexUpgraderwithlucene-backward-codecs, the Luke index browser, and the benchmark, replicator and misc tool modules — plus a one-line map of every Lucene module. -
Lucene vs. Solr vs. Elasticsearch vs. OpenSearch — how the embedded Lucene library compares with the three search servers built on it on deployment model, clustering, API style, licensing and operational weight, with a decision list for choosing one.
Cheat sheet
-
Cheat Sheet (PDF) — a single-page, printable summary of everything in this section, with a downloadable PDF.
Bibliography
-
the Apache Lucene site and its per-release Javadoc — the source every page in this section is written and verified against. See in particular the Javadoc package overviews (
core/index,core/document,core/analysis,core/search,core/store,codecs) and the module pages (analysis-common,analysis-icu/-kuromoji/-nori/-smartcn/-stempel/-morfologik/-phonetic/-opennlp,queryparser,queries,facet,highlighter,suggest,join,grouping,expressions,classification,monitor,spatial-extras,spatial3d,replicator,luke,benchmark,misc,test-framework,backward-codecs,demo), plusChanges.html,MIGRATE.mdand the system-requirements page. Current release: Lucene 10.x; Lucene 10 requires Java 21. -
McCandless, Michael; Hatcher, Erik; Gospodnetić, Otis. Lucene in Action, Second Edition. Manning Publications, 2010. ISBN 9781933988177. Consulted as part of the bibliography for this section; its code targets Lucene 3.0.x and predates the Lucene 4 field-type / codec /
DocValuesrewrite, points / BKD (6.x), BM25 as the default similarity (6.x), theFilterremoval,CustomAnalyzer, theIntervalsAPI,UnifiedHighlighter,FunctionScoreQuery,CollectorManager/ concurrent search, soft deletes, theMonitormodule, kNN / HNSW vector search (9.x) and the Java-21 / PanamaMMapDirectory(10.x). Where it and the official documentation disagree, the official documentation is authoritative and the difference is noted; none of its content is the primary or main reference for this section. Publisher page: manning.com/books/lucene-in-action-second-edition. -
The book above is a consulted bibliographic reference only. It is not the primary or main reference for this section, and where it and the official Apache Lucene documentation disagree, the official documentation is authoritative and the difference is noted.