我的第一个 lucene程序
package lucene;
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.classic.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 static void main(String[] args) {
new HelloLucene().createIndex();
new HelloLucene().search();
}
/**
* 创建索引
*/
public void createIndex() {
IndexWriter indexWriter = null;
try {
// 1. 创建 Directory (索引存放位置)
//Directory dir = new RAMDirectory();
Directory dir = FSDirectory.open(new File("e:/test/index"));
// 2. 创建IndexWriter 写索引
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_9, new StandardAnalyzer(Version.LUCENE_4_9));
indexWriter = new IndexWriter(dir, iwc);
// 3. 创建Document 对象 field
Document document;
File file = new File("e:/test/example");
for (File f : file.listFiles()) {
document = new Document();
// 4. 为Documen添加field
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));
// 5. 通过IndexWriter 添加文档到索引中
indexWriter.addDocument(document);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (indexWriter != null) {
try {
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void search() {
IndexReader indexReader = null;
try {
// 1. 创建 Directory
Directory dir = FSDirectory.open(new File("e:/test/index"));
// 2. 创建 IndexReader
indexReader = IndexReader.open(dir);
// 3. 创建 IndexSearch
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
// 4. 创建搜索的Query
// 创建parse确定搜索的内容,第二个参数为搜索的fiel
QueryParser queryParser = new QueryParser(Version.LUCENE_4_9, "content", new StandardAnalyzer(Version.LUCENE_4_9));
// 创建Query,表示搜索域中的内容
Query query = queryParser.parse("Brook love amy");
// 5. 搜索并返回 TopDocs
TopDocs topDocs = indexSearcher.search(query, 10);
// 6. 根据topDocs 获得 scoreDocs
ScoreDoc[] socreDocs = topDocs.scoreDocs;
for (ScoreDoc doc : socreDocs) {
// 获取Document对象
Document document = indexSearcher.doc(doc.doc);
// 根据Document对象获取需要的值
System.out.println(document.get("filePath"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (indexReader != null) {
try {
indexReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}