Lucene实现对查询结果的排序:
Sort sort = new Sort(new SortField("isbn", false)); //单个字段
Sort sort = new Sort(new SortField[]{new SortField("isbn", false), new SortField("pbl_dt", true)}); //多个字段
其中,SortField的构造函数中第二个参数能够确定是升序还是降序。(true:降序; false:升序)
提醒:索引中tokenized的字段是不能被排序的,否则会抛异常。
package com.lucene.search;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class Searcher {
public static void main(String[] args) throws Exception {
File indexDir = new File("C:\\target\\index\\book");
String q = "书";
if (!indexDir.exists() || !indexDir.isDirectory()) {
throw new IOException();
}
search(indexDir, q);
}
public static void search(File indexDir, String q) throws Exception {
Directory fsDir = FSDirectory.getDirectory(indexDir);
IndexSearcher searcher = new IndexSearcher(fsDir);
//Sort sort = new Sort(new SortField("isbn", false));
Sort sort = new Sort(new SortField[]{new SortField("isbn", false), new SortField("pbl_dt", true)});
Term term = new Term("content", q.toLowerCase());
TermQuery termQuery = new TermQuery(term);
Hits hits = searcher.search(termQuery, sort);
System.out.println("共有" + searcher.maxDoc() + "条索引,命中" + hits.length() + "条");
for (int i = 0; i < hits.length(); i++) {
int DocId = hits.id(i);
String DocName = hits.doc(i).get("name");
String DocIsbn = hits.doc(i).get("isbn");
String DocPblDt = hits.doc(i).get("pbl_dt");
System.out.println(DocId + ":" + DocName + " ISBN:" + DocIsbn + " PBLDT:" + DocPblDt);
}
}
}
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程