計算基點與索引庫中每個地理位置的距離,按距離大小排序。基點為(0,0),計算從(0,0)到地圖中各個地方的距離,然後依此排序,但地方進行了分類,包括restaurant、school、shop。這些類放在乙個type域中,
1、通過實現sortcomparatorsource介面來完成自定義排序。對每個類分別完成計算基點到這些類的地方的距離
public class distancecomparatorsource implementssortcomparatorsource do
//完成包含當前項的文件的遍歷完成距離計算
}while(enumerator.next());//對指定域內的所有項進行遍歷,筆者認為fieldname
//是指query中指定的網域名稱,即這些地點的型別,因為地方可能至少要幾種類
//型,
所以要對域內的項進行遍歷。
}fianlly }
}public intcompare()
publiccomparable sortvalue(scoredoc i)
public intsorttype()
public string tostring(){
return "distance from("x","+y+")";
2、我們為每個地點都指定了三個域,即乙個地名,乙個用x和y座標表示的位置。
public class distancesortingtest extends tetstcase{
privateramdirectory directory;
privateindexsearcher searcher;
privatequeryquery;
protectedvoid setup() throws exception{
directory=new ramdirectory();
indexwriter writer=new indexwriter(directory,newwhitespaceanalyzer(),true);
addpoint(writer,"e1 charro","restaurant",1,2);
addpoint(writer,"cafe poca cosa","restaurant",5,9);
addpoint(writer,"os betos","restaurant",9,6);
addpoint(writer,"nico's tacoshop","restaurant",3,8);
writer.close();
searcher=newindexsearcher(directory);
query=new termquery(new term("type","restaurant"));
privatevoid addpoint(indexwriter writer,string name,string type,int x,inty)
throws ioexceptoin{
document doc=new document();
doc.add(field.keyword("name",name));
doc.add(field.keyword("type",type));
doc.add(field.keyword("location",x+","+y));
下面進行測試
sort sort=new sort(newsortfield("location",new distancecomparatorsource(0,0)));
hits hits=searcher.search(query,sort);
3、訪問自定義排序的值
使用indexsearcher的過載的search方法:
pulbic topfielddocs search(query query,filter filter,final in***ocs,sort sort)
1)topfielddocs類中包括了hits物件的總數,用來排序的sortfield陣列、fielddoc物件的集合。fielddoc封裝了已經計算出來的原始評分、文件id及comparables集合,comparable的值被每個sortfield物件呼叫。
2)如果沒有使用與排序相關的類,lucene為我們提供了類似的底層api,返回乙個包含scoredoc物件的topdocs物件。
3)sort sort=new sort(newsortfield("location",new distancecomparatorsource(0,0)));
//指定返回的hit物件上限為3
topfielddocs docs=searcher.search(query,null,3,sort);
//hits物件的總數
assertequals(4,docs.totalhits);//總數為4,因為要對所有hits進行評估找出3個最優的命中結果
assertequals(3,docs.scoredocs.length);//返回文件總數
fielddoc fielddoc=(fielddoc)docs.scoredocs[0];//獲得排序值
assertequals("(10,10)->(9,6)=sqrt(17)",newfloat(math.sqrt(17)),fielddoc.fields[0]);//斷言距離最近的餐廳
documentdocument=searcher.doc(fielddoc.doc);//獲得實際的文件
lucene自定義排序的實現
lucene能夠很方便的實現自定義排序 具體做法就是寫乙個類實現sortcomparatorsource這個介面 在類裡返回scoredoccomparator 實現scoredoccomparator 的三個方法compare,sortvalue,sorttype就行了 public class ...
lucene學習之自定義評分
想要根據城市來自定義評分,原來的輸出 根據 你好.我是jack 一共找到3檔案 編號 0 分數 1.0 id 1 city 北京 編號 1 分數 1.0 id 2 city 南京 編號 2 分數 1.0 id 3 city 上海 自己新建的query物件 public class myfieldsc...
Lucene 自定義過濾器Filter
lucene中查詢 query 和過濾 filter 有相似之處,查詢能處理的過濾也可以完成。不同之處在於查詢時帶有評分操作,返回的結果集有相關性評分,而過濾返回的結果集沒有相關性評分,即返回結果是無排序的。特定項範圍過濾器,如 a m 或者 o z termrangefilter filter n...