在sql语句中,有升序和降序排列。在Lucene中,同样也有。

Sort里的属性 SortField里的属性 含义
Sort.INDEXORDER SortField.FIELD_DOC 按照索引的顺序进行排序
Sort.RELEVANCE SortField.FIELD_SCORE 按照关联性评分进行排序
=========SortField类============
//field是排序字段type是排序类型
public SortField(String field, Type type);
//field是排序字段type是排序类型reverse是指定升序还是降序
//reverse 为true是降序 false为升序
public SortField(String field, Type type, boolean reverse) =========Sort类============
public Sort();//Sort对象构造方法默认是按文档评分排序
public Sort(SortField field);//排序的一个SortField
public Sort(SortField... fields)//排序的多个SortField可以传入一个数组

前提,创建索引:

 import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Random; import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory; public class FileIndexUtils {
private static Directory directory = null;
static{
try {
directory = FSDirectory.open(Paths.get("D://lucene//document"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static Directory getDirectory(){
return directory;
}
/**
* 创建索引
* @param hasNew
*/
@SuppressWarnings("deprecation")
public static void createIndex(boolean hasNew){
IndexWriter writer = null;
try {
writer = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
if(hasNew){
writer.deleteAll();
} Document document = null;
int index = 0;
//随机数,为排序数字
Random random = new Random();
//为源文件创建索引
File file = new File("D://text");
for(File f:file.listFiles()){
int score = random.nextInt();
document = new Document();
document.add(new Field("id",String.valueOf(index++), Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("content",new FileReader(f)));
document.add(new Field("fileName",f.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
document.add(new Field("path",f.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
document.add(new IntField("score",score,Field.Store.YES));
document.add(new NumericDocValuesField("size",(long)f.length()));
document.add(new LongField("size", f.length(), Field.Store.YES));
document.add(new IntField("date",(int) f.lastModified(),Field.Store.YES));
writer.addDocument(document);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

一,Sort排序

getSearcher()

 private static IndexReader reader = null;
static{
try {
reader = DirectoryReader.open(FileIndexUtils.getDirectory());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} public IndexSearcher getSearcher(){
try {
if(reader == null){
reader = DirectoryReader.open(FileIndexUtils.getDirectory());
}else{
IndexReader tr = DirectoryReader.openIfChanged((DirectoryReader) reader);
if(tr!=null) {
reader.close();
reader = tr;
}
}
return new IndexSearcher(reader);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
   /**
* 排序Sort
* @param queryStr
* @param sort
*/
public void searcherBySort(String queryStr,Sort sort) {
try {
IndexSearcher searcher = getSearcher();
QueryParser parser = new QueryParser("content",new StandardAnalyzer());
Query query = parser.parse(queryStr);
TopDocs tds = null;
if(sort!=null)
tds = searcher.search(query, 50, sort);
else {
tds = searcher.search(query, 50);
}
for(ScoreDoc sd:tds.scoreDocs) {
Document d = searcher.doc(sd.doc);
System.out.println(sd.doc+":("+sd.score+")" +
"["+d.get("fileName")+"【"+d.get("path")+"】---"+d.get("score")+"--->"+
Integer.valueOf(d.get("size"))/1024+"-----");
} } catch (Exception e) {
e.printStackTrace();
}
}

测试:

    @Test
public void test01(){
st.searcherBySort("select",Sort.RELEVANCE);
System.out.println("------------");
st.searcherBySort("select",null);
}

二、SortField

/**
* 排序SortField
* @param sortField
* @param reverse
*/
public void searcherBySortField(String filename,boolean reverse){
try {
IndexSearcher searcher = getSearcher();
SortField sortField = new SortField(filename,SortField.Type.LONG,reverse);
Sort sort = new Sort(sortField); TopDocs tds = searcher.search(new MatchAllDocsQuery(),100,sort);
for(ScoreDoc sd:tds.scoreDocs){
Document d = searcher.doc(sd.doc);
System.out.println("["+d.get("fileName")+"]【"+d.get("path")+"】---score:"+d.get("score")+"--->"+"size:"+d.get("size"));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

测试:

    @Test
public void test02(){
st.searcherBySortField("size", false);
System.out.println("------------");
}

size根据大小排序。

最新文章

  1. iFrame 功能详解
  2. 浏览器中CSS的BUG
  3. 使用my exclipse对数据库进行操作(3)
  4. 深入浅出Redis04使用Redis数据库(lists类型)
  5. 月下载量上千次的APP源码分享
  6. A. Alyona and Numbers(CF ROUND 358 DIV2)
  7. MyBatis学习-入门篇
  8. ELK5.0安装教程
  9. jvm系列 (四) ---强、软、弱、虚引用
  10. 享受Python和PHP动态类型检查语言的快感
  11. Asp.NetCore轻松学-配置服务 apollo 部署实践
  12. centos7升级内核至最新
  13. mysql用户管理及授权
  14. Tomcat集成Memcached Session Manager方案
  15. AdapterView<T extends Adapter>
  16. 51nod 1275 连续字段的差异(单调队列)
  17. php统计中英文混合的文章字数
  18. POJ 1061 青蛙的约会(拓展欧几里得算法求解模线性方程组详解)
  19. __NSCFConstantString && __NSPlaceholderDictionary
  20. BZOJ4152:[AMPPZ2014]The Captain——题解

热门文章

  1. HDOJ/HDU 1015 Safecracker(枚举、暴力)
  2. JavaScript浏览器本地数据存储
  3. C++ 把输出结果写入文件/从文件中读取数据
  4. 部署war包到tomcat服务器
  5. Maven source jar get
  6. 升级OpenSSH详细步骤
  7. 跟着百度学PHP[7]会话控制(session与cookie) 1.cookie的设置
  8. linux 入侵检查转载
  9. iOS socket原理及连接过程详解
  10. java方法的重载