用户名: 密 码:
您现在的位置:首页 >> SEO开发技巧 >> 内容

一个小小的搜索例子,实现对某个文件夹下的文件进行搜索

时间:2009/12/25 11:13:22 点击:6955

  核心提示:一个小小的搜索例子,实现对某个文件夹下的文件进行搜索这里只有主要代码,整个project在附件中,导入到MyEclipse中时根据自己的情况修改配置文件中paoding-dic-home.properties的地址,当然,前提是你必须有庖丁解牛的字典,在页面搜索“项目”,会出现结果(基本每个文件中都...

一个小小的搜索例子,实现对某个文件夹下的文件进行搜索

这里只有主要代码,整个project在附件中,导入到MyEclipse中时根据自己的情况修改配置文件中paoding-dic-home.properties的地址,当然,前提是你必须有庖丁解牛的字典,在页面搜索项目,会出现结果(基本每个文件中都有项目这个词)

附件中有项目T_Search,文件lucene\data,索引\lucene\index

MIndexer.java:创建索引(对文件进行创建,先把文件内容读取成String)

Java代码 复制代码
  1. public class MIndexer {   
  2.     public void createIndex() {      
  3.         long start = System.currentTimeMillis();      
  4.         try {      
  5.             // 获取Paoding中文分词器      
  6.             Analyzer analyzer = new PaodingAnalyzer();       
  7.             // indexWriter建立索引,E:\lucene\index建立索引的目录   
  8.             IndexWriter writer = new IndexWriter("E:\\lucene\\index", analyzer, true,IndexWriter.MaxFieldLength.UNLIMITED);    
  9.           //E:\lucene\data建立索引的数据,主要是.txt、.pdf文件    
  10.             indexDocs(writer, new File("E:\\lucene\\data"));    
  11.             writer.optimize();      
  12.             writer.close();      
  13.             System.out.println("用时:" + (System.currentTimeMillis() - start) + " 毫秒");      
  14.         } catch (IOException e) {      
  15.             e.printStackTrace();      
  16.         }      
  17.     }      
  18.     // 遍历文件夹文件,对需要的文件建立索引      
  19.     static void indexDocs(IndexWriter writer, File file) throws IOException {      
  20.         if (file.canRead()) {      
  21.             if (file.isDirectory()) {      
  22.                 String[] files = file.list();      
  23.                 if (files != null) {      
  24.                     for (int i = 0; i < files.length; i++) {      
  25.                         indexDocs(writer, new File(file, files[i]));      
  26.                     }      
  27.                 }      
  28.             } else {      
  29.                 if (file.getName().endsWith(".htm")      
  30.                         || file.getName().endsWith(".html")      
  31.                         || file.getName().endsWith(".jsp")      
  32.                         || file.getName().endsWith(".php")      
  33.                         || file.getName().endsWith(".txt")   
  34.                         || file.getName().endsWith(".pdf")) {     
  35.                     try {      
  36.                         // 针对参数文件建立索引文档 ,一个Document就相当于一跳记录      
  37.                         Document doc = new Document();      
  38.                         // Field.Index.ANALYZED 文件名称 建立索引,分词      
  39.                         doc.add(new Field("filename", file.getCanonicalPath(),      
  40.                                 Field.Store.YES, Field.Index.ANALYZED,      
  41.                                 Field.TermVector.WITH_POSITIONS_OFFSETS));    
  42.                         if(file.getName().endsWith(".pdf")){   
  43.                             doc.add(new Field("contents", pdf2txt(file),      
  44.                                     Field.Store.YES, Field.Index.ANALYZED,      
  45.                                     Field.TermVector.WITH_POSITIONS_OFFSETS));   
  46.                         }else {   
  47.                             doc.add(new Field("contents", ReadFile(file),      
  48.                                     Field.Store.YES, Field.Index.ANALYZED,      
  49.                                     Field.TermVector.WITH_POSITIONS_OFFSETS));   
  50.                         }     
  51.                            
  52.                         writer.addDocument(doc);      
  53.                     } catch (FileNotFoundException fnfe) {      
  54.                         ;      
  55.                     }      
  56.                 }      
  57.             }      
  58.         }      
  59.     }      
  60.      
  61.     // 用字符串形式,读取一个File的内容      
  62.     public static String ReadFile(File f) {      
  63.         String line = null;      
  64.         StringBuffer temp = new StringBuffer();      
  65.         try {      
  66.             BufferedReader br = new BufferedReader(new InputStreamReader(      
  67.                     new FileInputStream(f), "UTF-8"));      
  68.             while ((line = br.readLine()) != null) {      
  69.                 temp.append(line);      
  70.             }      
  71.         } catch (FileNotFoundException e) {      
  72.             e.printStackTrace();      
  73.         } catch (IOException e) {      
  74.             e.printStackTrace();      
  75.         }      
  76.         return temp.toString();      
  77.     }      
  78.     //若文件为pdf,就用这个读取   
  79.     public static String pdf2txt(File pfile) {   
  80.         String _content = "";   
  81.         if (pfile.exists() && pfile.getName().lastIndexOf(".pdf") >= 1) {   
  82.             String textFile = String.format("%s%s%s%s%s.txt",   
  83.                     pfile.getPath().substring(0,   
  84.                             pfile.getPath().lastIndexOf(pfile.getName())),   
  85.                     System.getProperty("file.separator"), "temp", System   
  86.                             .getProperty("file.separator"), pfile.getName()   
  87.                             .substring(0, pfile.getName().lastIndexOf(".pdf")));   
  88.             if (!new File(textFile.substring(0, textFile.lastIndexOf(new File(   
  89.                     textFile).getName()))).exists()) {   
  90.                 new File(textFile.substring(0, textFile.lastIndexOf(new File(   
  91.                         textFile).getName()))).mkdirs();   
  92.             }   
  93.   
  94.             PDDocument pdDoc = null;   
  95.             COSDocument cosDoc = null;   
  96.             try {   
  97.                 pdDoc = PDDocument.load(pfile);   
  98.                 PDFParser parser = new PDFParser(new FileInputStream(pfile));   
  99.                 parser.parse();   
  100.                 cosDoc = parser.getDocument();   
  101.                 PDFTextStripper stripper = new PDFTextStripper();   
  102.                 _content = stripper.getText(new PDDocument(cosDoc));   
  103.             } catch (IOException e) {   
  104.                 e.printStackTrace();   
  105.             } finally {   
  106.                 try {   
  107.                     cosDoc.close();   
  108.                     pdDoc.close();   
  109.                     if (new File(textFile).exists()) {   
  110.                         new File(textFile).delete();   
  111.                     }   
  112.                 } catch (IOException e) {   
  113.                     e.printStackTrace();   
  114.                 }   
  115.             }   
  116.         }   
  117.         return _content;   
  118.     }   
  119. }  

 

 

MSearcher.java:搜索,返回符合条件的List

 

Java代码 复制代码
  1. public class MSearcher {   
  2.     public List<MBean> searchIndex(String keyword, boolean highlight,   
  3.             int content_length, int start, int length) {   
  4.         String indexpath = "E:\\lucene\\index"// 索引所在目录   
  5.   
  6.         List<MBean> mList = new ArrayList<MBean>();   
  7.         if (indexpath != null && new File(indexpath).exists()   
  8.                 && keyword != null && !keyword.trim().equals("") && length > 0) {   
  9.             start = (start > 0) ? start : 1;   
  10.             String[] FIELD = { "filename""contents" };   
  11.             // 获取Paoding中文分词器   
  12.             Analyzer analyzer = new PaodingAnalyzer();   
  13.             FSDirectory directory;   
  14.             IndexReader reader;   
  15.             Searcher searcher;   
  16.             try {   
  17.                 directory = FSDirectory.getDirectory(indexpath);   
  18.                 reader = IndexReader.open(directory);   
  19.                 String queryString = keyword;   
  20.                 /*  
  21.                  * 下面这个表示要同时搜索这两个域,而且只要一个域里面有满足我们搜索的内容就行 SHOULD表示查询条件为or  
  22.                  * MUST表示查询条件为and MUST_NOT表示查询条件为not  
  23.                  */  
  24.                 BooleanClause.Occur[] flags = new BooleanClause.Occur[] {   
  25.                         BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };   
  26.                 Query query = MultiFieldQueryParser.parse(queryString, FIELD,   
  27.                         flags, analyzer);   
  28.   
  29.                 searcher = new IndexSearcher(directory);   
  30.                 query = query.rewrite(reader);   
  31.                 //分页,取出前start + length - 1条数据   
  32.                 TopDocCollector collector = new TopDocCollector(start + length - 1);   
  33.                 searcher.search(query, collector);   
  34.                 ScoreDoc[] hits = collector.topDocs().scoreDocs;   
  35.                 BoldFormatter formatter = new BoldFormatter();   
  36.                 Highlighter highlighter = new Highlighter(formatter,   
  37.                         new QueryScorer(query));   
  38.                 highlighter.setTextFragmenter(new SimpleFragmenter(   
  39.                         content_length));   
  40.                 for (int i = start - 1; i < hits.length; i++) {   
  41.                     MBean mBean = new MBean();   
  42.                     Document doc = searcher.doc(hits[i].doc);   
  43.                     String _filename = doc.get(FIELD[0]);   
  44.                     String _contents = doc.get(FIELD[1]);   
  45.                     int maxNumFragmentsRequired = 5;   
  46.                     String fragmentSeparator = "...";   
  47.                     TermPositionVector tpv_filename = (TermPositionVector) reader   
  48.                             .getTermFreqVector(hits[i].doc, FIELD[0]);   
  49.                     TermPositionVector tpv_contents = (TermPositionVector) reader   
  50.                             .getTermFreqVector(hits[i].doc, FIELD[1]);   
  51.                     String high_filename = "";   
  52.                     String high_contents = "";   
  53.                     if (tpv_filename != null) {   
  54.                         TokenStream token_filename = TokenSources   
  55.                                 .getTokenStream(tpv_filename);   
  56.                         high_filename = highlighter.getBestFragments(   
  57.                                 token_filename, _filename,   
  58.                                 maxNumFragmentsRequired, fragmentSeparator);   
  59.                     }   
  60.                     if (tpv_contents != null) {   
  61.                         TokenStream token_contents = TokenSources   
  62.                                 .getTokenStream(tpv_contents);   
  63.                         high_contents = highlighter.getBestFragments(   
  64.                                 token_contents, _contents,   
  65.                                 maxNumFragmentsRequired, fragmentSeparator);   
  66.                     }   
  67.                     mBean.setFilename((high_filename != null && !high_filename   
  68.                             .equals("")) ? high_filename : _filename);   
  69.                     mBean.setContents((high_contents != null && !high_contents   
  70.                             .equals("")) ? high_contents   
  71.                             : (_contents.length() > content_length ? _contents   
  72.                                     .substring(0, content_length) : _contents));   
  73.                     mList.add(mBean);   
  74.                 }   
  75.   
  76.                 searcher.close();   
  77.                 reader.close();   
  78.             } catch (ParseException e) {   
  79.                 e.printStackTrace();   
  80.             } catch (IOException e) {   
  81.                 e.printStackTrace();   
  82.             }   
  83.         }   
  84.         return mList;   
  85.     }   
  86.   
  87.     public Integer searchIndexLength(String keyword, boolean highlight,   
  88.             int content_length, int start, int length, int maxLength) {   
  89.         int _count = 0;   
  90.         String indexpath = "E:\\lucene\\index";   
  91.         if (indexpath != null && new File(indexpath).exists()   
  92.                 && keyword != null && !keyword.trim().equals("") && length > 0) {   
  93.             start = (start > 0) ? start : 1;   
  94.             String[] FIELD = { "filename""contents" };   
  95.             Analyzer analyzer = new PaodingAnalyzer();   
  96.             FSDirectory directory;   
  97.             IndexReader reader;   
  98.             Searcher searcher;   
  99.             try {   
  100.                 directory = FSDirectory.getDirectory(indexpath);   
  101.                 reader = IndexReader.open(directory);   
  102.                 String queryString = keyword;   
  103.                 BooleanClause.Occur[] flags = new BooleanClause.Occur[] {   
  104.                         BooleanClause.Occur.SHOULD,   
  105.                         BooleanClause.Occur.SHOULD };   
  106.                 Query query = MultiFieldQueryParser.parse(queryString, FIELD,   
  107.                         flags, analyzer);   
  108.   
  109.                 searcher = new IndexSearcher(reader);   
  110.                 query = query.rewrite(reader);   
  111.   
  112.                 TopDocCollector collector = new TopDocCollector(maxLength);   
  113.                 searcher.search(query, collector);   
  114.                 ScoreDoc[] hits = collector.topDocs().scoreDocs;   
  115.                 _count = hits.length;   
  116.                 searcher.close();   
  117.                 reader.close();   
  118.             } catch (ParseException e) {   
  119.                 e.printStackTrace();   
  120.             } catch (IOException e) {   
  121.                 e.printStackTrace();   
  122.             }   
  123.         }   
  124.         return _count;   
  125.     }   
  126.   
  127. }  

 

Search.java:处理用户请求的Servlet

Java代码 复制代码
  1. public class Search extends HttpServlet {   
  2.     private static final Integer NUMBER = 10;//每页显示10条   
  3.     private static final Integer CONTENT_LENGTH = 50;   
  4.     private static final Boolean HIGHLIGHT = true;   
  5.     private static final long serialVersionUID = 1L;   
  6.     private MSearcher mSearcher = new MSearcher();   
  7.   
  8.     @Override  
  9.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  10.             throws ServletException, IOException {   
  11.         request.setCharacterEncoding("UTF-8");   
  12.         String q = request.getParameter("q") != null ? request   
  13.                 .getParameter("q").trim() : request.getParameter("q");   
  14.                 System.out.println("----"+q);   
  15.         List<MBean> mList = new ArrayList<MBean>();   
  16.         List<PBean> pList = new ArrayList<PBean>();   
  17.         int start = request.getParameter("start")!= null ? Integer   
  18.                 .valueOf(request.getParameter("start"))   
  19.                 : 0;   
  20.         int all_count = 0;   
  21.         all_count = mSearcher.searchIndexLength( q, HIGHLIGHT,   
  22.                 CONTENT_LENGTH, start, NUMBER, NUMBER * 1000);   
  23.   
  24.         mList = mSearcher.searchIndex( q, HIGHLIGHT,   
  25.                 CONTENT_LENGTH, start, NUMBER);   
  26.            
  27.         pList = getPageList(all_count, start);   
  28.         if (start > NUMBER) {   
  29.             request.setAttribute("previous", start - NUMBER);   
  30.         }   
  31.         if (start < all_count - NUMBER) {   
  32.             request.setAttribute("next", NUMBER + (start != 0 ? start : 1));   
  33.         }   
  34.         request.setAttribute("q", q);   
  35.         request.setAttribute("start", start);   
  36.         request.setAttribute("pList", pList);   
  37.         request.setAttribute("mList", mList.isEmpty() ? null : mList);   
  38.         request.getRequestDispatcher("/index.jsp").forward(request, response);   
  39.     }   
  40.   
  41.     @Override  
  42.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  43.             throws ServletException, IOException {   
  44.         doPost(request, response);   
  45.     }   
  46.   
  47.     private static List<PBean> getPageList(int all_count, int start) {   
  48.         MIndexer mIndexer = new MIndexer();   
  49.         mIndexer.createIndex();   
  50.         List<PBean> pList = new ArrayList<PBean>();   
  51.         int all_page = (all_count <= 0) ? 1 : (all_count / NUMBER + (all_count   
  52.                 % NUMBER > 0 ? 1 : 0));   
  53.         int now_page = (start <= 0) ? 1  
  54.                 : (start / NUMBER + (start % NUMBER > 0 ? 1 : 0));   
  55.         for (int i = (now_page - 10 > 0 ? now_page - 10 : 1); i <= (((now_page + 9) <= all_page) ? (now_page + 9)   
  56.                 : all_page); i++) {   
  57.             PBean pBean = new PBean();   
  58.             pBean.setPage(i);   
  59.             pBean.setStart((pBean.getPage() - 1) * NUMBER + 1);   
  60.             pList.add(pBean);   
  61.         }   
  62.         return pList;   
  63.     }   
  64. }  

 

文章来源:http://www.xinxilong.com

作者:不详 来源:网络
相关评论
发表我的评论
  • 大名:
  • 内容:
  • 论坛群发大师(www.xinxilong.com) © 2008 版权所有 All Rights Resverved.
  • Email:4984672[at]qq.com 沪ICP备12025887号-1
  • Powered by 论坛群发大师