Search code examples
javalucenescoring

Lucene Custom Scoring


I want to make a lucene custom scoring function that takes a value stored in a document and add it to the final score.

I already figured out how to add a value to the scoring function , but I can't manage to get a stored value of a document into the method.

 class CustomizedScoreProvider extends CustomScoreProvider {

    public CustomizedScoreProvider(LeafReaderContext reader) {
            super(reader);
            // TODO Auto-generated constructor stub
        }

    public  float customScore(int doc, float subQueryScore,float valSrcScores[]){

     try {

         subQueryScore+=4; \\ I only added this for testing , 
     } catch(Exception e) { \\ I want to add a value that is stored in a field of a document
         e.printStackTrace();
            }
    return subQueryScore;
             }
    }

class CustomizedScoreQuery extends CustomScoreQuery{


public CustomizedScoreQuery(Query subQuery,IndexReader ireader) {
        super(subQuery);
        // TODO Auto-generated constructor stub
    }
public CustomizedScoreProvider getCustomScoreProvider (LeafReaderContext reader){
    CustomizedScoreProvider i=new CustomizedScoreProvider(reader);
     return (i);
}
}

Solution

  • Thank you , but I already solved the problem, with the index reader I searched for the file, then I extracted the value of the field I wanted to use.

    class CustomizedScoreProvider extends CustomScoreProvider {
    private LeafReaderContext context;
    public CustomizedScoreProvider(LeafReaderContext reader) {
            super(reader);
            this.context= reader;
            // TODO Auto-generated constructor stub
        }
    
    public  float customScore(int doc, float subQueryScore,float valSrcScores[]) throws IOException{
    
        Document Social=context.reader().document(doc);
         IndexableField i= Social.getField("soc");// the field I wanted to extract
         float k= (float)i.numericValue();
         subQueryScore+=k;
    
    return subQueryScore;
             }
    }