Lucene入门案例
程序员文章站
2022-07-12 23:31:58
...
Lucene入门案例 - 1
- 引入相关jar包
- commons-io-2.6.jar
- lucene-analyzers-common-7.4.0.jar
- lucene-core-7.4.0.jar
- 创建class
public class LuceneFirst {
@Test
public void createIndex() throws Exception {
// Directory directory = new RAMDirectory();
Directory directory = FSDirectory.open(new File("E:\\Desktop\\Director").toPath());
IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig());
File dir = new File("E:\\Desktop\\learnway\\lucene\\02.参考资料\\searchsource");
File[] files = dir.listFiles();
for (File file : files) {
String fileName = file.getName();
String filePath = file.getPath();
String fileContext = FileUtils.readFileToString(file, "UTF-8");
long fileSize = FileUtils.sizeOf(file);
Field fieldName = new TextField("name", fileName, Field.Store.YES);
Field fieldPat = new TextField("path", filePath, Field.Store.YES);
Field fieldContext = new TextField("context", fileContext, Field.Store.YES);
Field fieldSize = new TextField("size", fileSize+"", Field.Store.YES);
Document document = new Document();
document.add(fieldContext);
document.add(fieldName);
document.add(fieldPat);
document.add(fieldSize);
indexWriter.addDocument(document);
}
indexWriter.close();
}
}
- 使用luke查看生成的index文档
4.编写一个读取index文档的方法
@Test
public void searchIndex()throws Exception {
Directory directory = FSDirectory.open(new File("E:\\Desktop\\Director").toPath());
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Query query = new TermQuery(new Term("context", "spring"));
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("查询总记录数:"+topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
int docId = scoreDoc.doc;
Document document = indexSearcher.doc(docId);
System.out.println(document.get("name"));
System.out.println(document.get("path"));
System.out.println(document.get("size"));
// System.out.println(document.get("context"));
System.out.println("----------------");
}
indexReader.close();
}
上一篇: CSS3 3D相册
下一篇: 小菜鸡刷CTF(二)