开发搜索引擎初步(二)搜索(Lucene实现)

本文介绍如何利用已建立的索引文件进行基本搜索操作,包括构建搜索条件、执行搜索并输出搜索结果,以及计算搜索用时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

经过上一篇的经验,想必大家对建立索引应该没有什么问题了,下面我们就开始最简单的搜索,也就是对我们已经建立好的索引进行检索,废话不多说,下面看代码

package com.dreamers.search; import java.io.File; import java.io.IOException; import java.util.Date; import org.apache.lucene.document.Document; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; public class IndexSearch { private String INDEX_STORE_PATH = "d:\\LuceneDemo";//注意,此处的PATH为你的索引在磁盘中的存放位置 public void search(){ try{ Directory directory = FSDirectory.open(new File(INDEX_STORE_PATH));//建立库,导入索引 System.out.println("使用索引搜索"); IndexSearcher searcher = new IndexSearcher(directory);//初始化搜索的类,在Lucene中 Term t = new Term("publisher","历城二中");//构建搜索初始化元 Query q = new TermQuery(t); Date begin = new Date();//建立时间,以便显示搜索用时 ScoreDoc[] hits = searcher.search(q,null,1000).scoreDocs;//将搜索到的资源放入数组 System.out.println("共找到 " + hits.length + " 个文档符合条件"); for (int i = 0; i < hits.length; i++){ Document doc = new Document();//遍历资源 doc = searcher.doc(hits[i].doc); System.out.print("文件名为: "); System.out.print(doc.get("title")); System.out.print("."); System.out.println(doc.get("kind")); System.out.print("地址为 : "); System.out.println(doc.get("url")); System.out.print("描述: "); System.out.println(doc.get("describe")); System.out.print("scores is :"); System.out.println(hits[i].score); System.out.print("作者为:"); System.out.println(doc.get("author")); System.out.println("---------------------------------------------------"); } Date end = new Date(); long time = end.getTime()-begin.getTime(); System.out.print("搜索用时 " + time + "ms"); }catch(IOException x){ x.printStackTrace(); } } public static void main(String [] args){ IndexSearch search = new IndexSearch(); search.search();//测试 } }

通过这个程序,我们可以很简单的实现对自己的在磁盘上面建立的索引文件进行按照自己的想法进行索引,呵呵,下面的工作就是自己去实现了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值