org.apache.lucene.search

## Class IndexSearcher

- java.lang.Object
- - org.apache.lucene.search.IndexSearcher

    public class IndexSearcher
    extends Object

Implements search over a single IndexReader.

Applications usually need only call the inherited `search(Query,int)` or `search(Query,Filter,int)` methods. For performance reasons, if your index is unchanging, you should share a single IndexSearcher instance across multiple searches instead of creating a new one per-search. If your index has changed and you wish to see the changes reflected in searching, you should use `DirectoryReader.openIfChanged(DirectoryReader)` to obtain a new reader and then create a new IndexSearcher from that. Also, for low-latency turnaround it's best to use a near-real-time reader (`DirectoryReader.open(IndexWriter,boolean)`). Once you have a new `IndexReader`, it's relatively cheap to create a new IndexSearcher from it.

NOTE: ``IndexSearcher`` instances are completely thread safe, meaning multiple threads can call any of its methods, concurrently. If your application requires external synchronization, you should not synchronize on the `IndexSearcher` instance; use your own (non-Lucene) objects instead.

### Nested Class Summary

Nested Classes
`static class` `IndexSearcher.LeafSlice` A class holding a subset of the `IndexSearcher`s leaf contexts to be executed within a single thread.

### Field Summary

Fields
`protected List<AtomicReaderContext>` `leafContexts`
`protected IndexSearcher.LeafSlice[]` `leafSlices` used with executor - each slice holds a set of leafs executed within one thread
`protected IndexReaderContext` `readerContext`

### Constructor Summary

Constructors
Constructor and Description
`IndexSearcher(IndexReader r)` Creates a searcher searching the provided index.
`IndexSearcher(IndexReaderContext context)` Creates a searcher searching the provided top-level `IndexReaderContext`.
`IndexSearcher(IndexReaderContext context, ExecutorService executor)` Creates a searcher searching the provided top-level `IndexReaderContext`.
`IndexSearcher(IndexReader r, ExecutorService executor)` Runs searches for each segment separately, using the provided ExecutorService.

### Method Summary

