作者:lxm淡淡嘚甜_671 | 来源:互联网 | 2023-05-19 08:54
第二种自定义评分的实现方式如下:***自定义评分的第二种写法,基于FunctionQuery*(1)创建类并继承ValueSource*(2)重写getValues方法*@author
第二种自定义评分的实现方式如下:
**
* 自定义评分的第二种写法,基于FunctionQuery
* (1)创建类并继承ValueSource
* (2)重写getValues方法
* @author Johnny
*
*/
public class MySelfScore2 {
public void searchBySelfScore(){
try{
IndexSearcher search = new IndexSearcher(DirectoryReader.open(FileIndexUtils.getDirectory()));
Query q = new TermQuery(new Term("content","java"));
/**使用Lucene提供的CustomScoreQuery调用valueSource实现类**/
CustomScoreQuery csq = new CustomScoreQuery(q, new FunctionQuery(new MyScore2()));
TopDocs tds = search.search(csq, 200);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(ScoreDoc sd:tds.scoreDocs){
Document d = search.doc(sd.doc);
System.out.println(sd.doc+":("+sd.score+")" +
"["+d.get("filename")+"【"+d.get("path")+"】--->"+
d.get("size")+"-----"+sdf.format(new Date(Long.valueOf(d.get("date"))))+"]");
}
System.out.println("-----------Total result:"+tds.scoreDocs.length);
}catch(Exception e){
e.printStackTrace();
}
}
private class MyScore2 extends ValueSource{
@Override
public FunctionValues getValues(Map context,
final AtomicReaderContext readerContext) throws IOException {
return new FloatDocValues(this) {
@Override
public float floatVal(int doc) {
float s = 1;
//从域缓存中读取数据
// 从域缓存中加载索引字段信息
try {
Longs lOngs= FieldCache.DEFAULT.getLongs(readerContext.reader(), "size", false);
long size = longs.get(doc);
if(size>1000){
s = 0.5f;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
};
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String description() {
// TODO Auto-generated method stub
return null;
}
}
}
查询方法已经在上一篇博客中给出
测试方法如下:
/**第二种自定义评分方式**/
@Test
public void testSelfSore2(){
MySelfScore2 ms = new MySelfScore2();
ms.searchBySelfScore();
}