建立业务查询的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); } }