刚学,直接上代码,记之~~
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class HelloLucene {
public void index() {
IndexWriter writer = null;
try {
// 创建Directory
// Directory directory = new RAMDirectory(); // 建立在内存中
Directory directory = FSDirectory.open(new File(
"E:/lucene_test/index01")); // 创建在硬盘中
// 创建IndexWriter
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,
new StandardAnalyzer(Version.LUCENE_35));
writer = new IndexWriter(directory, config);
// 创建Document
Document document = null;
// 为Document添加Field
File file = new File("E:/lucene_test/test");
File[] files = file.listFiles();
for (File f : files) {
document = new Document();
document.add(new Field("content", new FileReader(f))); // 将文件内容添加到索引域中
document.add(new Field("filename", f.getName(),
Field.Store.YES, Field.Index.NOT_ANALYZED)); // 添加文件名
document.add(new Field("filepath", f.getAbsolutePath(),
Field.Store.YES, Field.Index.NOT_ANALYZED));// 添加文件路径
// 通过IndexWriter添加Document到索引中
writer.addDocument(document);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 搜索
*/
public void searcher() {
IndexReader reader = null;
try {
// 创建Directory
Directory directory = FSDirectory.open(new File(
"E:/lucene_test/index01")); // 创建在硬盘中
// 创建IndexReader
reader = IndexReader.open(directory);
// 创建IndexSearcher
IndexSearcher indexSearcher = new IndexSearcher(reader);
// 创建QueryParser来确定搜索文件的内容, 其中第二个参数是搜索的域
QueryParser parser = new QueryParser(Version.LUCENE_35, "content",
new StandardAnalyzer(Version.LUCENE_35));
// 创建Query,表示搜索域为content中包含java的文档
Query query = parser.parse("loadAuthority"); // 要搜索的关键字loadAuthority
// 根据searcher搜索并返回TopDocs
TopDocs topDocs = indexSearcher.search(query, 10); // 显示10条内容
// 根据TopDocs获取ScoreDoc对象
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
// 根据searcher和ScoreDoc对象获取具体的Document对象
Document document = indexSearcher.doc(scoreDoc.doc);
System.out.println("filename = " + document.get("filename"));
System.out.println("filepath = " + document.get("filepath"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}