lucene自定义排序例子(二)

2014-11-24 10:46:16 · 作者: · 浏览: 9
;
}
@Override
public void copy(int arg0, int arg1) throws IOException {
// TODO Auto-generated method stub
values[arg0] = getDistance(arg1);
}
@Override
public void setBottom(int arg0) {
// TODO Auto-generated method stub
bottom = values[arg0];
}
@Override
public void setNextReader(IndexReader arg0, int arg1) //在读下一个段时,书上有误,根据api的理解,如下实现得到正确结果
throws IOException {
// TODO Auto-generated method stub
String[] temp = FieldCache.DEFAULT.getStrings(arg0, "location");
xDoc = new int[temp.length];
yDoc = new int[temp.length];
for(int i = 0 ;i
String[] str = temp[i].split(",");
xDoc[i] = Integer.parseInt(str[0]);
yDoc[i] = Integer.parseInt(str[1]);
}
}
@Override
public Object value(int arg0) {
// TODO Auto-generated method stub
return new Float(values[arg0]);
}
public int sortType(){
return SortField.CUSTOM;
}
public String toString(){
return "Distance from ("+x+","+y+")";
}
}
}
下面是具体的测试运行排序结果的程序:
[java]
package org.apache.lucene.demo;
import java.io.IOException;
import javax.crypto.SealedObject;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelectorResult;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
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.search.TopFieldDocs;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
public class DistanceSortingTest {
/**
* @param args
* @throws IOException
* @throws LockObtainFailedException
* @throws CorruptIndexException
*/
public static void main(String[] args) throws CorruptIndexException, LockObtainFailedException, IOException {
// TODO Auto-generated method stub
RAMDirectory directory = new RAMDirectory();
IndexWriter indexWriter = new IndexWriter(directory, new WhitespaceAnalyzer(),
IndexWriter.MaxFieldLength.UNLIMITED);
addPoint(indexWriter, "El charro", "restaurant", 1, 2);
addPoint(indexWriter, "Cafe Poca Cosa", "restaurant", 5, 9);
addPoint(indexWriter, "Los Betos", "restaurant", 9, 6);
addPoint(indexWriter, "Nico's Toco Shop", "restaurant", 3, 8);
indexWriter.close();
Searcher sear