public class HelloLucene {
/**
* 建立索引
*/
public void index() {
IndexWriter writer = null;
try {
//1.创建Directory
Directory directory = FSDirectory.open(new File("e:/lucene/index01"));
//2.创建indexWriter
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_2, new StandardAnalyzer());
writer = new IndexWriter(directory, config);
//3.创建document对象
Document doc = null;
//4.位document添加field
File files = new File("e:/lucene/example");
for (File file: files.listFiles()) {
doc = new Document();
doc.add(new Field("content", new FileReader(file),TextField.TYPE_NOT_STORED));
doc.add(new Field("path", file.getAbsolutePath(), TextField.TYPE_STORED));
doc.add(new Field("fileName", file.getName(), TextField.TYPE_STORED));
//通过indexWriter添加文档到索引中
writer.addDocument(doc);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void search() {
try {
//1.创建directory
Directory directory = FSDirectory.open(new File("e:/lucene/index01"));
//2.创建indexReader
IndexReader reader = DirectoryReader.open(directory);
//3.根据indexReader创建indexSerach
IndexSearcher search = new IndexSearcher(reader);
//4.创建搜索的query
//创建query来确定搜索文件的内容贴,第一个参数为搜索的域
QueryParser parse = new QueryParser("content", new StandardAnalyzer());
//创建query表示搜索域content中包含Java的文档
Query query = parse.parse("java");
//5.根据search搜索并返回topDocs
TopDocs tds = search.search(query, 10);
//6.根据topDocs获取ScoreDoc对象
ScoreDoc[] docs = tds.scoreDocs;
for (ScoreDoc sd : docs) {
//7.根据search和ScoreDoc对像获取具体的document,sd.doc位为档的id
Document document = search.doc(sd.doc);
//8.根据document对象获取相应的值
System.out.println(document.get("fileName")+"["+document.get("path")+"]");
//9.关闭Reader
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new HelloLucene().index();
new HelloLucene().search();
}
}
lucene入门实例
最新推荐文章于 2018-10-18 14:28:00 发布