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