Methods
`CollectionStatistics` `collectionStatistics(String field)` Returns `CollectionStatistics` for a field.
`Weight` `createNormalizedWeight(Query query)` Creates a normalized weight for a top-level `Query`.
`Document` `doc(int docID)` Sugar for `.getIndexReader().document(docID)`
`Document` `doc(int docID, Set<String> fieldsToLoad)` Sugar for `.getIndexReader().document(docID, fieldsToLoad)`
`void` `doc(int docID, StoredFieldVisitor fieldVisitor)` Sugar for `.getIndexReader().document(docID, fieldVisitor)`
`Document` `document(int docID, Set<String> fieldsToLoad)` Deprecated. Use `doc(int, Set)` instead.
`Explanation` `explain(Query query, int doc)` Returns an Explanation that describes how `doc` scored against `query`.
`protected Explanation` `explain(Weight weight, int doc)` Expert: low-level implementation method Returns an Explanation that describes how `doc` scored against `weight`.
`static Similarity` `getDefaultSimilarity()` Expert: returns a default Similarity instance.
`IndexReader` `getIndexReader()` Return the `IndexReader` this searches.
`Similarity` `getSimilarity()`
`IndexReaderContext` `getTopReaderContext()` Returns this searchers the top-level `IndexReaderContext`.
`Query` `rewrite(Query original)` Expert: called to re-write queries into primitive queries.
`protected void` `search(List<AtomicReaderContext> leaves, Weight weight, Collector collector)` Lower-level search API.
`protected TopFieldDocs` `search(List<AtomicReaderContext> leaves, Weight weight, FieldDoc after, int nDocs, Sort sort, boolean fillFields, boolean doDocScores, boolean doMaxScore)` Just like `search(Weight, int, Sort, boolean, boolean)`, but you choose whether or not the fields in the returned `FieldDoc` instances should be set by specifying fillFields.
`protected TopDocs` `search(List<AtomicReaderContext> leaves, Weight weight, ScoreDoc after, int nDocs)` Expert: Low-level search implementation.
`void` `search(Query query, Collector results)` Lower-level search API.
`void` `search(Query query, Filter filter, Collector results)` Lower-level search API.
`TopDocs` `search(Query query, Filter filter, int n)` Finds the top `n` hits for `query`, applying `filter` if non-null.
`TopFieldDocs` `search(Query query, Filter filter, int n, Sort sort)` Search implementation with arbitrary sorting.
`TopFieldDocs` `search(Query query, Filter filter, int n, Sort sort, boolean doDocScores, boolean doMaxScore)` Search implementation with arbitrary sorting, plus control over whether hit scores and max score should be computed.
`TopDocs` `search(Query query, int n)` Finds the top `n` hits for `query`.
`TopFieldDocs` `search(Query query, int n, Sort sort)` Search implementation with arbitrary sorting and no filter.
`protected TopFieldDocs` `search(Weight weight, FieldDoc after, int nDocs, Sort sort, boolean fillFields, boolean doDocScores, boolean doMaxScore)` Just like `search(Weight, int, Sort, boolean, boolean)`, but you choose whether or not the fields in the returned `FieldDoc` instances should be set by specifying fillFields.
`protected TopFieldDocs` `search(Weight weight, int nDocs, Sort sort, boolean doDocScores, boolean doMaxScore)` Expert: Low-level search implementation with arbitrary sorting and control over whether hit scores and max score should be computed.
`protected TopDocs` `search(Weight weight, ScoreDoc after, int nDocs)` Expert: Low-level search implementation.
`TopDocs` `searchAfter(ScoreDoc after, Query query, Filter filter, int n)` Finds the top `n` hits for `query`, applying `filter` if non-null, where all results are after a previous result (`after`).
`TopDocs` `searchAfter(ScoreDoc after, Query query, Filter filter, int n, Sort sort)` Finds the top `n` hits for `query`, applying `filter` if non-null, where all results are after a previous result (`after`).
`TopDocs` `searchAfter(ScoreDoc after, Query query, Filter filter, int n, Sort sort, boolean doDocScores, boolean doMaxScore)` Finds the top `n` hits for `query` where all results are after a previous result (`after`), allowing control over whether hit scores and max score should be computed.
`TopDocs` `searchAfter(ScoreDoc after, Query query, int n)` Finds the top `n` hits for `query` where all results are after a previous result (`after`).
`TopDocs` `searchAfter(ScoreDoc after, Query query, int n, Sort sort)` Finds the top `n` hits for `query` where all results are after a previous result (`after`).
`void` `setSimilarity(Similarity similarity)` Expert: Set the Similarity implementation used by this IndexSearcher.
`protected IndexSearcher.LeafSlice[]` `slices(List<AtomicReaderContext> leaves)` Expert: Creates an array of leaf slices each holding a subset of the given leaves.
`TermStatistics` `termStatistics(Term term, TermContext context)` Returns `TermStatistics` for a term.
`String` `toString()`
`protected Query` `wrapFilter(Query query, Filter filter)`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

### Field Detail

#### readerContext

    protected final IndexReaderContext readerContext

#### leafContexts

    protected final List<AtomicReaderContext> leafContexts

#### leafSlices

    protected final IndexSearcher.LeafSlice[] leafSlices

used with executor - each slice holds a set of leafs executed within one thread

### Constructor Detail

#### IndexSearcher

    public IndexSearcher(IndexReader r)

Creates a searcher searching the provided index.

#### IndexSearcher

    public IndexSearcher(IndexReader r,
                 ExecutorService executor)

Runs searches for each segment separately, using the provided ExecutorService. IndexSearcher will not shutdown/awaitTermination this ExecutorService on close; you must do so, eventually, on your own. NOTE: if you are using `NIOFSDirectory`, do not use the shutdownNow method of ExecutorService as this uses Thread.interrupt under-the-hood which can silently close file descriptors (see LUCENE-2239).

