lucene 结合paoding分词器

首先是建立索引的类文件:

 

 

Java代码   收藏代码
  1. package com.jereh.lucene;  
  2.   
  3. import java.io.*;  
  4. import java.util.Date;  
  5. import net.paoding.analysis.analyzer.PaodingAnalyzer;  
  6. import org.apache.lucene.document.DateTools;  
  7. import org.apache.lucene.document.Document;  
  8. import org.apache.lucene.document.Field;  
  9. import org.apache.lucene.index.IndexWriter;  
  10. import org.apache.lucene.store.Directory;  
  11. import org.apache.lucene.store.FSDirectory;  
  12.   
  13. /** 
  14.  * 创建索引 Lucene 3.0+ 
  15.  *  
  16.  * @author Administrator 
  17.  *  
  18.  */  
  19. public class Indexer {  
  20.   
  21.     /** 
  22.      * @param args 
  23.      * @throws IOException 
  24.      */  
  25.     public static void index(String dateDir, String indexDir)  
  26.             throws IOException {  
  27.         IndexWriter indexWriter = null;  
  28.         // 创建Directory对象  
  29.         Directory dir = FSDirectory.getDirectory(new File(indexDir));   
  30.         // 创建IndexWriter对象,第一个参数是Directory,第二个是分词器,第三个表示是否是创建,如果为false为在此基础上面修改,第四表示表示分词的最大值,比如说new  
  31.         // MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED  
  32.         indexWriter = new IndexWriter(dir,new PaodingAnalyzer());  
  33.         File[] files = new File(dateDir).listFiles();  
  34.         for (int i = 0; i < files.length; i++) {  
  35.             Document doc = new Document();  
  36.             // 创建Field对象,并放入doc对象中  
  37.             doc.add(new Field("contents", readContents(files[i], "UTF-8"),  
  38.                     Field.Store.YES, Field.Index.UN_TOKENIZED));  
  39.             doc.add(new Field("filename", files[i].getName(), Field.Store.YES,  
  40.                     Field.Index.TOKENIZED));  
  41.             doc.add(new Field("indexDate", DateTools.dateToString(new Date(),  
  42.                     DateTools.Resolution.DAY), Field.Store.YES,  
  43.                     Field.Index.TOKENIZED));  
  44.             // 写入IndexWriter  
  45.             indexWriter.addDocument(doc);  
  46.         }  
  47.         // 查看IndexWriter里面有多少个索引  
  48.         System.out.println("numDocs:" + indexWriter.numRamDocs());  
  49.         indexWriter.optimize();  
  50.         indexWriter.close();  
  51.     }  
  52.   
  53.     public static String readContents(File file, String charset)  
  54.             throws IOException {  
  55.         BufferedReader reader = new BufferedReader(new InputStreamReader(  
  56.                 new FileInputStream(file), charset));  
  57.         String line = new String();  
  58.         String temp = new String();  
  59.   
  60.         while ((line = reader.readLine()) != null) {  
  61.             temp += line;  
  62.         }  
  63.         reader.close();  
  64.         return temp;  
  65.     }  
  66.   
  67. }  

 

 其次是进行搜索的类:

 

Java代码   收藏代码
  1. package com.jereh.lucene;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import net.paoding.analysis.analyzer.PaodingAnalyzer;  
  6. import org.apache.lucene.document.Document;  
  7. import org.apache.lucene.queryParser.ParseException;  
  8. import org.apache.lucene.queryParser.QueryParser;  
  9. import org.apache.lucene.search.Hits;  
  10. import org.apache.lucene.search.IndexSearcher;  
  11. import org.apache.lucene.search.Query;  
  12. import org.apache.lucene.store.Directory;  
  13. import org.apache.lucene.store.FSDirectory;  
  14. /** 
  15.  * 搜索索引 Lucene 3.0+ 
  16.  *  
  17.  * @author Administrator 
  18.  *  
  19.  */  
  20. public class Searcher {  
  21.   
  22.     public static void search(String indexDir) throws IOException,  
  23.             ParseException {  
  24.         Directory dir = FSDirectory.getDirectory(new File(indexDir));  
  25.         // 创建 IndexSearcher对象,相比IndexWriter对象,这个参数就要提供一个索引的目录就行了  
  26.         IndexSearcher indexSearch = new IndexSearcher(dir);  
  27.         // 创建QueryParser对象,第一个参数表示Lucene的版本,第二个表示搜索Field的字段,第三个表示搜索使用分词器  
  28.         QueryParser queryParser = new QueryParser("filename",new PaodingAnalyzer());  
  29.         // 生成Query对象  
  30.         Query query = queryParser.parse("滑移装载机");  
  31.         // 搜索结果 TopDocs里面有scoreDocs[]数组,里面保存着索引值  
  32.         //TopDocs hits = indexSearch.search(query, 10);  
  33.         Hits hits = indexSearch.search(query);  
  34.         // hits.totalHits表示一共搜到多少个  
  35.         System.out.println("找到了" + hits.length() + "个");  
  36.         // 循环hits.scoreDocs数据,并使用indexSearch.doc方法把Document还原,再拿出对应的字段的值  
  37.         Document doc = null;  
  38.         for(int i=0;i<hits.length();i++){  
  39.             doc = hits.doc(i);  
  40.             System.out.print(doc.get("filename"));  
  41.         }  
  42.         indexSearch.close();  
  43.     }  
  44. }  

 

