org.apache.lucene.search.function | Programmatic control over documents scores. |
org.apache.lucene.search.highlight | The highlight package contains classes to provide "keyword in context" features typically used to highlight search terms in the text of results pages. |
org.apache.lucene.search.payloads | The payloads package provides Query mechanisms for finding and using payloads. |
org.apache.lucene.search.regex | Regular expression Query. |
org.apache.lucene.search.similar | Document similarity query generators. |
org.apache.lucene.search.spans | The calculus of spans. |
org.apache.lucene.search.spell | Suggest alternate spellings for words. |
org.apache.lucene.search.vectorhighlight | This is an another highlighter implementation. |
ExtendedFieldCache | code | html | |
ExtendedFieldCache.DoubleParser | code | html | |
ExtendedFieldCache.LongParser | code | html | |
FieldCache | Expert: Maintains caches of term values. | code | html |
FieldCache.ByteParser | Interface to parse bytes from document fields. | code | html |
FieldCache.DoubleParser | Interface to parse doubles from document fields. | code | html |
FieldCache.FloatParser | Interface to parse floats from document fields. | code | html |
FieldCache.IntParser | Interface to parse ints from document fields. | code | html |
FieldCache.LongParser | Interface to parse long from document fields. | code | html |
FieldCache.Parser | Marker interface as super-interface to all parsers. | code | html |
FieldCache.ShortParser | Interface to parse shorts from document fields. | code | html |
ParallelMultiSearcher.Function | A function with one argument | code | html |
RMIRemoteSearchable | Marker interface to enable subclasses of org.apache.lucene.search.Searchable to be used via Java RMI. | code | html |
ScoreDocComparator | Expert: Compares two ScoreDoc objects for sorting. | code | html |
Searchable | The interface for search implementations. | code | html |
SortComparatorSource | Expert: returns a comparator for sorting ScoreDocs. | code | html |
Collector | Expert: Collectors are primarily meant to be used to gather raw results from a search, and implement sorting or custom result filtering, collation, etc. |
code | html |
DocIdSet | A DocIdSet contains a set of doc ids. | code | html |
DocIdSetIterator | This abstract class defines methods to iterate over a set of non-decreasing doc ids. | code | html |
Explanation.IDFExplanation | Small Util class used to pass both an idf factor as well as an explanation for that factor. | code | html |
FieldCache.CacheEntry | EXPERT: A unique Identifier/Description for each item in the FieldCache. | code | html |
FieldCacheImpl.Cache | Expert: Internal cache. | code | html |
FieldCacheRangeFilter | A range filter built on top of a cached single term field (in FieldCache ). | code | html |
FieldCacheRangeFilter.FieldCacheDocIdSet | code | html | |
FieldComparator | Expert: a FieldComparator compares hits so as to determine their sort order when collecting the top results with TopFieldCollector . | code | html |
FieldComparatorSource | Provides a FieldComparator for custom field sorting. | code | html |
FieldValueHitQueue | Expert: A hit queue for sorting by hits by terms in more than one field. | code | html |
Filter | Abstract base class for restricting which documents may be returned during searching. | code | html |
FilteredDocIdSet | Abstract decorator class for a DocIdSet implementation that provides on-demand filtering/validation mechanism on a given DocIdSet. | code | html |
FilteredDocIdSetIterator | Abstract decorator class of a DocIdSetIterator implementation that provides on-demand filter/validation mechanism on an underlying DocIdSetIterator. | code | html |
FilteredTermEnum | Abstract class for enumerating a subset of all terms. | code | html |
HitCollector | Lower-level search API. | code | html |
MultiTermQuery | An abstract Query that matches documents containing a subset of terms provided by a FilteredTermEnum enumeration. | code | html |
MultiTermQuery.RewriteMethod | Abstract class that defines how the query is rewritten. | code | html |
PhraseScorer | Expert: Scoring functionality for phrase queries. | code | html |
Query | The abstract base class for queries. | code | html |
Scorer | Expert: Common scoring functionality for different types of queries. | code | html |
Searcher | An abstract base class for search implementations. | code | html |
Similarity | Expert: Scoring API. | code | html |
SortComparator | Abstract base class for sorting hits returned by a Query. | code | html |
SpanFilter | Abstract base class providing a mechanism to restrict searches to a subset of an index and also maintains and returns position information. | code | html |
TopDocsCollector | A base class for all collectors that return a TopDocs output. | code | html |
TopFieldCollector | A Collector that sorts by SortField using FieldComparator s. | code | html |
TopScoreDocCollector | A Collector implementation that collects the top-scoring hits, returning them as a TopDocs . | code | html |
Weight | Expert: Calculate query weights and build query scorers. | code | html |
BooleanClause.Occur | Specifies how clauses are to occur in matching documents. | code | html |
BooleanClause | A clause in a BooleanQuery. | code | html |
BooleanFilter | A container Filter that allows Boolean composition of Filters. | code | html |
BooleanQuery | A Query that matches documents matching boolean combinations of other queries, e.g. | code | html |
BooleanQuery.BooleanWeight | Expert: the Weight for BooleanQuery, used to normalize, score and explain these queries. | code | html |
BooleanQuery.TooManyClauses | Thrown when an attempt is made to add more than #getMaxClauseCount() clauses. | code | html |
BooleanScorer | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
BooleanScorer.BooleanScorerCollector | code | html | |
BooleanScorer.Bucket | code | html | |
BooleanScorer.BucketScorer | code | html | |
BooleanScorer.BucketTable | A simple hash table of document scores within a range. | code | html |
BooleanScorer.SubScorer | code | html | |
BooleanScorer2 | An alternative to BooleanScorer that also allows a minimum number of optional scorers that should match. | code | html |
BooleanScorer2.Coordinator | code | html | |
BooleanScorer2.SingleMatchScorer | Count a scorer as a single match. | code | html |
BoostingQuery | The BoostingQuery class can be used to effectively demote results that match a given query. | code | html |
CachingSpanFilter | Wraps another SpanFilter's result and caches it. | code | html |
CachingWrapperFilter | Wraps another filter's result and caches it. | code | html |
CheckHits | Copyright 2004 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. | code | html |
ComplexExplanation | Expert: Describes the score computation for document and query, and can distinguish a match independent of a positive value. | code | html |
ConjunctionScorer | Scorer for conjunctions, sets of queries, all of which are required. | code | html |
ConstantScoreQuery | A query that wraps a filter and simply returns a constant score equal to the query boost for every document in the filter. | code | html |
ConstantScoreQuery.ConstantScorer | code | html | |
ConstantScoreQuery.ConstantWeight | code | html | |
ConstantScoreRangeQuery | A range query that returns a constant score equal to its boost for all documents in the range. | code | html |
DateFilter | A Filter that restricts search results to a range of time. | code | html |
DefaultSimilarity | Expert: Default scoring implementation. | code | html |
DisjunctionMaxQuery | A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries. | code | html |
DisjunctionMaxQuery.DisjunctionMaxWeight | Expert: the Weight for DisjunctionMaxQuery, used to normalize, score and explain these queries. | code | html |
DisjunctionMaxScorer | The Scorer for DisjunctionMaxQuery. | code | html |
DisjunctionSumScorer | A Scorer for OR like queries, counterpart of ConjunctionScorer . |
code | html |
DuplicateFilter | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
ExactPhraseScorer | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
Explanation | Expert: Describes the score computation for document and query. | code | html |
ExtendedFieldCacheImpl | code | html | |
FieldCache.CreationPlaceholder | code | html | |
FieldCache.StringIndex | Expert: Stores term text values and document ordering data. | code | html |
FieldCacheImpl | Expert: The default cache implementation, storing all values in memory. | code | html |
FieldCacheImpl.ByteCache | code | html | |
FieldCacheImpl.CacheEntryImpl | code | html | |
FieldCacheImpl.DoubleCache | code | html | |
FieldCacheImpl.Entry | Expert: Every composite-key in the internal cache is of this type. | code | html |
FieldCacheImpl.FloatCache | code | html | |
FieldCacheImpl.IntCache | code | html | |
FieldCacheImpl.LongCache | code | html | |
FieldCacheImpl.ShortCache | code | html | |
FieldCacheImpl.StopFillCacheException | Hack: When thrown from a Parser (NUMERIC_UTILS_* ones), this stops processing terms and returns the current FieldCache array. | code | html |
FieldCacheImpl.StringCache | code | html | |
FieldCacheImpl.StringIndexCache | code | html | |
FieldCacheTermsFilter | A Filter that only accepts documents whose single term value in the specified field is contained in the provided set of allowed terms. | code | html |
FieldCacheTermsFilter.FieldCacheTermsFilterDocIdSet | code | html | |
FieldCacheTermsFilter.FieldCacheTermsFilterDocIdSet.FieldCacheTermsFilterDocIdSetIterator | code | html | |
FieldComparator.ByteComparator | Parses field's values as byte (using FieldCache#getBytes and sorts by ascending value | code | html |
FieldComparator.DocComparator | Sorts by ascending docID | code | html |
FieldComparator.DoubleComparator | Parses field's values as double (using FieldCache#getDoubles and sorts by ascending value | code | html |
FieldComparator.FloatComparator | Parses field's values as float (using FieldCache#getFloats and sorts by ascending value | code | html |
FieldComparator.IntComparator | Parses field's values as int (using FieldCache#getInts and sorts by ascending value | code | html |
FieldComparator.LongComparator | Parses field's values as long (using FieldCache#getLongs and sorts by ascending value | code | html |
FieldComparator.RelevanceComparator | Sorts by descending relevance. | code | html |
FieldComparator.ShortComparator | Parses field's values as short (using FieldCache#getShorts and sorts by ascending value | code | html |
FieldComparator.StringComparatorLocale | Sorts by a field's value using the Collator for a given Locale. | code | html |
FieldComparator.StringOrdValComparator | Sorts by field's natural String sort order, using ordinals. | code | html |
FieldComparator.StringValComparator | Sorts by field's natural String sort order. | code | html |
FieldDoc | Expert: A ScoreDoc which also contains information about how to sort the referenced document. | code | html |
FieldDocSortedHitQueue | Expert: Collects sorted results from Searchable's and collates them. | code | html |
FieldSortedHitQueue | Expert: A hit queue for sorting by hits by terms in more than one field. | code | html |
FieldValueHitQueue.Entry | code | html | |
FieldValueHitQueue.MultiComparatorsFieldValueHitQueue | An implementation of FieldValueHitQueue which is optimized in case there is more than one comparator. | code | html |
FieldValueHitQueue.OneComparatorFieldValueHitQueue | An implementation of FieldValueHitQueue which is optimized in case there is just one comparator. | code | html |
FilterClause | A Filter that wrapped with an indication of how that filter is used when composed with another filter. | code | html |
FilterManager | Filter caching singleton. | code | html |
FilterManager.FilterCleaner | Keeps the cache from getting too big. | code | html |
FilterManager.FilterItem | Holds the filter and the last time the filter was used, to make LRU-based cache cleaning possible. | code | html |
FilteredQuery | A query that applies a filter to the results of another query. | code | html |
FuzzyLikeThisQuery | Fuzzifies ALL terms provided as strings and then picks the best n differentiating terms. | code | html |
FuzzyLikeThisQuery.FieldVals | code | html | |
FuzzyLikeThisQuery.FuzzyTermQuery | code | html | |
FuzzyLikeThisQuery.ScoreTerm | code | html | |
FuzzyLikeThisQuery.ScoreTermQueue | code | html | |
FuzzyQuery | Implements the fuzzy search query. | code | html |
FuzzyQuery.ScoreTerm | code | html | |
FuzzyTermEnum | Subclass of FilteredTermEnum for enumerating all terms that are similar to the specified filter term. | code | html |
Hit | Wrapper used by HitIterator to provide a lazily loaded hit from Hits . | code | html |
HitDoc | code | html | |
HitIterator | An iterator over Hits that provides lazy fetching of each document. | code | html |
HitQueue | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
Hits | A ranked list of documents, used to hold search results. | code | html |
IndexSearcher | Implements search over a single IndexReader. | code | html |
MatchAllDocsQuery | A query that matches all documents. | code | html |
MatchAllDocsQuery.MatchAllDocsWeight | code | html | |
MatchAllDocsQuery.MatchAllScorer | code | html | |
MockFilter | Copyright 2004 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. | code | html |
MultiPhraseQuery | MultiPhraseQuery is a generalized version of PhraseQuery, with an added method #add(Term[]) . | code | html |
MultiPhraseQuery.MultiPhraseWeight | code | html | |
MultiSearcher | Implements search over a set of Searchables . |
code | html |
MultiSearcher.CachedDfSource | Document Frequency cache acting as a Dummy-Searcher. | code | html |
MultiSearcher.MultiSearcherCallableNoSort | A thread subclass for searching a single searchable | code | html |
MultiSearcher.MultiSearcherCallableWithSort | A thread subclass for searching a single searchable | code | html |
MultiTermQuery.ConstantScoreAutoRewrite | A rewrite method that tries to pick the best constant-score rewrite method based on term and document counts from the query. | code | html |
MultiTermQuery.ConstantScoreBooleanQueryRewrite | code | html | |
MultiTermQuery.ConstantScoreFilterRewrite | code | html | |
MultiTermQuery.ScoringBooleanQueryRewrite | code | html | |
MultiTermQueryWrapperFilter | A wrapper for MultiTermQuery , that exposes its functionality as a Filter . | code | html |
NonMatchingScorer | A scorer that matches no document at all. | code | html |
NumericRangeFilter | A Filter that only accepts numeric values within a specified range. | code | html |
NumericRangeQuery | A Query that matches numeric values within a specified range. |
code | html |
NumericRangeQuery.NumericRangeTermEnum | Subclass of FilteredTermEnum for enumerating all terms that match the sub-ranges for trie range queries. | code | html |
ParallelMultiSearcher | Implements parallel search over a set of Searchables . |
code | html |
ParallelMultiSearcher.CountDocFreq | Accumulates the document frequency for a term. | code | html |
ParallelMultiSearcher.CountTotalHits | Counts the total number of hits for all TopDocs instances provided. | code | html |
PhrasePositions | Position of a term in a document that takes into account the term offset within the phrase. | code | html |
PhrasePrefixQuery | PhrasePrefixQuery is a generalized version of PhraseQuery, with an added method #add(Term[]) . | code | html |
PhrasePrefixQuery.PhrasePrefixWeight | code | html | |
PhraseQuery | A Query that matches documents containing a particular sequence of terms. | code | html |
PhraseQuery.PhraseWeight | code | html | |
PhraseQueue | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
PositiveScoresOnlyCollector | A Collector implementation which wraps another Collector and makes sure only documents with scores > 0 are collected. | code | html |
PrefixFilter | A Filter that restricts search results to values that have a matching prefix in a given field. | code | html |
PrefixQuery | A Query that matches documents containing terms with a specified prefix. | code | html |
PrefixTermEnum | Subclass of FilteredTermEnum for enumerating all terms that match the specified prefix filter term. | code | html |
QueryFilter | Constrains search results to only match those which also match a provided query. | code | html |
QueryTermVector | code | html | |
QueryWrapperFilter | Constrains search results to only match those which also match a provided query. | code | html |
RangeFilter | A Filter that restricts search results to a range of values in a given field. | code | html |
RangeQuery | A Query that matches documents within an exclusive range. | code | html |
RemoteCachingWrapperFilter | Provides caching of org.apache.lucene.search.Filter s themselves on the remote end of an RMI connection. | code | html |
RemoteSearchable | A remote searchable implementation. | code | html |
ReqExclScorer | A Scorer for queries with a required subscorer and an excluding (prohibited) sub DocIdSetIterator. | code | html |
ReqOptSumScorer | A Scorer for queries with a required part and an optional part. | code | html |
SampleComparable | An example Comparable for use with the custom sort tests. | code | html |
ScoreCachingWrappingScorer | A Scorer which wraps another scorer and caches the score of the current document. | code | html |
ScoreDoc | Expert: Returned by low-level search implementations. | code | html |
SimilarityDelegator | Expert: Delegating scoring implementation. | code | html |
SingleTermEnum | Subclass of FilteredTermEnum for enumerating a single term. | code | html |
SloppyPhraseScorer | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | code | html |
Sort | Encapsulates sort criteria for returned hits. | code | html |
SortField | Stores information about how to sort documents by terms in an individual field. | code | html |
SpanFilterResult | The results of a SpanQueryFilter. | code | html |
SpanFilterResult.PositionInfo | code | html | |
SpanFilterResult.StartEnd | code | html | |
SpanQueryFilter | Constrains search results to only match those which also match a provided query. | code | html |
TermQuery | A Query that matches documents containing a term. | code | html |
TermQuery.TermWeight | code | html | |
TermRangeFilter | A Filter that restricts search results to a range of term values in a given field. | code | html |
TermRangeQuery | A Query that matches documents within an range of terms. | code | html |
TermRangeTermEnum | Subclass of FilteredTermEnum for enumerating all terms that match the specified range parameters. | code | html |
TermScorer | Expert: A Scorer for documents matching a Term . |
code | html |
TermsFilter | Constructs a filter for docs matching any of the terms added to this class. | code | html |
TestSimilarity.SimpleSimilarity | code | html | |
TimeLimitedCollector | The TimeLimitedCollector is used to timeout search requests that take longer than the maximum allowed search time limit. |
code | html |
TimeLimitedCollector.TimeExceededException | Thrown when elapsed search time exceeds allowed search time. | code | html |
TimeLimitedCollector.TimerThread | code | html | |
TimeLimitingCollector | The TimeLimitingCollector is used to timeout search requests that take longer than the maximum allowed search time limit. | code | html |
TimeLimitingCollector.TimeExceededException | Thrown when elapsed search time exceeds allowed search time. | code | html |
TimeLimitingCollector.TimerThread | code | html | |
TopDocCollector | A HitCollector implementation that collects the top-scoring documents, returning them as a TopDocs . | code | html |
TopDocs | Represents hits returned by Searcher#search(Query,Filter,int) and Searcher#search(Query,int) . | code | html |
TopFieldCollector.MultiComparatorNonScoringCollector | code | html | |
TopFieldCollector.MultiComparatorScoringMaxScoreCollector | code | html | |
TopFieldCollector.MultiComparatorScoringNoMaxScoreCollector | code | html | |
TopFieldCollector.OneComparatorNonScoringCollector | code | html | |
TopFieldCollector.OneComparatorScoringMaxScoreCollector | code | html | |
TopFieldCollector.OneComparatorScoringNoMaxScoreCollector | code | html | |
TopFieldCollector.OutOfOrderMultiComparatorNonScoringCollector | code | html | |
TopFieldCollector.OutOfOrderMultiComparatorScoringMaxScoreCollector | code | html | |
TopFieldCollector.OutOfOrderMultiComparatorScoringNoMaxScoreCollector | code | html | |
TopFieldCollector.OutOfOrderOneComparatorNonScoringCollector | code | html | |
TopFieldCollector.OutOfOrderOneComparatorScoringMaxScoreCollector | code | html | |
TopFieldCollector.OutOfOrderOneComparatorScoringNoMaxScoreCollector | code | html | |
TopFieldDocCollector | A HitCollector implementation that collects the top-sorting documents, returning them as a TopFieldDocs . | code | html |
TopFieldDocs | Represents hits returned by Searcher#search(Query,Filter,int,Sort) . | code | html |
TopScoreDocCollector.InOrderTopScoreDocCollector | code | html | |
TopScoreDocCollector.OutOfOrderTopScoreDocCollector | code | html | |
WildcardQuery | Implements the wildcard search query. | code | html |
WildcardTermEnum | Subclass of FilteredTermEnum for enumerating all terms that match the specified wildcard filter term. | code | html |
TestBooleanPrefixQuery | code | html | |
TestCachingWrapperFilter | Copyright 2004 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. | code | html |
TestDateFilter | DateFilter JUnit tests. | code | html |
TestDocBoost | Document boost unit test. | code | html |
TestFilteredQuery | FilteredQuery JUnit tests. | code | html |
TestFuzzyQuery | Tests FuzzyQuery . | code | html |
TestMultiSearcher | Tests MultiSearcher class. | code | html |
TestNot | Similarity unit test. | code | html |
TestParallelMultiSearcher | Unit tests for the ParallelMultiSearcher | code | html |
TestPhrasePrefixQuery | This class tests PhrasePrefixQuery class. | code | html |
TestPhraseQuery | Tests PhraseQuery . | code | html |
TestPositionIncrement | Term position unit test. | code | html |
TestPrefixQuery | Tests PrefixQuery class. | code | html |
TestQueryTermVector | Copyright 2004 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. | code | html |
TestRangeQuery | code | html | |
TestRemoteSearchable | code | html | |
TestSetNorm | Document boost unit test. | code | html |
TestSimilarity | Similarity unit test. | code | html |
TestSort | Unit tests for sorting code. | code | html |
TestTermVectors | Copyright 2004 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. | code | html |
TestWildcard | TestWildcard tests the '*' and '?' wildard characters. | code | html |
Search over indices. Applications usually call org.apache.lucene.search.Searcher#search(Query,int) or org.apache.lucene.search.Searcher#search(Query,Filter,int) .
Of the various implementations of Query, the TermQuery is the easiest to understand and the most often used in applications. A TermQuery matches all the documents that contain the specified Term, which is a word that occurs in a certain Field. Thus, a TermQuery identifies and scores all Documents that have a Field with the specified string in it. Constructing a TermQuery is as simple as:
TermQuery tq = new TermQuery(new Term("fieldName", "term"));In this example, the Query identifies all Documents that have the Field named "fieldName" containing the word "term".
Things start to get interesting when one combines multiple TermQuery instances into a BooleanQuery. A BooleanQuery contains multiple BooleanClauses, where each clause contains a sub-query (Query instance) and an operator (from BooleanClause.Occur) describing how that sub-query is combined with the other clauses:
SHOULD — Use this operator when a clause can occur in the result set, but is not required. If a query is made up of all SHOULD clauses, then every document in the result set matches at least one of these clauses.
MUST — Use this operator when a clause is required to occur in the result set. Every document in the result set will match all such clauses.
MUST NOT — Use this operator when a clause must not occur in the result set. No document in the result set will match any such clauses.
Another common search is to find documents containing certain phrases. This is handled two different ways:
PhraseQuery — Matches a sequence of Terms. PhraseQuery uses a slop factor to determine how many positions may occur between any two terms in the phrase and still be considered a match.
SpanNearQuery — Matches a sequence of other SpanQuery instances. SpanNearQuery allows for much more complicated phrase queries since it is constructed from other SpanQuery instances, instead of only TermQuery instances.
The TermRangeQuery matches all documents that occur in the exclusive range of a lower Term and an upper Term. according to java.lang.String#compareTo(String) . It is not intended for numerical ranges, use NumericRangeQuery instead. For example, one could find all documents that have terms beginning with the letters a through c. This type of Query is frequently used to find documents that occur in a specific date range.
The NumericRangeQuery matches all documents that occur in a numeric range. For NumericRangeQuery to work, you must index the values using a special NumericField.
While the PrefixQuery has a different implementation, it is essentially a special case of the WildcardQuery. The PrefixQuery allows an application to identify all documents with terms that begin with a certain string. The WildcardQuery generalizes this by allowing for the use of * (matches 0 or more characters) and ? (matches exactly one character) wildcards. Note that the WildcardQuery can be quite slow. Also note that WildcardQuery should not start with * and ?, as these are extremely slow. To remove this protection and allow a wildcard at the beginning of a term, see method setAllowLeadingWildcard in QueryParser.
A FuzzyQuery matches documents that contain terms similar to the specified term. Similarity is determined using Levenshtein (edit) distance. This type of query can be useful when accounting for spelling variations in the collection.
Chances are DefaultSimilarity is sufficient for all your searching needs. However, in some applications it may be necessary to customize your Similarity implementation. For instance, some applications do not need to distinguish between shorter and longer documents (see a "fair" similarity).
To change Similarity, one must do so for both indexing and searching, and the changes must happen before either of these actions take place. Although in theory there is nothing stopping you from changing mid-stream, it just isn't well-defined what is going to happen.
To make this change, implement your own Similarity (likely you'll want to simply subclass DefaultSimilarity) and then use the new class by calling IndexWriter.setSimilarity before indexing and Searcher.setSimilarity before searching.
If you are interested in use cases for changing your similarity, see the Lucene users's mailing list at Overriding Similarity. In summary, here are a few use cases:
SweetSpotSimilarity — SweetSpotSimilarity gives small increases as the frequency increases a small amount and then greater increases when you hit the "sweet spot", i.e. where you think the frequency of terms is more significant.
Overriding tf — In some applications, it doesn't matter what the score of a document is as long as a matching term occurs. In these cases people have overridden Similarity to return 1 from the tf() method.
Changing Length Normalization — By overriding lengthNorm, it is possible to discount how the length of a field contributes to a score. In DefaultSimilarity, lengthNorm = 1 / (numTerms in field)^0.5, but if one changes this to be 1 / (numTerms in field), all fields will be treated "fairly".
[One would override the Similarity in] ... any situation where you know more about your data then just that it's "text" is a situation where it *might* make sense to to override your Similarity method.
Changing scoring is an expert level task, so tread carefully and be prepared to share your code if you want help.
With the warning out of the way, it is possible to change a lot more than just the Similarity when it comes to scoring in Lucene. Lucene's scoring is a complex mechanism that is grounded by three main classes:
In some sense, the Query class is where it all begins. Without a Query, there would be nothing to score. Furthermore, the Query class is the catalyst for the other scoring classes as it is often responsible for creating them or coordinating the functionality between them. The Query class has several methods that are important for derived classes:
The Weight interface provides an internal representation of the Query so that it can be reused. Any Searcher dependent state should be stored in the Weight implementation, not in the Query class. The interface defines six methods that must be implemented:
The Scorer abstract class provides common scoring functionality for all Scorer implementations and is the heart of the Lucene scoring process. The Scorer defines the following abstract (they are not yet abstract, but will be in Lucene 3.0 and should be considered as such now) methods which must be implemented (some of them inherited from DocIdSetIterator ):
In a nutshell, you want to add your own custom Query implementation when you think that Lucene's aren't appropriate for the task that you want to do. You might be doing some cutting edge research or you need more information back out of Lucene (similar to Doug adding SpanQuery functionality).