jar包
java类
public class LuceneText {
@Test
public void testLucene() throws Exception {
File file = new File("E:\\java视频\\17luncene&solr\\lucene");
if (!file.exists()) {
return ;
}
Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
Version matchVersion = Version.LATEST;
Analyzer analyzer = new StandardAnalyzer();//官方推荐
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(matchVersion, analyzer );
//第一步创建java工程并且导入jar
//第二步创建一个inedewriter对象
IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
//1.指定索引库的存放位置Driectory
//2.指定一个分析器对文档进行分析
//第三步创建document对象
Document document = new Document();
//第四步创建field对象 将field对象添加到document
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
//文件名称
String file_name = file2.getName();
Field field_name = new TextField("file_name", file_name, Store.YES);
//文件大小
long sizeOf = FileUtils.sizeOf(file2);
Field field_size = new LongField("sizeOf", sizeOf, Store.YES);
//文件路径
String file_path = file2.getPath();
Field field_path = new StoredField("file_path", file_name);
//文件内容
String field_content = FileUtils.readFileToString(file2);
Field field_field_content = new TextField("field_content", field_content,Store.YES);
document.add(field_name);
document.add(field_size);
document.add(field_path);
document.add(field_field_content);
//第五步使用indexwriter对象将document对象写入索引,此过程进行索引创建,并将document对象写入索引库
indexWriter.addDocument(document);
}
//第六步关闭indexwriter对象
indexWriter.close();
}
@Test
public void queryLucene() throws Exception {
System.err.println("执行查询");
//第一步创建directory对象,也就是索引位置
Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
//第二部创建indexReader对象,需要指定directory对象
IndexReader indexReader = DirectoryReader.open(directory);
//第三部创建一个indexsearcher对象 ,需要指定indexreader对象
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//第四部创建一个termQuery对象 需要指定indexreader对象
Query query = new TermQuery(new Term("file_name","那时"));
//第五步执行查询
TopDocs topDocs = indexSearcher.search(query, 5);
//第六步返回查询结果
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//第七步关闭indexreader对象
for (ScoreDoc scoreDoc : scoreDocs) {
//获取doc对象
int doc = scoreDoc.doc;
//用获取的doc查文档
Document document = indexSearcher.doc(doc);
System.out.println(document.get("file_name"));
System.out.println(document.get("sizeOf"));
System.out.println(document.get("file_path"));
System.out.println(document.get("field_content"));
System.out.println("------------------------------------");
}
indexReader.close();
}