【问题标题】:How to use a CustomScoreQuery in Lucene 7.x如何在 Lucene 7.x 中使用 CustomScoreQuery
【发布时间】:2018-01-22 14:26:27
【问题描述】:

我对 Lucene 比较陌生,我想实现自己的 CustomScoreQuery,因为我的大学需要它。

我使用 Lucene 演示作为起点来索引文件夹中的所有文档,并希望使用我自己的算法对它们进行评分。

这里是演示源代码的链接。

https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/SearchFiles.html

我正在检查 Luke: Lucene Toolbox Project 以查看我的索引是否符合预期。我的问题是访问它。

package CustomModul;
import java.io.IOException;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Terms;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.Query;

public class CountingQuery extends CustomScoreQuery {

public CountingQuery(Query subQuery) {
    super(subQuery);
}


public class CountingQueryScoreProvider extends CustomScoreProvider {

    String _field;

    public CountingQueryScoreProvider(String field, LeafReaderContext context) {
        super(context);
        _field = field;
    }

    public float customScore(int doc, float subQueryScore, float valSrcScores[]) throws IOException {           
        IndexReader r = context.reader();

        //getTermVector returns Null
        Terms vec = r.getTermVector(doc, _field);

        //*TO-DO* Algorithm

        return (float)(1.0f);       
    }   
}

protected CustomScoreProvider getCustomScoreProvider(
        LeafReaderContext context) throws IOException {
    return new CountingQueryScoreProvider("contents", context);
}

}

在我的 customScore 函数中,我访问了大多数教程中描述的索引。我应该使用 getTermVector 访问索引,但它返回 NULL。 在其他帖子中,我读到这可能是由于内容是在 Lucene Demo IndexFiles 中声明的 TextField 引起的。

在尝试了很多不同的方法后,我得出的结论是我需要帮助,我就在这里。

我现在的问题是我是否需要调整索引过程(如何?)或者除了 getTermVector 之外还有其他方法可以访问 ScoreProvider 中的索引吗?

【问题讨论】:

    标签: java lucene


    【解决方案1】:

    我能够自己解决问题,如果有人发现此问题正在寻找答案,我想分享我的解决方案。

    问题确实是由内容是 TextField 引起的 https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html

    为了解决这个问题,一个人必须构建他自己的字段,我确实将所述 IndexFile 中的第 193 行替换为

    FieldType myFieldType = new FieldType(TextField.TYPE_STORED);
    myFieldType.setOmitNorms(true);
    myFieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
    myFieldType.setStored(false);
    myFieldType.setStoreTermVectors(true);  
    myFieldType.setTokenized(true);
    myFieldType.freeze();
    Field myField = new Field("contents",
                    new BufferedReader(new InputStreamReader(stream, 
                    StandardCharsets.UTF_8)),
                    myFieldType);
    doc.add(myField);
    

    这允许在 customScore 函数中使用 getTermVector。希望这对将来的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 2016-01-31
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多