【Lucene】Lucene通過CustomScoreQuery實現自定義評分

  • 建立業務查詢的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);
	}
	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章