lucene怎么实现按匹配度排序

我是鱼小小 2011-01-25 04:06:46
lucene 怎么实现按匹配度排序
查询语句为 “ ZLGJZ:北京 OR ZLGJZ:公司”

结果需要是含有‘北京’和‘公司’两个词的 数据排在前面,其他只含有‘北京’或‘公司’的数据排在其后。

希望高手能指点迷津帮帮小弟
...全文
706 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
Lucene的搜索结果默认按相关度排序,这个相关度排序是基于内部的Score和DocID,Score又基于关键词的内部评分和做索引时的boost。默认Score高的排前面,如果Score一样,再按索引顺序,先索引的排前面。那么有人问了,如果我要先索引的排后面怎么办呢?隐士研究了源码后发现这是相当简单的事情。以下代码基于Lucene 2.0。

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

java 代码
/**
* Sorts by computed relevance. This is the same sort criteria as calling
* {@link Searcher#search(Query) Searcher#search()}without a sort criteria,
* only with slightly more overhead.
*/
public Sort() {
this(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC });
}
那么该如何构造我们需要的SortField呢?请看SortField的一个构造函数,有一个参数reverse可供我们调整结果集的顺序。

java 代码
/** Creates a sort, possibly in reverse, by terms in the given field with the
* type of term values explicitly given.
* @param field Name of field to sort by. Can be <code>null</code> if
* <code>type</code> is SCORE or DOC.
* @param type Type of values in the terms.
* @param reverse True if natural order should be reversed.
*/
public SortField (String field, int type, boolean reverse) {
this.field = (field != null) ? field.intern() : field;
this.type = type;
this.reverse = reverse;
}
由此可见,只要构造一个SortField[]就可以实现我们要的功能,请看:

java 代码
// 评分降序,评分一样时后索引的排前面
new SortField[] { SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true) }

// 评分升序,评分一样时后索引的排前面,呵呵,此为最不相关的排前面,挺有趣的
new SortField[] { new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true) }
呵呵,只要将此SortField[]作为参数传入Sort的构造函数得到Sort的一个instance,将此instance传入searcher.search(query, sort)即可得到了期望的结果。

具体实例可参考隐士做的搜索站http://so.mdbchina.com。
zn85600301 2011-01-25
  • 打赏
  • 举报
回复
额 我知道按得分排序
这个得分 也很诡异 和文章的篇幅也有关

51,397

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