在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根据大小排序。

Lucene 排序 Sort与SortField的更多相关文章

  1. 转:详细解说 STL 排序(Sort)

    详细解说 STL 排序(Sort) 详细解说 STL 排序(Sort) 作者Winter 详细解说 STL 排序(Sort) 0 前言: STL,为什么你必须掌握 1 STL提供的Sort 算法 1. ...

  2. 设计模式 - 模板方法模式(template method pattern) 排序(sort) 具体解释

    模板方法模式(template method pattern) 排序(sort) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考模板方法模式(tem ...

  3. [js] - 关于js的排序sort

    js的排序sort并不能一次排序好 function solution(nums){ return nums.sort(sortNumber); } function sortNumber(a, b) ...

  4. 给乱序的链表排序 · Sort List, 链表重排reorder list LoLn...

    链表排序 · Sort List [抄题]: [思维问题]: [一句话思路]: [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入): [画图]: quick ...

  5. 详细解说 STL 排序(Sort)(转)

    作者Winter 详细解说 STL 排序(Sort) 0 前言: STL,为什么你必须掌握 1 STL提供的Sort 算法 1.1 所有sort算法介绍 1.2 sort 中的比较函数 1.3 sor ...

  6. Excel VBA解读(54):排序——Sort方法

    Excel VBA解读(54):排序——Sort方法 看看下面的Excel界面截图,“排序”和“筛选”往往在一起,这大概是很多数据需要先排序后筛选吧  首先以“性别”作为排序字段,升序排列,并且第一行 ...

  7. sort排序,按指定字段进去重,sort -t "^" -k 8 -su,ls给文件名中数字排序sort -k1.5n,Tab符要转义

    sort sort 命令对 File 参数指定的文件中的行排序,并将结果写到标准输出.如果 File 参数指定多个文件,那么 sort 命令将这些文件连接起来,并当作一个文件进行排序. sort语法 ...

  8. 详细解说 STL 排序(Sort)

    0 前言: STL,为什么你必须掌握 对于程序员来说,数据结构是必修的一门课.从查找到排序,从链表到二叉树,几乎所有的算法和原理都需要理解,理解不了也要死记硬背下来.幸运的是这些理论都已经比较成熟,算 ...

  9. 53. 特殊的O(n)时间排序[sort ages with hashtable]

    [本文链接] http://www.cnblogs.com/hellogiser/p/sort-ages-with-hashtable.html [题目] 某公司有几万名员工,请完成一个时间复杂度为O ...

随机推荐

  1. C#中类的默认访问是私有的

    如果类前面没有访问修饰符的话,那里面的成员默认是私有private. 下面的代码是从MSDN上拷的,那个d它说明了私有:class Employee{private int i;double d; / ...

  2. 【单页应用】view与model相关梳理(转载)

    [单页应用]view与model相关梳理 前情回顾 根据之前的学习,我们形成了一个view与一个messageCenterview这块来说又内建了一套mvc的东西,我们这里来理一下首先View一层由三 ...

  3. UART(串口)

    (1)串行通信线路三种工作方式:单工通信.半双工通信.全双工通信 单工:单工就是指A只能发信号,而B只能接收信号,通信是单向的. 半双工:半双工就是指A能发信号给B,B也能发信号给A,但这两个过程不能 ...

  4. HDOJ/HDU 1075 What Are You Talking About(字符串查找翻译~Map)

    Problem Description Ignatius is so lucky that he met a Martian yesterday. But he didn't know the lan ...

  5. ubuntu adb devices 找不到任何东西,安装驱动

    在Android平台下做开发,adb总是需要使用到的,同时,因为linux没有windows这样操作傻瓜化,有些东西还是需要自行设置的,否则将会连接不上. 关于这些内容,google也有一定的描述,可 ...

  6. python-面向对象(四)——类成员的访问方式汇总

    类成员的访问方式 #!/usr/bin/env python # _*_coding:utf-8 _*_ class pepole(object): '''This is __doc__ inform ...

  7. Zend Framework 2参考Zend\Authentication(数据库表认证)

    + 转载自:Zend Framework 2参考Zend\Authentication(数据库表认证) 介绍 Zend\Authentication\Adapter\DbTable提供对存储在数据库表 ...

  8. Splunk < 6.3 版本 SSL 证书过期事宜

    最近Splunk发出邮件提醒客户SSL证书过期事宜. 问题看起来比较严重,因为所有的实例,包括 forwarder\peernode\indexer\master node 等等都受影响,而且Depl ...

  9. SQL查询记录添加序号(HANA)

    语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN) row_number() OVER() 从1开始,为每一条分组记录返回一个数字,这里 ...

  10. js读取本地磁盘文本文件并保存为JSON数据(有格式的文本)

    主要的代码是红色区域,HTML5获取本地文件对象并进行操作 //给上传按钮添加点击事件 $(".myappTXTUploadBtn").click(function(){ var ...