Lucene 入门实例

项目结构


constans.java 是常量类

LuceneIndex.java 建立索引类

LuceneSearch.java 搜索类

数据文件:



[java]  view plain copy
  1. package com.xin;  
  2.   
  3. public class Constants {   
  4.     public final static String INDEX_FILE_PATH = "e:\\lucene\\test"//索引的文件的存放路径   
  5.     public final static String INDEX_STORE_PATH = "e:\\lucene\\index"//索引的存放位置   
  6. }   

[java]  view plain copy
  1. package com.xin;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.Reader;  
  8. import java.util.Date;  
  9.   
  10. import org.apache.lucene.analysis.Analyzer;  
  11. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  12. import org.apache.lucene.document.Document;  
  13. import org.apache.lucene.document.Field;  
  14. import org.apache.lucene.document.StringField;  
  15. import org.apache.lucene.document.TextField;  
  16. import org.apache.lucene.index.IndexWriter;  
  17. import org.apache.lucene.index.IndexWriterConfig;  
  18. import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
  19. import org.apache.lucene.store.Directory;  
  20. import org.apache.lucene.store.FSDirectory;  
  21. import org.apache.lucene.util.Version;  
  22. /** 
  23.  * @author chongxin 
  24.  * @since 2013/6/19 
  25.  * @version Lucene 4.3.1 
  26.  * */  
  27. public class LuceneIndex {  
  28.     // 索引器  
  29.     private IndexWriter writer = null;  
  30.     public LuceneIndex() {  
  31.         try {  
  32.             //索引文件的保存位置  
  33.             Directory dir = FSDirectory.open(new File(Constants.INDEX_STORE_PATH));  
  34.             //分析器  
  35.             Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);  
  36.             //配置类  
  37.             IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,analyzer);  
  38.             iwc.setOpenMode(OpenMode.CREATE);//创建模式 OpenMode.CREATE_OR_APPEND 添加模式  
  39.               
  40.             writer = new IndexWriter(dir, iwc);  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.   
  46.     // 将要建立索引的文件构造成一个Document对象,并添加一个域"content"  
  47.     private Document getDocument(File f) throws Exception {  
  48.         Document doc = new Document();  
  49.   
  50.         FileInputStream is = new FileInputStream(f);  
  51.         Reader reader = new BufferedReader(new InputStreamReader(is));  
  52.         //字符串 StringField LongField TextField  
  53.         Field pathField = new StringField("path", f.getAbsolutePath(),Field.Store.YES);  
  54.         Field contenField = new TextField("contents", reader);  
  55.         //添加字段  
  56.         doc.add(contenField);  
  57.         doc.add(pathField);  
  58.         return doc;  
  59.     }  
  60.   
  61.     public void writeToIndex() throws Exception {  
  62.         File folder = new File(Constants.INDEX_FILE_PATH);  
  63.           
  64.         if (folder.isDirectory()) {  
  65.             String[] files = folder.list();  
  66.             for (int i = 0; i < files.length; i++) {  
  67.                 File file = new File(folder, files[i]);  
  68.                 Document doc = getDocument(file);  
  69.                 System.out.println("正在建立索引 : " + file + "");  
  70.                 writer.addDocument(doc);  
  71.             }  
  72.         }  
  73.     }  
  74.   
  75.     public void close() throws Exception {  
  76.         writer.close();  
  77.     }  
  78.   
  79.     public static void main(String[] args) throws Exception {  
  80.         // 声明一个对象  
  81.         LuceneIndex indexer = new LuceneIndex();  
  82.         // 建立索引  
  83.         Date start = new Date();  
  84.         indexer.writeToIndex();  
  85.         Date end = new Date();  
  86.   
  87.         System.out.println("建立索引用时" + (end.getTime() - start.getTime()) + "毫秒");  
  88.   
  89.         indexer.close();  
  90.     }  
  91. }  
