全文检索lucene学习笔记(五)

来源:互联网 发布:c语言程序入门 编辑:程序博客网 时间:2024/04/30 06:56
 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);}}}


 

原创粉丝点击