您的位置:首页 > 产品设计 > UI/UE

【Lucene】Lucene通过CustomScoreQuery实现自定义评分

2016-06-12 09:11 615 查看
建立业务查询的query,该query嵌套在自定义评分CustomScoreQuery中,从而为query添加了自定义评分功能

Query query = new TermQuery(new Term("name", "myname"));
query = new ProductCustomScoreQuery(query);


从上一步可以看出, 我们需要新建一个ProductCustomScoreQuery类,该类继承CustomScoreQuery类,并重写getCustomScoreProvider()方法,该方法返回一个CustomScoreProvider对象,该对象是最终实现自定义评分功能的对象

public class ProductCustomScoreQuery extends CustomScoreQuery
{
public ProductCustomScoreQuery(Query subQuery)
{
super(subQuery);
}

@Override
protected CustomScoreProvider getCustomScoreProvider(AtomicReaderContext context) throws IOException
{
return new ProductCustomScoreProvider(context);
}
}


从上一步可以看出,我们还需要新建一个ProductCustomScoreProvider类, 该类继承CustomScoreProvider类,并重写customScore()方法,该方法是实现自定义评分的核心方法。

public class ProductCustomScoreProvider extends CustomScoreProvider
{
public ProductCustomScoreProvider(AtomicReaderContext context)
{
super(context);
}

@Override
public float customScore(int doc, float subQueryScore, float valSrcScore) throws IOException
{
//获取Document的ProductCode
BytesRef br = new BytesRef();
FieldCache.DEFAULT.getTerms(this.context.reader(), "ProductCode", false).get(doc, br);
String productCode = br.utf8ToString();

//文档在原始评分的基础上, 再乘以productCode的长度, 实现自定义评分
return productCode.length * super.customScore(doc, subQueryScore, valSrcScore);
}

}


本文出自 “DeaconLi” 博客,请务必保留此出处http://lizhuquan0769.blog.51cto.com/2591147/1788065
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: