I’m testing sorting feature in lucene with no luck. I am new to it.
I’ve tried using either TopFieldCollector or TopFieldDocs but no sorting seems to be applied.
Below a test code. What’s wrong with it?
private void testNumericSorting(){
// 1. index some data
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
IndexWriter w = new IndexWriter(index, config);
addDoc(w, "orange", 1);
addDoc(w, "lemon orange", 10);
w.close();
// 2. query
String querystr = "orange";
Query q = new QueryParser(Version.LUCENE_35, "title", analyzer).parse(querystr);
int hitsPerPage = 10;
IndexSearcher searcher = new IndexSearcher(index, true);
// Normal score, with no sorting
//TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
//searcher.search(q, collector);
//ScoreDoc[] hits = collector.topDocs().scoreDocs;
// Score with TopFieldCollector
Sort sort = new Sort(new SortField[] {
SortField.FIELD_SCORE,
new SortField("num", SortField.INT) });
TopFieldCollector topField = TopFieldCollector.create(sort, hitsPerPage, true, true, true, false);
searcher.search(q, topField);
ScoreDoc[] sortedHits = topField.topDocs().scoreDocs;
// Score with TopFieldDocs
// TopFieldDocs topFields = searcher.search(q, null, hitsPerPage, sort);
// ScoreDoc[] sortedHits = topFields.scoreDocs;
System.out.println("Found " + sortedHits.length + " hits.");
for(int i=0;i<sortedHits.length;++i) {
int docId = sortedHits[i].doc;
float score = sortedHits[i].score;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("title")+ " score:"+score);
}
searcher.close();
}
private static void addDoc(IndexWriter w, String value, Integer num) throws IOException {
Document doc = new Document();
doc.add(new Field("title", value, Field.Store.YES, Field.Index.ANALYZED));
//doc.add(new NumericField("num", Field.Store.NO, false).setIntValue(num));
doc.add(new Field ("num", Integer.toString(num), Field.Store.NO, Field.Index.NOT_ANALYZED));
w.addDocument(doc);
}
If print results with and without sorting I get the following output (basically no changes):
Without sorting, found 2 hits.
1. orange score:0.5945348
2. lemon orange score:0.37158427
With sorting, found 2 hits.
1. orange score:0.5945348
2. lemon orange score:0.37158427
The problem is that you are adding the “num” field as a String and then trying to sort it as an integer. You should either add it as an integer (using NumericField) or sort as a String (but beware that it will be sorted according to the lexicographical order).