搜索引擎的基础在于对全文索引库的管理,在Lucene中,通过IndexWriter来写入索引库。伪代码如下:
1.创建IndexWriter,准备写索引;
2.遍历要索引的路径;
3.优化索引。
下面是主要的实现代码:
- public void go() throws Exception {
- long start = System.currentTimeMillis();
- if (verbose) {
- System.out.println("Creating index in: " + indexDir);
- //创建索引目录或者建立增量索引
- if (incremental) System.out.println("- using incremental mode");
- }
- Index = new IndexWriter(new File(indexDir), new StandardAnalyzer(),
- !incremental);//打开或创建索引库,indexDir是索引存放的路径
- File dir = new File(sSourceDir);//待索引的文件存放的路径
- indexDir(dir);//索引路径
- index.optimize();//索引优化
- index.close();//关闭索引库
- if(verbose)
- System.out.println("index complete in :"+(System. currentTime Millis() - start)/1000);
- }
下面这段代码把文件内容加到索引库:
- private void indexFile(File item) {
- if (verbose) System.out.println("Adding FILE: " + item);
- News news = loadFile(item);//把文件中的内容加载到news对象
- if ( news!= null && news.body != null) {
- Document doc = new Document();
- //创建网址列
- Field f = new Field("url", news.URL ,
- Field.Store.YES, Field.Index.UN_TOKENIZED,
- Field.TermVector.NO);
- doc.add(f);
- //创建标题列
- f = new Field("title", news.title ,
- Field.Store.YES, Field.Index.TOKENIZED,
- Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- //创建内容列
- f = new Field("body", news.body.toString() ,
- Field.Store.YES, Field.Index.TOKENIZED,
- Field.TermVector.WITH_POSITIONS_OFFSETS);
- doc.add(f);
- try{
- //文档增加到索引库
- index.addDocument(doc);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- System.exit(-1);
- }
- }
- }
完整的代码可以在本书附带的光盘中找到。
运行以后,一般会生成以下三个索引文件:
_0.cfs
segments.gen
segments_2
其中任何索引库都会包括的一个文件是:segments.gen。可以通过判断一个路径下是否包括这个文件来判断一个路径下是否已经存在Lucene索引。



