0 Comments

编写代码(15分钟)

发布于:2013-01-17  |   作者:广州网站建设  |   已聚集:人围观

搜索引擎的基础在于对全文索引库的管理,在Lucene中,通过IndexWriter来写入索引库。伪代码如下:

1.创建IndexWriter,准备写索引;

2.遍历要索引的路径;

3.优化索引。

下面是主要的实现代码:


  1. public void go() throws Exception  {  
  2.         long start = System.currentTimeMillis();  
  3.         if (verbose) {  
  4.             System.out.println("Creating index in: " + indexDir);  
  5.             //创建索引目录或者建立增量索引  
  6.             if (incremental) System.out.println("- using incremental mode");  
  7.         }  
  8.         Index = new IndexWriter(new File(indexDir), new StandardAnalyzer(),  
  9.             !incremental);//打开或创建索引库,indexDir是索引存放的路径  
  10.           
  11.         File dir = new File(sSourceDir);//待索引的文件存放的路径   
  12.         indexDir(dir);//索引路径   
  13.         index.optimize();//索引优化  
  14.         index.close();//关闭索引库  
  15.         if(verbose)  
  16.         System.out.println("index complete in :"+(System.  currentTime Millis() - start)/1000);  

下面这段代码把文件内容加到索引库:


  1. private void indexFile(File item) {  
  2.         if (verbose) System.out.println("Adding FILE: " + item);    
  3.         News news = loadFile(item);//把文件中的内容加载到news对象  
  4.         if ( news!= null && news.body != null) {  
  5.             Document doc = new Document();  
  6.             //创建网址列  
  7.             Field f = new Field("url", news.URL ,   
  8.                     Field.Store.YES, Field.Index.UN_TOKENIZED,  
  9.                     Field.TermVector.NO);  
  10.             doc.add(f);  
  11.             //创建标题列  
  12.             f = new Field("title", news.title ,   
  13.                     Field.Store.YES, Field.Index.TOKENIZED,  
  14.                     Field.TermVector.WITH_POSITIONS_OFFSETS);  
  15.             doc.add(f);  
  16.             //创建内容列  
  17.             f = new Field("body", news.body.toString() ,   
  18.                     Field.Store.YES, Field.Index.TOKENIZED,  
  19.                     Field.TermVector.WITH_POSITIONS_OFFSETS);  
  20.             doc.add(f);  
  21.             try{  
  22.                 //文档增加到索引库  
  23.                 index.addDocument(doc);  
  24.             }  
  25.             catch(Exception e)  
  26.             {  
  27.                 e.printStackTrace();  
  28.                 System.exit(-1);  
  29.             }  
  30.         }  

完整的代码可以在本书附带的光盘中找到。

运行以后,一般会生成以下三个索引文件:

_0.cfs

segments.gen

segments_2

其中任何索引库都会包括的一个文件是:segments.gen。可以通过判断一个路径下是否包括这个文件来判断一个路径下是否已经存在Lucene索引。

标签:
飞机