lucene的一简单例子

1.引入lucene包,用到了Junit,包搞进来就可以了
2.先跑建立索引文件的单元测试,有了索引才能查询嘛,然后在跑下面的检索数据方法
3.目录根据自己需要更改哦

private final String indexPath = "E:/lucene";
private final String searchPath = "E:/123";

@Test
/**
* 建立索引文件
*/
public void createIndexFiles() throws Exception {
Directory d = new SimpleFSDirectory(new File(indexPath));// 创建索引的目录
IndexWriter iw = new IndexWriter(d, new StandardAnalyzer(
Version.LUCENE_29), true, MaxFieldLength.UNLIMITED);
File f = new File(searchPath);// 要检索的目录
addToWriter(f, iw);
iw.close();
}

/**
* 递归调用检索文件夹
*
* @param f
* @param iw
* @throws Exception
*/
public void addToWriter(File f, IndexWriter iw) throws Exception {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++)
addToWriter(files[i], iw);
} else if (f.getName().endsWith(".html")
|| f.getName().endsWith(".txt")) {
Document doc = new Document();
/**
* Store.YES 存储 Index.NO 词法分析器不在解析此Field
*/
doc.add(new Field("title", f.getName(), Store.YES, Index.NO));
doc.add(new Field("content", new FileReader(f)));
iw.addDocument(doc);
}
}

/**
* 检索数据
*
* @throws Exception
*/
@Test
public void search() throws Exception {
Directory d = new SimpleFSDirectory(new File(indexPath));
IndexSearcher search = new IndexSearcher(d, true);
QueryParser qp = new QueryParser(Version.LUCENE_29, "content",
new StandardAnalyzer(Version.LUCENE_29));
/**
* 检索关键字,其实Google地址栏里就是输入的这里哦,当然Google肯定是自己公司的搜索技术,这里只是举例
*/
Query query = qp.parse("content");
TopDocs tp = search.search(query, 100);
System.out.println("检索到:" + tp.totalHits + "个文件包含此数据");
for (int i = 0; i < tp.scoreDocs.length; i++) {
int num = tp.scoreDocs[i].doc;
Document doc = search.doc(num);
System.out.println("文件名为:" + doc.get("title"));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值