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)method. 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 useDirectoryReader.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)). Once you have a newIndexReader, it's relatively cheap to create a new IndexSearcher from it.NOTE:
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 theIndexSearcherIndexSearcherinstance; use your own (non-Lucene) objects instead.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classIndexSearcher.LeafSliceA class holding a subset of theIndexSearchers leaf contexts to be executed within a single thread.
-
Field Summary
Fields Modifier and Type Field Description protected List<LeafReaderContext>leafContextsprotected IndexReaderContextreaderContext
-
Constructor Summary
Constructors Constructor Description IndexSearcher(IndexReader r)Creates a searcher searching the provided index.IndexSearcher(IndexReaderContext context)Creates a searcher searching the provided top-levelIndexReaderContext.IndexSearcher(IndexReaderContext context, ExecutorService executor)Creates a searcher searching the provided top-levelIndexReaderContext.IndexSearcher(IndexReader r, ExecutorService executor)Runs searches for each segment separately, using the provided ExecutorService.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description CollectionStatisticscollectionStatistics(String field)ReturnsCollectionStatisticsfor a field.intcount(Query query)Count how many documents match the given query.WeightcreateNormalizedWeight(Query query, boolean needsScores)Deprecated.Clients should rewrite the query and then callcreateWeight(Query, boolean, float)with a boost value of 1fWeightcreateWeight(Query query, boolean needsScores, float boost)Creates aWeightfor the given query, potentially adding caching if possible and configured.Documentdoc(int docID)Sugar for.getIndexReader().document(docID)Documentdoc(int docID, Set<String> fieldsToLoad)Sugar for.getIndexReader().document(docID, fieldsToLoad)voiddoc(int docID, StoredFieldVisitor fieldVisitor)Sugar for.getIndexReader().document(docID, fieldVisitor)Explanationexplain(Query query, int doc)Returns an Explanation that describes howdocscored againstquery.protected Explanationexplain(Weight weight, int doc)Expert: low-level implementation method Returns an Explanation that describes howdocscored againstweight.static QueryCachegetDefaultQueryCache()Expert: Get the defaultQueryCacheornullif the cache is disabled.static QueryCachingPolicygetDefaultQueryCachingPolicy()Expert: Get the defaultQueryCachingPolicy.static SimilaritygetDefaultSimilarity()Expert: returns a default Similarity instance.IndexReadergetIndexReader()Return theIndexReaderthis searches.QueryCachegetQueryCache()Return the query cache of thisIndexSearcher.QueryCachingPolicygetQueryCachingPolicy()Return the query cache of thisIndexSearcher.SimilaritygetSimilarity(boolean needsScores)Expert: Get theSimilarityto use to compute scores.IndexSearcher.LeafSlice[]getSlices()Returns the leaf slices used for concurrent searching, or null if noExecutorServicewas passed to the constructor.IndexReaderContextgetTopReaderContext()Returns this searchers the top-levelIndexReaderContext.Queryrewrite(Query original)Expert: called to re-write queries into primitive queries.protected voidsearch(List<LeafReaderContext> leaves, Weight weight, Collector collector)Lower-level search API.TopDocssearch(Query query, int n)Finds the topnhits forquery.TopFieldDocssearch(Query query, int n, Sort sort)Search implementation with arbitrary sorting.TopFieldDocssearch(Query query, 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.voidsearch(Query query, Collector results)Lower-level search API.<C extends Collector,T>
Tsearch(Query query, CollectorManager<C,T> collectorManager)Lower-level search API.TopDocssearchAfter(ScoreDoc after, Query query, int numHits)Finds the topnhits forquerywhere all results are after a previous result (after).TopDocssearchAfter(ScoreDoc after, Query query, int n, Sort sort)Finds the topnhits forquerywhere all results are after a previous result (after).TopFieldDocssearchAfter(ScoreDoc after, Query query, int numHits, Sort sort, boolean doDocScores, boolean doMaxScore)Finds the topnhits forquerywhere all results are after a previous result (after), allowing control over whether hit scores and max score should be computed.static voidsetDefaultQueryCache(QueryCache defaultQueryCache)Expert: set the defaultQueryCacheinstance.static voidsetDefaultQueryCachingPolicy(QueryCachingPolicy defaultQueryCachingPolicy)Expert: set the defaultQueryCachingPolicyinstance.voidsetQueryCache(QueryCache queryCache)Set theQueryCacheto use when scores are not needed.voidsetQueryCachingPolicy(QueryCachingPolicy queryCachingPolicy)Set theQueryCachingPolicyto use for query caching.voidsetSimilarity(Similarity similarity)Expert: Set the Similarity implementation used by this IndexSearcher.protected IndexSearcher.LeafSlice[]slices(List<LeafReaderContext> leaves)Expert: Creates an array of leaf slices each holding a subset of the given leaves.TermStatisticstermStatistics(Term term, TermContext context)ReturnsTermStatisticsfor a term.StringtoString()
-
-
-
Field Detail
-
readerContext
protected final IndexReaderContext readerContext
-
leafContexts
protected final List<LeafReaderContext> leafContexts
-
-
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 close/awaitTermination this ExecutorService on close; you must do so, eventually, on your own. NOTE: if you are usingNIOFSDirectory, 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-levelIndexReaderContext.Given a non-
nullExecutorServicethis method runs searches for each segment separately, using the provided ExecutorService. IndexSearcher will not close/awaitTermination this ExecutorService on close; you must do so, eventually, on your own. NOTE: if you are usingNIOFSDirectory, 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-levelIndexReaderContext.- 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 respectgetSimilarity(boolean).- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
getDefaultQueryCache
public static QueryCache getDefaultQueryCache()
Expert: Get the defaultQueryCacheornullif the cache is disabled.- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
setDefaultQueryCache
public static void setDefaultQueryCache(QueryCache defaultQueryCache)
Expert: set the defaultQueryCacheinstance.- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
getDefaultQueryCachingPolicy
public static QueryCachingPolicy getDefaultQueryCachingPolicy()
Expert: Get the defaultQueryCachingPolicy.- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
setDefaultQueryCachingPolicy
public static void setDefaultQueryCachingPolicy(QueryCachingPolicy defaultQueryCachingPolicy)
Expert: set the defaultQueryCachingPolicyinstance.- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
setQueryCache
public void setQueryCache(QueryCache queryCache)
Set theQueryCacheto use when scores are not needed. A value ofnullindicates that query matches should never be cached. This method should be called before starting using thisIndexSearcher.NOTE: When using a query cache, queries should not be modified after they have been passed to IndexSearcher.
- See Also:
QueryCache- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
getQueryCache
public QueryCache getQueryCache()
Return the query cache of thisIndexSearcher. This will be either thedefault query cacheor the query cache that was last set throughsetQueryCache(QueryCache). A return value ofnullindicates that caching is disabled.- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
setQueryCachingPolicy
public void setQueryCachingPolicy(QueryCachingPolicy queryCachingPolicy)
Set theQueryCachingPolicyto use for query caching. This method should be called before starting using thisIndexSearcher.- See Also:
QueryCachingPolicy- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
getQueryCachingPolicy
public QueryCachingPolicy getQueryCachingPolicy()
Return the query cache of thisIndexSearcher. This will be either thedefault policyor the policy that was last set throughsetQueryCachingPolicy(QueryCachingPolicy).- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
slices
protected IndexSearcher.LeafSlice[] slices(List<LeafReaderContext> leaves)
Expert: Creates an array of leaf slices each holding a subset of the given leaves. EachIndexSearcher.LeafSliceis executed in a single thread. By default there will be oneIndexSearcher.LeafSliceper leaf (LeafReaderContext).
-
getIndexReader
public IndexReader getIndexReader()
Return theIndexReaderthis 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 IOExceptionSugar 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)
-
setSimilarity
public void setSimilarity(Similarity similarity)
Expert: Set the Similarity implementation used by this IndexSearcher.
-
getSimilarity
public Similarity getSimilarity(boolean needsScores)
Expert: Get theSimilarityto use to compute scores. WhenneedsScoresisfalse, this method will return a simpleSimilaritythat does not leverage scoring factors such as norms. WhenneedsScoresistrue, this returns theSimilaritythat has been set throughsetSimilarity(Similarity)or thegetDefaultSimilarity()defaultSimilarityif none has been set explicitly.
-
count
public int count(Query query) throws IOException
Count how many documents match the given query.- Throws:
IOException
-
getSlices
public IndexSearcher.LeafSlice[] getSlices()
Returns the leaf slices used for concurrent searching, or null if noExecutorServicewas passed to the constructor.- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
searchAfter
public TopDocs searchAfter(ScoreDoc after, Query query, int numHits) throws IOException
Finds the topnhits forquerywhere 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 exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
search
public TopDocs search(Query query, int n) throws IOException
Finds the topnhits forquery.- Throws:
BooleanQuery.TooManyClauses- If a query would exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
search
public void search(Query query, Collector results) throws IOException
Lower-level search API.LeafCollector.collect(int)is called for every matching document.- Throws:
BooleanQuery.TooManyClauses- If a query would exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
search
public TopFieldDocs search(Query query, 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 topnhits forquery, and sorting the hits by the criteria insort. IfdoDocScoresistruethen the score of each hit will be computed and returned. IfdoMaxScoreistruethen the maximum score over all collected hits will be computed.- Throws:
BooleanQuery.TooManyClauses- If a query would exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
search
public TopFieldDocs search(Query query, int n, Sort sort) throws IOException
Search implementation with arbitrary sorting.- Parameters:
query- The query to search forn- Return only the top n resultssort- TheSortobject- Returns:
- The top docs, sorted according to the supplied
Sortinstance - 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 topnhits forquerywhere 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 exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
searchAfter
public TopFieldDocs searchAfter(ScoreDoc after, Query query, int numHits, Sort sort, boolean doDocScores, boolean doMaxScore) throws IOException
Finds the topnhits forquerywhere 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. IfdoDocScoresistruethen the score of each hit will be computed and returned. IfdoMaxScoreistruethen the maximum score over all collected hits will be computed.- Throws:
BooleanQuery.TooManyClauses- If a query would exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
search
public <C extends Collector,T> T search(Query query, CollectorManager<C,T> collectorManager) throws IOException
Lower-level search API. Search all leaves using the givenCollectorManager. In contrast tosearch(Query, Collector), this method will use the searcher'sExecutorServicein order to parallelize execution of the collection on the configuredleafSlices.- Throws:
IOException- See Also:
CollectorManager- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
search
protected void search(List<LeafReaderContext> leaves, Weight weight, Collector collector) throws IOException
Lower-level search API.LeafCollector.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 onweight- to match documentscollector- to receive hits- Throws:
BooleanQuery.TooManyClauses- If a query would exceedBooleanQuery.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 exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
explain
public Explanation explain(Query query, int doc) throws IOException
Returns an Explanation that describes howdocscored againstquery.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 howdocscored againstweight.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 exceedBooleanQuery.getMaxClauseCount()clauses.IOException
-
createNormalizedWeight
@Deprecated public Weight createNormalizedWeight(Query query, boolean needsScores) throws IOException
Deprecated.Clients should rewrite the query and then callcreateWeight(Query, boolean, float)with a boost value of 1fCreates a normalized weight for a top-levelQuery. The query is rewritten by this method andQuery.createWeight(org.apache.lucene.search.IndexSearcher, boolean, float)called, afterwards theWeightis normalized. The returnedWeightcan then directly be used to get aScorer.- Throws:
IOException- NOTE: This API is for internal purposes only and might change in incompatible ways in the next release.
-
createWeight
public Weight createWeight(Query query, boolean needsScores, float boost) throws IOException
Creates aWeightfor the given query, potentially adding caching if possible and configured.- Throws:
IOException- WARNING: This API is experimental and might change in incompatible ways in the next release.
-
getTopReaderContext
public IndexReaderContext getTopReaderContext()
Returns this searchers the top-levelIndexReaderContext.- See Also:
IndexReader.getContext()
-
termStatistics
public TermStatistics termStatistics(Term term, TermContext context) throws IOException
ReturnsTermStatisticsfor 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
ReturnsCollectionStatisticsfor 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.
-
-