Lucene 排序 Sort与SortField

时间:2023-03-08 16:37:26

在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);
}

Lucene 排序 Sort与SortField

二、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("------------");
}

Lucene 排序 Sort与SortField

size根据大小排序。