WARNING: This API is experimental and might change in incompatible ways in the next release.

#### IndexSearcher

    public IndexSearcher(IndexReaderContext context,
                 ExecutorService executor)

Creates a searcher searching the provided top-level `IndexReaderContext`.

Given a non-`null` `ExecutorService` this method runs searches for each segment separately, using the provided ExecutorService. IndexSearcher will not shutdown/awaitTermination this ExecutorService on close; you must do so, eventually, on your own. NOTE: if you are using `NIOFSDirectory`, do not use the shutdownNow method of ExecutorService as this uses Thread.interrupt under-the-hood which can silently close file descriptors (see LUCENE-2239).

See Also:
  `IndexReaderContext`, `IndexReader.getContext()`
WARNING: This API is experimental and might change in incompatible ways in the next release.

#### IndexSearcher

    public IndexSearcher(IndexReaderContext context)

Creates a searcher searching the provided top-level `IndexReaderContext`.

See Also:
  `IndexReaderContext`, `IndexReader.getContext()`
WARNING: This API is experimental and might change in incompatible ways in the next release.

### Method Detail

#### getDefaultSimilarity

    public static Similarity getDefaultSimilarity()

Expert: returns a default Similarity instance. In general, this method is only called to initialize searchers and writers. User code and query implementations should respect `getSimilarity()`.

NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.

#### slices

    protected IndexSearcher.LeafSlice[] slices(List<AtomicReaderContext> leaves)

Expert: Creates an array of leaf slices each holding a subset of the given leaves. Each `IndexSearcher.LeafSlice` is executed in a single thread. By default there will be one `IndexSearcher.LeafSlice` per leaf (`AtomicReaderContext`).

#### getIndexReader

    public IndexReader getIndexReader()

Return the `IndexReader` this searches.

#### doc

    public Document doc(int docID)
                 throws IOException

Sugar for `.getIndexReader().document(docID)`

Throws:
  `IOException`
See Also:
  `IndexReader.document(int)`

#### doc

    public void doc(int docID,
           StoredFieldVisitor fieldVisitor)
             throws IOException

Sugar for `.getIndexReader().document(docID, fieldVisitor)`

Throws:
  `IOException`
See Also:
  `IndexReader.document(int, StoredFieldVisitor)`

#### doc

    public Document doc(int docID,
               Set<String> fieldsToLoad)
                 throws IOException

Sugar for `.getIndexReader().document(docID, fieldsToLoad)`

Throws:
  `IOException`
See Also:
  `IndexReader.document(int, Set)`

#### document

    @Deprecated
    public final Document document(int docID,
                               Set<String> fieldsToLoad)
                            throws IOException

Deprecated. Use `doc(int, Set)` instead.

Throws:
  `IOException`

#### setSimilarity

    public void setSimilarity(Similarity similarity)

Expert: Set the Similarity implementation used by this IndexSearcher.

#### getSimilarity

    public Similarity getSimilarity()

#### wrapFilter

    protected Query wrapFilter(Query query,
                   Filter filter)

NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.

#### searchAfter

    public TopDocs searchAfter(ScoreDoc after,
                      Query query,
                      int n)
                        throws IOException

Finds the top `n` hits for `query` where all results are after a previous result (`after`).

By passing the bottom result from a previous page as `after`, this method can be used for efficient 'deep-paging' across potentially large result sets.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### searchAfter

    public TopDocs searchAfter(ScoreDoc after,
                      Query query,
                      Filter filter,
                      int n)
                        throws IOException

Finds the top `n` hits for `query`, applying `filter` if non-null, where all results are after a previous result (`after`).

By passing the bottom result from a previous page as `after`, this method can be used for efficient 'deep-paging' across potentially large result sets.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public TopDocs search(Query query,
                 int n)
                   throws IOException

Finds the top `n` hits for `query`.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public TopDocs search(Query query,
                 Filter filter,
                 int n)
                   throws IOException

Finds the top `n` hits for `query`, applying `filter` if non-null.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public void search(Query query,
              Filter filter,
              Collector results)
                throws IOException

