现在的位置: 首页 > 综合 > 正文

lucene 搜索入门实例

2013年08月05日 ⁄ 综合 ⁄ 共 6107字 ⁄ 字号 评论关闭
  1. Y_indexer.java  建索引
  2. package com.hapark.lucene;
  3. import java.io.BufferedReader;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.io.IOException;   
  7. import java.io.InputStreamReader;   
  8. import java.util.ArrayList;
  9. import java.util.Date;   
  10.   
  11. import org.apache.lucene.analysis.Analyzer;   
  12. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  13. import org.apache.lucene.document.Document;   
  14. import org.apache.lucene.document.Field;   
  15. import org.apache.lucene.index.IndexWriter;   
  16. public class Y_indexer {
  17.       public static void main(String[] args) throws Exception {   
  18.             /* 指明要索引文件夹的位置,这里是D盘的y文件夹下 */  
  19.             File fileDir = new File("d://y");   
  20.       
  21.             /* 这里放索引文件的位置 */  
  22.             File indexDir = new File("d://index");   
  23.             Analyzer luceneAnalyzer = new StandardAnalyzer();   
  24.             IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,   
  25.                     true); 
  26.             ArrayList list = new ArrayList();
  27.             getList(fileDir, list);
  28.             File[] textFiles = (File[])list.toArray(new File[0]);
  29.             System.out.println(textFiles.length);
  30.             long startTime = new Date().getTime();   
  31.                
  32.             //增加document到索引去   
  33.             for (int i = 0; i < textFiles.length; i++) {   
  34.                 if (textFiles[i].isFile()   
  35.                         && textFiles[i].getName().endsWith(".html")) {   
  36.                     System.out.println("File " + textFiles[i].getCanonicalPath()   
  37.                             + "正在被索引....");   
  38.                     String temp = FileReaderAll(textFiles[i].getCanonicalPath(),   
  39.                             "GBK");   
  40.                     System.out.println(temp);   
  41.                     Document document = new Document();   
  42.                     Field FieldPath = new Field("path", textFiles[i].getPath(),   
  43.                             Field.Store.YES, Field.Index.NO);   
  44.                     Field FieldBody = new Field("body", temp, Field.Store.YES,   
  45.                             Field.Index.TOKENIZED,   
  46.                             Field.TermVector.WITH_POSITIONS_OFFSETS);   
  47.                     Field FieldTitle = new Field("title", temp, Field.Store.YES,   
  48.                             Field.Index.TOKENIZED,   
  49.                             Field.TermVector.WITH_POSITIONS_OFFSETS);   
  50.                     document.add(FieldPath);   
  51.                     document.add(FieldBody);   
  52.                     document.add(FieldTitle);
  53.                     indexWriter.addDocument(document);   
  54.                 }   
  55.             }   
  56.             //optimize()方法是对索引进行优化   
  57.             indexWriter.optimize();   
  58.             indexWriter.close();   
  59.                
  60.             //测试一下索引的时间   
  61.             long endTime = new Date().getTime();   
  62.             System.out   
  63.                     .println("这花费了"  
  64.                             + (endTime - startTime)   
  65.                             + " 毫秒来把文档增加到索引里面去!"  
  66.                             + fileDir.getPath());   
  67.         }  
  68.       
  69.       
  70.       /**
  71.        * 多层文件夹
  72.        * @param file
  73.        * @param list
  74.        */
  75.       public static void getList(File file, ArrayList list){
  76.           if(file.isDirectory() && file.getName().indexOf(".") != 0){
  77.               
  78.               File [] file2 = file.listFiles();
  79.               for(int i= 0; i< file2.length; i++)
  80.               getList(file2[i], list);
  81.           }else{
  82.           list.add(file);
  83.           }
  84.       }
  85.       
  86.         public static String FileReaderAll(String FileName, String charset)   
  87.                 throws IOException {   
  88.             BufferedReader reader = new BufferedReader(new InputStreamReader(   
  89.                     new FileInputStream(FileName), charset));   
  90.             String line = new String();   
  91.             String temp = new String();   
  92.                
  93.             while ((line = reader.readLine()) != null) {   
  94.                 temp += line;   
  95.             }   
  96.             reader.close();   
  97.             return temp;   
  98.         }   
  99.     }  

 

 

  1. Y_searcher  lucene 搜索
  2. package com.hapark.lucene;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.List;
  7. import org.apache.lucene.analysis.Analyzer;
  8. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  9. import org.apache.lucene.queryParser.ParseException;
  10. import org.apache.lucene.queryParser.QueryParser;
  11. import org.apache.lucene.search.Hits;
  12. import org.apache.lucene.search.IndexSearcher;
  13. import org.apache.lucene.search.Query;
  14. public class Y_searcher {
  15.       
  16.      public List search(){
  17.          List searchResult = new ArrayList();//创建一个List接口的一个实例类ArrayList类
  18.          try{
  19.          Hits hits = null;   
  20.          String key = "苏";   
  21.          Query query = null;   
  22.          IndexSearcher searcher = new IndexSearcher("d://yuyang"); 
  23.             Analyzer analyzer = new StandardAnalyzer();   //创建一个Analyzer接口的一个实例类StandardAnalyzer
  24.            
  25.                 QueryParser qp = new QueryParser("title", analyzer);   
  26.                 query = qp.parse(key);   
  27.            
  28.             if (searcher != null) {   
  29.                   Date start=new Date();
  30.                 hits = searcher.search(query);   //遍历hist结果的length
  31.                 if(hits.length()==0){
  32.                      System.out.println("对不起。没你想要的结果!");
  33.                 }
  34.                 else{
  35.                 for(int i=0;i<hits.length();i++){ 
  36.                      Date end=new Date();
  37.                   //  System.out.println("找到:" + hits.length() + " Totalresult!");   
  38.                   System.out.println("文件的路径:"+hits.doc(i).get("path"));
  39.                    // System.out.println("内容:"+hits.doc(i).get("body"));
  40.                     System.out.println(hits.doc(i).get("title"));
  41.                     System.out.println("检索完成,用时" + (end.getTime() - start.getTime()) + "毫秒");
  42.                 } 
  43.                 }
  44.             }
  45.          }
  46.                 catch(ParseException ex){
  47.                       
  48.                   }
  49.                 catch(IOException e){
  50.                     
  51.                 }
  52.                 return searchResult;
  53.                 }   
  54.      public static void main(String args[]){
  55.               Y_searcher y_s=new Y_searcher();
  56.               y_s.search();
  57.      }
  58. }

 

抱歉!评论已关闭.