最后是运行的类:

 

Java代码   收藏代码
  1. package com.jereh.lucene;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import net.paoding.analysis.analyzer.PaodingAnalyzer;  
  7. import net.paoding.analysis.examples.gettingstarted.BoldFormatter;  
  8. import org.apache.lucene.analysis.Analyzer;  
  9. import org.apache.lucene.document.Document;  
  10. import org.apache.lucene.document.Field;  
  11. import org.apache.lucene.index.IndexReader;  
  12. import org.apache.lucene.index.IndexWriter;  
  13. import org.apache.lucene.queryParser.ParseException;  
  14. import org.apache.lucene.queryParser.QueryParser;  
  15. import org.apache.lucene.search.Hits;  
  16. import org.apache.lucene.search.IndexSearcher;  
  17. import org.apache.lucene.search.Query;  
  18. import org.apache.lucene.search.Searcher;  
  19. import org.apache.lucene.search.highlight.Highlighter;  
  20. import org.apache.lucene.search.highlight.QueryScorer;  
  21. import org.apache.lucene.search.highlight.SimpleFragmenter;  
  22. import org.apache.lucene.store.Directory;  
  23. import org.apache.lucene.store.RAMDirectory;  
  24.   
  25. public class Test {  
  26.   
  27.     public static void main(String[] args) throws IOException, ParseException {  
  28.         // try {  
  29.         // //Indexer.index("E:/code/jrcms_liugong/website/products/",  
  30.         // "F:/workspace/spring-mvc/WebRoot/WEB-INF/index/");  
  31.         // Searcher.search("F:/workspace/spring-mvc/WebRoot/WEB-INF/index/");  
  32.         // } catch (Exception e) {  
  33.         // e.printStackTrace();  
  34.         // }  
  35.         // 将庖丁封装成符合Lucene要求的Analyzer规范  
  36.         String dateDir = "E:/code/jrcms_liugong/website/about/";  
  37.         Analyzer analyzer = new PaodingAnalyzer();  
  38.         File[] files = new File(dateDir).listFiles();  
  39.         for (File f : files) {  
  40.             // 读取本类目录下的text.txt文件  
  41.             String content = Indexer.readContents(f, "UTF-8");  
  42.             // 接下来是标准的Lucene建立索引和检索的代码  
  43.             Directory ramDir = new RAMDirectory();  
  44.             IndexWriter writer = new IndexWriter(ramDir, analyzer);  
  45.             Document doc = new Document();  
  46.             Field fname = new Field("filename",f.getName(),Field.Store.YES,Field.Index.UN_TOKENIZED);  
  47.             Field fd = new Field("contents", content, Field.Store.YES,  
  48.                     Field.Index.TOKENIZED,  
  49.                     Field.TermVector.WITH_POSITIONS_OFFSETS);  
  50.             doc.add(fname);  
  51.             doc.add(fd);  
  52.             writer.addDocument(doc);  
  53.             writer.optimize();  
  54.             writer.close();  
  55.             IndexReader reader = IndexReader.open(ramDir);  
  56.             String queryString = "国家级企业技术中心";  
  57.             QueryParser parser = new QueryParser("contents", analyzer);  
  58.             Query query = parser.parse(queryString);  
  59.             Searcher searcher = new IndexSearcher(ramDir);  
  60.             query = query.rewrite(reader);  
  61.             //System.out.println("Searching for: " + query.toString("contents"));  
  62.             Hits hits = searcher.search(query);  
  63.             BoldFormatter formatter = new BoldFormatter();  
  64.             Highlighter highlighter = new Highlighter(formatter,  
  65.                     new QueryScorer(query));  
  66.             highlighter.setTextFragmenter(new SimpleFragmenter(50));  
  67.             for (int i = 0; i < hits.length(); i++) {  
  68.                 String text = hits.doc(i).get("filename");  
  69. //              int maxNumFragmentsRequired = 5;  
  70. //              String fragmentSeparator = "...";  
  71. //              TermPositionVector tpv = (TermPositionVector) reader.getTermFreqVector(hits.id(i), "contents");  
  72. //              TokenStream tokenStream = TokenSources.getTokenStream(tpv);  
  73. //              String result = highlighter.getBestFragments(tokenStream, text,  
  74. //                      maxNumFragmentsRequired, fragmentSeparator);  
  75. //              System.out.println("\n" + result);  
  76.                 System.out.println(text);  
  77.             }  
  78.             reader.close();  
  79.         }  
  80.   
  81.     }  
  82. }  

 

 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值