Lower-level search API.

`Collector.collect(int)` is called for every matching document.

Parameters:
  `query` - to match documents
  `filter` - if non-null, used to permit documents to be collected.
  `results` - to receive hits
Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public void search(Query query,
              Collector results)
                throws IOException

Lower-level search API.

`Collector.collect(int)` is called for every matching document.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public TopFieldDocs search(Query query,
                      Filter filter,
                      int n,
                      Sort sort)
                        throws IOException

Search implementation with arbitrary sorting. Finds the top `n` hits for `query`, applying `filter` if non-null, and sorting the hits by the criteria in `sort`.

NOTE: this does not compute scores by default; use `search(Query,Filter,int,Sort,boolean,boolean)` to control scoring.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public TopFieldDocs search(Query query,
                      Filter filter,
                      int n,
                      Sort sort,
                      boolean doDocScores,
                      boolean doMaxScore)
                        throws IOException

Search implementation with arbitrary sorting, plus control over whether hit scores and max score should be computed. Finds the top `n` hits for `query`, applying `filter` if non-null, and sorting the hits by the criteria in `sort`. If `doDocScores` is `true` then the score of each hit will be computed and returned. If `doMaxScore` is `true` then the maximum score over all collected hits will be computed.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### searchAfter

    public TopDocs searchAfter(ScoreDoc after,
                      Query query,
                      Filter filter,
                      int n,
                      Sort sort)
                        throws IOException

Finds the top `n` hits for `query`, applying `filter` if non-null, where all results are after a previous result (`after`).

By passing the bottom result from a previous page as `after`, this method can be used for efficient 'deep-paging' across potentially large result sets.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    public TopFieldDocs search(Query query,
                      int n,
                      Sort sort)
                        throws IOException

Search implementation with arbitrary sorting and no filter.

Parameters:
  `query` - The query to search for
  `n` - Return only the top n results
  `sort` - The `Sort` object
Returns:
  The top docs, sorted according to the supplied `Sort` instance
Throws:
  `IOException` - if there is a low-level I/O error

#### searchAfter

    public TopDocs searchAfter(ScoreDoc after,
                      Query query,
                      int n,
                      Sort sort)
                        throws IOException

Finds the top `n` hits for `query` where all results are after a previous result (`after`).

By passing the bottom result from a previous page as `after`, this method can be used for efficient 'deep-paging' across potentially large result sets.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### searchAfter

    public TopDocs searchAfter(ScoreDoc after,
                      Query query,
                      Filter filter,
                      int n,
                      Sort sort,
                      boolean doDocScores,
                      boolean doMaxScore)
                        throws IOException

Finds the top `n` hits for `query` where all results are after a previous result (`after`), allowing control over whether hit scores and max score should be computed.

By passing the bottom result from a previous page as `after`, this method can be used for efficient 'deep-paging' across potentially large result sets. If `doDocScores` is `true` then the score of each hit will be computed and returned. If `doMaxScore` is `true` then the maximum score over all collected hits will be computed.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    protected TopDocs search(Weight weight,
                 ScoreDoc after,
                 int nDocs)
                      throws IOException

Expert: Low-level search implementation. Finds the top `n` hits for `query`, applying `filter` if non-null.

Applications should usually call `search(Query,int)` or `search(Query,Filter,int)` instead.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    protected TopDocs search(List<AtomicReaderContext> leaves,
                 Weight weight,
                 ScoreDoc after,
                 int nDocs)
                      throws IOException

Expert: Low-level search implementation. Finds the top `n` hits for `query`.

Applications should usually call `search(Query,int)` or `search(Query,Filter,int)` instead.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    protected TopFieldDocs search(Weight weight,
                      int nDocs,
                      Sort sort,
                      boolean doDocScores,
                      boolean doMaxScore)
                           throws IOException

Expert: Low-level search implementation with arbitrary sorting and control over whether hit scores and max score should be computed. Finds the top `n` hits for `query` and sorting the hits by the criteria in `sort`.

