Lucene 自定义评分

Lucene Custom Scoring

我想制作一个 lucene 自定义评分函数,它采用存储在文档中的值并将其添加到最终分数。

我已经想出了如何向评分函数添加一个值,但是我无法将文档的存储值获取到该方法中。

 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);
}
}

如果我明白你想做什么,那么你需要打开一个文件(你的"document")并解析一个浮点数。

此处解释了如何以几种不同的方式打开文件并获取其内容: How to open a txt file and read numbers in java

请注意,您需要 Float.parseFloat(String s) 而不是 Integer.parseInt(String s)

谢谢,不过我已经解决了问题,用索引 reader 我搜索了文件,然后提取了我想使用的字段的值。

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;
         }
}