执行结果:
[java]  view plain copy
  1. 正在建立索引 : e:\lucene\test\a.txt  
  2. 正在建立索引 : e:\lucene\test\b.txt  
  3. 正在建立索引 : e:\lucene\test\c.txt  
  4. 正在建立索引 : e:\lucene\test\d.txt  
  5. 建立索引用时109毫秒  

生成的索引文件:


查找:

[java]  view plain copy
  1. package com.xin;  
  2.   
  3. import java.io.File;  
  4. import java.util.Date;  
  5.   
  6. import org.apache.lucene.analysis.Analyzer;  
  7. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  8. import org.apache.lucene.document.Document;  
  9. import org.apache.lucene.index.DirectoryReader;  
  10. import org.apache.lucene.index.IndexReader;  
  11. import org.apache.lucene.queryparser.classic.QueryParser;  
  12. import org.apache.lucene.search.IndexSearcher;  
  13. import org.apache.lucene.search.Query;  
  14. import org.apache.lucene.search.ScoreDoc;  
  15. import org.apache.lucene.search.TopDocs;  
  16. import org.apache.lucene.store.FSDirectory;  
  17. import org.apache.lucene.util.Version;  
  18.   
  19. /** 
  20.  * @author chongxin 
  21.  * @since 2013/6/19 
  22.  * @version Lucene 4.3.1 
  23.  * */  
  24. public class LuceneSearch {  
  25.     // 声明一个IndexSearcher对象  
  26.     private IndexSearcher searcher = null;  
  27.     // 声明一个Query对象  
  28.     private Query query = null;  
  29.     private String field = "contents";  
  30.   
  31.     public LuceneSearch() {  
  32.         try {  
  33.             IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(Constants.INDEX_STORE_PATH)));  
  34.             searcher = new IndexSearcher(reader);  
  35.         } catch (Exception e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.     }  
  39.     //返回查询结果   
  40.     public final TopDocs search(String keyword) {  
  41.         System.out.println("正在检索关键字 : " + keyword);  
  42.         try {  
  43.             Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);  
  44.             QueryParser parser = new QueryParser(Version.LUCENE_40, field,analyzer);  
  45.             // 将关键字包装成Query对象  
  46.             query = parser.parse(keyword);  
  47.             Date start = new Date();  
  48.             TopDocs results = searcher.search(query, 5 * 2);  
  49.             Date end = new Date();  
  50.             System.out.println("检索完成,用时" + (end.getTime() - start.getTime())  
  51.                     + "毫秒");  
  52.             return results;  
  53.         } catch (Exception e) {  
  54.             e.printStackTrace();  
  55.             return null;  
  56.         }  
  57.     }  
  58.       //打印结果  
  59.     public void printResult(TopDocs results) {  
  60.         ScoreDoc[] h = results.scoreDocs;  
  61.         if (h.length == 0) {  
  62.             System.out.println("对不起,没有找到您要的结果。");  
  63.         } else {  
  64.             for (int i = 0; i < h.length; i++) {  
  65.                 try {  
  66.                     Document doc = searcher.doc(h[i].doc);  
  67.                     System.out.print("这是第" + i + "个检索到的结果,文件名为:");  
  68.                     System.out.println(doc.get("path"));  
  69.                 } catch (Exception e) {  
  70.                     e.printStackTrace();  
  71.                 }  
  72.             }  
  73.         }  
  74.         System.out.println("--------------------------");  
  75.     }  
  76.   
  77.     public static void main(String[] args) throws Exception {  
  78.         LuceneSearch test = new LuceneSearch();  
  79.         TopDocs h = null;  
  80.         h = test.search("中国");  
  81.         test.printResult(h);  
  82.         h = test.search("人民");  
  83.         test.printResult(h);  
  84.         h = test.search("共和国");  
  85.         test.printResult(h);  
  86.     }  
  87.   
  88. }  


转载自:https://i-blog.csdnimg.cn/blog_migrate/4cb09753568262c6b9bcc475d67942f4.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值