Applications should usually call `search(Query,Filter,int,Sort)` instead.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### search

    protected TopFieldDocs search(Weight weight,
                      FieldDoc after,
                      int nDocs,
                      Sort sort,
                      boolean fillFields,
                      boolean doDocScores,
                      boolean doMaxScore)
                           throws IOException

Just like `search(Weight, int, Sort, boolean, boolean)`, but you choose whether or not the fields in the returned `FieldDoc` instances should be set by specifying fillFields.

NOTE: this does not compute scores by default. If you need scores, create a `TopFieldCollector` instance by calling `TopFieldCollector.create(org.apache.lucene.search.Sort, int, boolean, boolean, boolean, boolean)` and then pass that to `search(List, Weight, Collector)`.

Throws:
  `IOException`

#### search

    protected TopFieldDocs search(List<AtomicReaderContext> leaves,
                      Weight weight,
                      FieldDoc after,
                      int nDocs,
                      Sort sort,
                      boolean fillFields,
                      boolean doDocScores,
                      boolean doMaxScore)
                           throws IOException

Just like `search(Weight, int, Sort, boolean, boolean)`, but you choose whether or not the fields in the returned `FieldDoc` instances should be set by specifying fillFields.

Throws:
  `IOException`

#### search

    protected void search(List<AtomicReaderContext> leaves,
              Weight weight,
              Collector collector)
                   throws IOException

Lower-level search API.

`Collector.collect(int)` is called for every document.

NOTE: this method executes the searches on all given leaves exclusively. To search across all the searchers leaves use `leafContexts`.

Parameters:
  `leaves` - the searchers leaves to execute the searches on
  `weight` - to match documents
  `collector` - to receive hits
Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### rewrite

    public Query rewrite(Query original)
                  throws IOException

Expert: called to re-write queries into primitive queries.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### explain

    public Explanation explain(Query query,
                      int doc)
                        throws IOException

Returns an Explanation that describes how `doc` scored against `query`.

This is intended to be used in developing Similarity implementations, and, for good performance, should not be displayed with every hit. Computing an explanation is as expensive as executing the query over the entire index.

Throws:
  `IOException`

#### explain

    protected Explanation explain(Weight weight,
                      int doc)
                           throws IOException

Expert: low-level implementation method Returns an Explanation that describes how `doc` scored against `weight`.

This is intended to be used in developing Similarity implementations, and, for good performance, should not be displayed with every hit. Computing an explanation is as expensive as executing the query over the entire index.

Applications should call `explain(Query, int)`.

Throws:
  `BooleanQuery.TooManyClauses` - If a query would exceed `BooleanQuery.getMaxClauseCount()` clauses.
  `IOException`

#### createNormalizedWeight

    public Weight createNormalizedWeight(Query query)
                                  throws IOException

Creates a normalized weight for a top-level `Query`. The query is rewritten by this method and `Query.createWeight(org.apache.lucene.search.IndexSearcher)` called, afterwards the `Weight` is normalized. The returned `Weight` can then directly be used to get a `Scorer`.

Throws:
  `IOException`
NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.

#### getTopReaderContext

    public IndexReaderContext getTopReaderContext()

Returns this searchers the top-level `IndexReaderContext`.

See Also:
  `IndexReader.getContext()`

#### toString

    public String toString()

Overrides:
  `toString` in class `Object`

#### termStatistics

    public TermStatistics termStatistics(Term term,
                                TermContext context)
                                  throws IOException

Returns `TermStatistics` for a term. This can be overridden for example, to return a term's statistics across a distributed collection.

Throws:
  `IOException`
WARNING: This API is experimental and might change in incompatible ways in the next release.

#### collectionStatistics

    public CollectionStatistics collectionStatistics(String field)
                                              throws IOException

Returns `CollectionStatistics` for a field. This can be overridden for example, to return a field's statistics across a distributed collection.

Throws:
  `IOException`
WARNING: This API is experimental and might change in incompatible ways in the next release.