1 创建索引
- /**
- * 建立索引
- */
- public void index(){
- IndexWriter writer=null;
- try {
- //1. 创建 Directory
- //Directory directory=new RAMDirectory();// 建立在内存中
- Directory directory=FSDirectory.open(new File("D:/lucene/lucene01"));// 创建在硬盘上
- //2. 创建 IndexWrite
- IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_35,new StandardAnalyzer(Version.LUCENE_35));
- writer=new IndexWriter(directory, iwc);
- //3. 创建 Document 对象
- Document doc=null;
- //4. 为 Document 添加 Field
- File f=new File("D:/lucene/example");
- for (File file:f.listFiles()) {
- doc=new Document();
- doc.add(new Field("content",new FileReader(file)));
- doc.add(new Field("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
- doc.add(new Field("path",file.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
- //5. 通过 Index Writer 添加文档到索引中
- writer.addDocument(doc);
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(writer!=null){
- try {
- writer.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
2 搜索
- /***
- * 搜索
- */
- public void searcher(){
- try {
- //1. 创建 Directory
- Directory directory=FSDirectory.open(new File("D:/lucene/lucene01"));// 创建在硬盘上
- //2. 创建 IndexReader
- IndexReader reader=IndexReader.open(directory);
- //3. 根据 IndexReader 创建 IndexSearcher
- IndexSearcher searcher=new IndexSearcher(reader);
- //4. 创建搜索的 Query
- // 创建 parser 来确定要搜索文件的内容, 第二个参数表示搜索的域
- QueryParser parser=new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35));
- // 创建 query, 表示搜索域为 content 中包含 Java 的文档
- Query query=parser.parse("migrate");
- //5. 根据 searcher 搜索并且返回 TopDocs
- //10 搜索条数
- TopDocs tds=searcher.search(query, 10);
- //6. 根据 TopDocs 获取 ScoreDoc 对象
- ScoreDoc[] sds= tds.scoreDocs;
- for (ScoreDoc sd : sds) {
- //7. 根据 searcher 和 ScoreDoc 对象获取具体的 document 对象
- Document d=searcher.doc(sd.doc);
- //8. 根据 Document 对象获取需要的值
- System.out.println(d.get("filename")+"["+d.get("path")+"]");
- }
- //9. 关闭 reader
- reader.close();
- } catch (CorruptIndexException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
3Junit 测试
- @Test
- public void testIndex(){
- HelloLucene hl=new HelloLucene();
- hl.index();
- }
- @Test
- public void testSearch(){
- HelloLucene hl=new HelloLucene();
- hl.searcher();
- }
来源: http://www.bubuko.com/infodetail-2502870.html