Lucene 最新版代码使用实例之【搜索index】

根据之前创建的索引进行搜索。

	/**
	 * V Lucene 3.5
	 * 搜索索引
	 */
	public static void readIndex(){
		IndexSearcher indexSearch = null;
		try {
			//保存索引文件的地方  
			 Directory dir = new SimpleFSDirectory(new File(LUCENEDATA));
			 
			 /**
			  * indexSearch = new IndexSearcher(dir);<被弃用>
			  */
			 indexSearch = new IndexSearcher(IndexReader.open(dir));
			 
			 //创建QueryParser对象,第一个参数表示Lucene的版本,第二个表示搜索Field的字段,第三个表示搜索使用分词器  
			 QueryParser queryParser = new QueryParser(Version.LUCENE_35,  
			         "name", new StandardAnalyzer(Version.LUCENE_35));
			 
			 String key = "tESt.html";
			 //生成Query对象  
			 Query query = queryParser.parse(key);
			 
			 /**
			  * 搜索结果 TopDocs里面有scoreDocs[]数组,里面保存着索引值
			  * API: Finds the top n  hits for query
			  */
			 TopDocs hits = indexSearch.search(query, 10);
			 //hits.totalHits表示一共搜到多少个
			 System.out.println("共搜索到"+hits.totalHits+"个 '"+key+"'");
			 
			 //循环hits.scoreDocs数据,并使用indexSearch.doc方法把Document还原,再拿出对应的字段的值  
			 for (ScoreDoc sdoc : hits.scoreDocs) {  
			     Document doc = indexSearch.doc(sdoc.doc);  
			     System.out.println(doc.get("path"));              
			 }
			 indexSearch.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("There is no index files...");
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
输出结果:

共搜索到4个 'tESt.html'
F:\特效\artDialog\basic\_doc\highlight\test.html
F:\特效\artDialog\_doc\highlight\test.html
F:\特效\basic\_doc\highlight\test.html
F:\特效\zu\highlight\test.html


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值