【发布时间】:2019-11-04 21:23:33
【问题描述】:
我目前正在开发一个使用 Lucene 8 的小型大学搜索引擎。我之前已经构建了它,但没有对文档应用任何权重。
我现在需要添加文档的 PageRanks 作为每个文档的权重,并且我已经计算了 PageRank 值。如何在 Lucene 8 中为 Document 对象(不是查询词)添加权重?我在网上查找了许多解决方案,但它们仅适用于旧版本的 Lucene。 Example source
这是我的(更新)代码,它从File 对象生成Document 对象:
public static Document getDocument(File f) throws FileNotFoundException, IOException {
Document d = new Document();
//adding a field
FieldType contentType = new FieldType();
contentType.setStored(true);
contentType.setTokenized(true);
contentType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
contentType.setStoreTermVectors(true);
String fileContents = String.join(" ", Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));
d.add(new Field("content", fileContents, contentType));
//adding other fields, then...
//the boost coefficient (updated):
double coef = 1.0 + ranks.get(path);
d.add(new DoubleDocValuesField("boost", coef));
return d;
}
我当前方法的问题是我需要一个 CustomScoreQuery 对象来搜索文档,但这在 Lucene 8 中不可用。此外,我不想在所有代码之后现在降级到 Lucene 7我用 Lucene 8 写的。
编辑:
经过一些(长时间的)研究,我在每个包含 boost 的文档中添加了一个 DoubleDocValuesField(请参阅上面的更新代码),并按照 @EricLavault 的建议使用 FunctionScoreQuery 进行搜索。但是,现在我的所有文档的得分都与其提升完全一致,无论查询如何!我该如何解决这个问题?这是我的搜索功能:
public static TopDocs search(String query, IndexSearcher searcher, String outputFile) {
try {
Query q_temp = buildQuery(query); //the original query, was working fine alone
Query q = new FunctionScoreQuery(q_temp, DoubleValuesSource.fromDoubleField("boost")); //the new query
q = q.rewrite(DirectoryReader.open(bm25IndexDir));
TopDocs results = searcher.search(q, 10);
ScoreDoc[] filterScoreDosArray = results.scoreDocs;
for (int i = 0; i < filterScoreDosArray.length; ++i) {
int docId = filterScoreDosArray[i].doc;
Document d = searcher.doc(docId);
//here, when printing, I see that the document's score is the same as its "boost" value. WHY??
System.out.println((i + 1) + ". " + d.get("path")+" Score: "+ filterScoreDosArray[i].score);
}
return results;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
//function that builds the query, working fine
public static Query buildQuery(String query) {
try {
PhraseQuery.Builder builder = new PhraseQuery.Builder();
TokenStream tokenStream = new EnglishAnalyzer().tokenStream("content", query);
tokenStream.reset();
while (tokenStream.incrementToken()) {
CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
builder.add(new Term("content", charTermAttribute.toString()));
}
tokenStream.end(); tokenStream.close();
builder.setSlop(1000);
PhraseQuery q = builder.build();
return q;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
【问题讨论】:
-
谢谢卢卡·基贝尔。我刚刚问了一个新问题:stackoverflow.com/questions/71334341/…