I have an index which made by lucene and each document in it have 3 filed that one of them is a numeric field which is my frequency. I search in my index but before it I want to sort it by the numeric field. is there any way to sort it by lucene before my search?
Sorting before searching doesn't really make a lot of sense, since Lucene is creating an inverted index for searching against, rather than storing and searching through a sequential set of documents.
However, it sounds like you want to run a search and get results that are already sorted in a specified way.
This is done by passing a Sort to the IndexSearcher.search call, like:
SortField field = new SortField("frequency", SortField.Type.FLOAT);
//Sorting, first, by "frequency", then by relevance score
Sort sort = new Sort(field, Sort.FIELD_SCORE);
searcher.search(query, maxDocs, sort);
The name of the field makes me wonder if you aren't re-inventing the wheel though. Lucene already factors term frequency into it's relevance scores. If you want to tweak that sort of scoring, if might be a better idea to create a custom Similarity class to calculate scores for you, extending either TFIDFSimilarity or DefaultSimilarity, and overriding the method tf, particularly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With