lucene利用sort对查询结果进行排序示例

利用sort对查询结果进行排序示例

对于要排序的字段,在索引的时候可以Field.Index.NOT_ANALYZED


package com.cn;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class TTT {

	public static void main(String []args)throws Exception {
		String [] ids = {"1","2","3","4","5"};
		String [] bookName = {"java start","java begin","java in action","java web","java ssh"};
		String [] page = {"300","400","256","302","279"};
		String [] price = {"89","99","70","60","120"};
		Directory directory = new RAMDirectory();
		
		IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34)));
		for(int i = 0;i < ids.length;i++){
			Document doc = new Document();
			doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			doc.add(new Field("bookName",bookName[i],Field.Store.YES,Field.Index.ANALYZED));
			doc.add(new Field("page",page[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			doc.add(new Field("price",price[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			indexWriter.addDocument(doc);
		}
		System.out.println("total:"+indexWriter.numDocs());
		indexWriter.close();
		Term term = new Term("bookName","java");
		Query query = new TermQuery(term);
		IndexSearcher indexSearcher = new IndexSearcher(directory);
		Sort sort = new Sort();
		SortField sortField = new SortField("price", SortField.INT);
		sort.setSort(sortField);
		TopDocs topDocs = indexSearcher.search(query, 10, sort);
		ScoreDoc [] scoreDoc = topDocs.scoreDocs;
		for(int i=0;i<scoreDoc.length;i++){
			Document d = indexSearcher.doc(scoreDoc[i].doc);
			System.out.println(d.get("bookName")+"\t"+d.get("page")+"\t"+d.get("price"));
		}
	}
}

运行结果为:

total:5
java web    302    60
java in action    256    70
java start    300    89
java begin    400    99
java ssh    279    120


阅读更多
个人分类: lucene
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