利用Lucene MoreLikeThis 实现“相关你可能感兴趣的”推荐栏

MoreLikeThis是Lucene的一个相似搜索组件。
用它可以很简单的实现“相似推荐”栏功能,如 用户浏览一本书,下方(或右侧)推荐用户 书名、作者或关键字 相似的其他书籍。

事例代码如下:

首先,列出所有书籍,然后逐一打印每一本书的“相似图书”列表


public class MoreLikeThis {
public static void main(String[] args) throws Throwable {
String indexDir = System.getProperty("index.dir");
FSDirectory directory = FSDirectory.open(new File(indexDir));
IndexReader reader = IndexReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader); // 为相似搜索准备的searcher
int numDocs = reader.maxDoc(); // 所有图书
MoreLikeThis mlt = new MoreLikeThis(reader); // 相似搜索组件登场
mlt.setFieldNames(new String[] { "title", "author" }); // 找“标题”和“作者”相似的
mlt.setMinTermFreq(1); // 默认值是2,建议自己做限制,否则可能查不出结果
mlt.setMinDocFreq(1); // 默认值是5,建议自己做限制,否则可能查不出结果
for (int docID = 0; docID < numDocs; docID++) {
System.out.println();
Document doc = reader.document(docID); // 逐一过所有图书
System.out.println(doc.get("title"));
Query query = mlt.like(docID); // 准备相似搜索了
System.out.println(" query=" + query);
TopDocs similarDocs = searcher.search(query, 10); // 开搜,做多10个结果
if (similarDocs.totalHits == 0)
System.out.println(" None like this"); // 只要结果不为空,就按这个打印出来
for (int i = 0; i < similarDocs.scoreDocs.length; i++) {
if (similarDocs.scoreDocs[i].doc != docID) { // 记着把自己排除掉哦
doc = reader.document(similarDocs.scoreDocs[i].doc);
System.out.println(" -> " + doc.getField("title").stringValue());
}
}
}
searcher.close();
reader.close();
directory.close();
}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值