Lucene自定义评分实现以下两步就OK了
一、
package myscore;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.Query;
import java.io.IOException;
/**
* 定义自己的评分查询Query
* Created with IntelliJ IDEA.
* User: wxshi
* Date: 15-2-10
* Time: 上午10:49
* To change this template use File | Settings | File Templates.
*/
public class MyCustomScoreQuery extends CustomScoreQuery {
public MyCustomScoreQuery(Query subQuery) {
super(subQuery);
}
@Override
protected CustomScoreProvider getCustomScoreProvider(AtomicReaderContext context) throws IOException {
//注册使用自定义的评分实现方式
return new MyScoreProvider(context);
}
}
二、
package myscore;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.util.Bits;
import java.io.IOException;
/**
* 重写评分的实现方式
* Created with IntelliJ IDEA.
* User: wxshi
* Date: 15-2-10
* Time: 上午10:51
* To change this template use File | Settings | File Templates.
*/
public class MyScoreProvider extends CustomScoreProvider {
private AtomicReaderContext context;
public MyScoreProvider(AtomicReaderContext context) {
super(context);
this.context = context;
}
//重写评分方法,假定需求为文档size倒排序
@Override
public float customScore(int doc, float subQueryScore, float valSrcScore)throws IOException {
float score = scoreBySize(doc,subQueryScore,valSrcScore);
//float score = scoreByField(doc,subQueryScore,valSrcScore);
return score;
}
//按文件大小评分,文件越小,评分越高
private float scoreBySize(int doc, float subQueryScore, float valSrcScore){
// 从域缓存中加载索引字段信息
FieldCache.Longs longs= null;
try {
longs = FieldCache.DEFAULT.getLongs(context.reader(), "size", false);
//doc实际上就是Lucene中得docId
long size = longs.get(doc);
float ff = Float.parseFloat(String.valueOf(size));//判断加权
//通过得分相乘放大分数,此处可以控制与原有得分结合的方式,加减乘除都可以
return subQueryScore * valSrcScore / ff;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return 0f;
}
//按文档域中含有某个字段(文学)打分,
private float scoreByField(int doc, float subQueryScore, float valSrcScore){
try {
Bits bit = FieldCache.DEFAULT.getDocsWithField(context.reader(), "content");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return 0f;
}
}