Lucene 时间排序
在Lucene4.6中,想要实现搜索结果按照时间倒序的效果:如果两个文档得分相同,那么就按照发布时间倒序排列;否则就按照分数排列。这种效果在Lucene4.6中实现起来极其简单,直接利用search接口的Sort参数即可达成,完全不需要像某些人说的重写Similarity那么麻烦。三两行代码的事情,体现了Make it simple, stupid的精髓。
Sort sort =
new
Sort(
new
SortField(
"text"
, SortField.Type.SCORE),
new
SortField(
"date"
, SortField.Type.INT,
true
));
TopDocs topDocs = isearcher.search(query,
5
, sort);
System.out.println(
"命中:"
+ topDocs.totalHits);
//输出结果
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for
(
int
i =
0
; i < Math.min(
5
, scoreDocs.length); i++)
{
Document targetDoc = isearcher.doc(scoreDocs[i].doc);
System.out.print(targetDoc.getField(fieldName).stringValue());
System.out.print(
" , "
+ targetDoc.getField(
"date"
).numericValue());
System.out.println(
" , "
+ scoreDocs[i].score);
}
我们看到“2006年光棍节攻略”因为时间比较新,并且相关性高,就排在了第一。“2005年光棍节攻略”相关度相同,因为时间旧就排在后面一点,而干扰文档“游戏攻略”即使时间最新,因为不相关的原因排在最后面。这种效果正好是我想要的,极大提升了用户体验。
Please read full article from Lucene 时间排序
No comments:
Post a Comment