Lucene相关度排序的调整

Lucene相关度排序的调整
2007-06-28 15:40

Lucene的搜索结果默认按相关度排序,这个相关度排序是基于内部的Score和DocID,Score又基于关键词的内部评分和做索引时的boost。默认Score高的排前面,如果Score一样,再按索引顺序,先索引的排前面。那么有人问了,如果我要先索引的排后面怎么办呢?隐士研究了源码后发现这是相当简单的事情。以下代码基于Lucene 2.0。

看Sort的默认构造函数,相关度就是SortField.FIELD_SCORE和SortField.FIELD_DOC的组合。

java 代码
  1. /**
  2. * Sorts by computed relevance. This is the same sort criteria as calling
  3. * {@link Searcher#search(Query) Searcher#search()}without a sort criteria,
  4. * only with slightly more overhead.
  5. */  
  6. public Sort() {   
  7.   this(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC });   
  8. }  

那么该如何构造我们需要的SortField呢?请看SortField的一个构造函数,有一个参数reverse可供我们调整结果集的顺序。

java 代码
  1. /** Creates a sort, possibly in reverse, by terms in the given field with the
  2.     * type of term values explicitly given.
  3.     * @param field   Name of field to sort by.   Can be null if
  4.     *               type is SCORE or DOC.
  5.     * @param type    Type of values in the terms.
  6.     * @param reverse True if natural order should be reversed.
  7.     */  
  8.   public SortField (String field, int type, boolean reverse) {   
  9.     this.field = (field != null) ? field.intern() : field;   
  10.     this.type = type;   
  11.     this.reverse = reverse;   
  12.    }  

由此可见,只要构造一个SortField[]就可以实现我们要的功能,请看:

java 代码
  1. // 评分降序,评分一样时后索引的排前面   
  2. new SortField[] { SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true) }   
  3.   
  4. // 评分升序,评分一样时后索引的排前面,呵呵,此为最不相关的排前面,挺有趣的   
  5. new SortField[] { new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true) }  

呵呵,只要将此SortField[]作为参数传入Sort的构造函数得到Sort的一个instance,将此instance传入searcher.search(query, sort)即可得到了期望的结果。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值