代码改变世界

应用Lucene.net建立全文索引引擎

2006-08-26 18:00  cppguy  阅读(7480)  评论(1编辑  收藏  举报
具体方案:
1.建立索引
为60篇记事本文档的中文小说建立索引,分析器采用Lucene.Net.Analysis.Cn.ChineseAnalyzer()(这个索引器是从http://www.cnblogs.com/dudu/archive/2004/06/22/17783.aspx下载的,是dudu修正bug后的版本,感谢dudu.)统计索引的建立时间.同时,会更改IndexWriter的参数以感受相关参数对索引建立速度的影响.
2.关键字检索
当索引建立完毕后,对索引进行简单关键字的检索,查看响应时间
3.多线程检索
采用多线程对索引的检索,以查看多线程环境下lucene的工作效率


1.构建Document
在建立索引之前,首先要构建Document类型,它把文本文档转变成lucene可以识别的Document格式.
class FileDocument
    
{
        
public static Document getDocument(FileInfo file)
        
{
            Document doc 
= new Document();

            
//为文件路径构建一个字段
            doc.Add(new Field("path", file.FullName, Field.Store.YES, Field.Index.UN_TOKENIZED));

            
//为文件名构建一个字段
            doc.Add(Field.Keyword("title",file.Name));

            
//为文件内容建一个字段
            doc.Add(new Field("content",new StreamReader(file.FullName,Encoding.Default)));

            
//为文本的最后修改时间构建一个字段
            doc.Add(new Field("modified", DateTools.TimeToString(file.LastWriteTime.Ticks, DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.UN_TOKENIZED));

            
return doc;
            
        }

    }

在上述代码中,一个共有的静态方法返回一个Document类型的对象,它的参数是FileInfo类型,在建立索引的时候,将获得的文件对象传入就可以得到与lucene相对应的Document类型.上面的代码一添加了四个不同的字段.

2.建立索引的代码
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Analysis;
using System.IO;

namespace IndexDemo
{
    
class IndexTest
    
{
        
static readonly System.IO.FileInfo INDEX_DIR = new System.IO.FileInfo("index2");
        
//索引存放位置
        public  static String INDEX_STORE_PATH = "c:\\index";

        
//合并索引前,内存中最大的文件数量
        public static int DEFAULT_MAX_DOCS_IN_RAM = 40;

        
//最大的字段长度
        public static readonly int DEFAULT_MAX_FIELD_LENGTH = int.MaxValue;

        
//单例模式
        private static IndexTest indextest = null;

        
//两个索引器
        private IndexWriter ramWriter = null;
        
private IndexWriter fsWriter = null;

        
//内存中已经有的文档数量
        private int docs_in_ram;
        
//内存中最大的文档数量
        private int ramMaxFiles = DEFAULT_MAX_DOCS_IN_RAM;
        
//内存是否被刷新过
        private Boolean freshed = true;

        
//索引存放的文件系统目录
        FSDirectory fsDir = null;
        
//索引存放的内存目录
        RAMDirectory ramDir = null;

        
//私有构造函数
        private IndexTest() { }

        
// 静态方法构造一个单例
        public static IndexTest getInstance()
        
{
            
if (indextest == null)
            
{
                indextest 
= new IndexTest();
            }

            
return indextest;
        }


        
//构造索引器
        public void newWriter()
        
{
            
if (fsWriter != null || ramWriter != null)
            
{
                Console.WriteLine(
"some indexer has builded");
                
return;
            }

            
try
            
{
                Boolean rebuild 
= true;


                ramDir 
= new RAMDirectory();

                Analyzer analyser 
= new ChineseAnalyzer();
                ramWriter 
= new IndexWriter(ramDir,analyser,true);
                fsDir 
= FSDirectory.GetDirectory("C:\\index", rebuild);
                fsWriter 
= new IndexWriter(fsDir,analyser,rebuild);
                initWriter();

                
            }

            
catch { }
        }

        
//初始化索引器
        private void initWriter()
        
{
            fsWriter.maxFieldLength 
= DEFAULT_MAX_FIELD_LENGTH;
        }


        
//优化索引
        public void optimizeIndex()
        
{
            
if(fsWriter== null||ramWriter== null)
            
{
                Console.WriteLine(
"initialize a new indexer fist");
                
return;
            }

            refreshRam();
            fsWriter.Optimize();
        }


        
//索引某个目录下的文件
        public void toIndex(String path)
        
{
            toIndex(
new FileInfo(path));
        }

        
//索引某个File对象
        public void toIndex(FileInfo file)
        
{
            
if (fsWriter== null || ramWriter == null)
            
{
                Console.WriteLine(
"some indexer has builded");
                
return;
            }

            freshed 
= false;
            DateTime start 
= DateTime.Now;
            
int number = indexFiles(file);
            DateTime end 
= DateTime.Now;
            
long time=end.Ticks-start.Ticks;
            Console.WriteLine(
"总共耗时{0}毫秒",Convert.ToString(time));
            Console.WriteLine(
"一共为{0}个文件建立索引", number);
 
        }


        
//关闭索引
        public void close()
        
{
            
if (fsWriter == null || ramWriter == null)
            
{
                Console.WriteLine(
"use newwriter() method to initialize a new indexerfirsrt");
                
return;
            }

            refreshRam();
            ramWriter.Close();
            fsWriter.Close();
 
        }

        
//刷新内存
        private void refreshRam()
        
{
            
if (!freshed)
            
{
                Console.WriteLine(
"Refreshing");
                fsWriter.AddIndexes(
new Lucene.Net.Store.Directory[] { ramDir});
            }


            ramDir.Close();
            ramDir 
= new RAMDirectory();
            ramWriter 
= new IndexWriter(ramDir,new ChineseAnalyzer(),true);

            docs_in_ram 
= 0;
            freshed 
= true;
        }

        
//向索引中加入文档
        private void addDocument(FileInfo file)
        
{
            
if (docs_in_ram >= ramMaxFiles)
            
{
                refreshRam();
            }

            ramWriter.AddDocument(FileDocument.getDocument(file));
            docs_in_ram
++;
            freshed 
= false;
 
        }


        
//递归的遍历文件目录来建立索引
        private int indexFiles(FileInfo file)
        
{
            
if (System.IO.Directory.Exists(file.FullName))
            
{
                
string[] files = System.IO.Directory.GetFiles(file.FullName);
                
int num = 0;
                
if (files != null)
                
{
                    
for (int i = 0; i < files.Length; i++)
                    
{
                        num
+=indexFiles(new FileInfo(files[i]));
                    }

                }

                
return num;
            }

            
else 
            
{

                
if (file.FullName.EndsWith(".txt"))
                
{
                    Console.WriteLine(
"正在搜索:"+file.Name);
                    addDocument(file);
                    
return 1;
                }

                
else
                
{
                    Console.WriteLine(
"文件类型不支持");
                    
return 0;
                }

            }


        }

        
static void Main(string[] args)
        
{
            IndexTest test 
= IndexTest.getInstance();
            test.newWriter();
            test.toIndex(
"e:\\source");
            test.close();
        }

    }

}

在上面的代码中,当通过getInstance()方法得到一个该类的实例后,则可以调用newWriter()方法来获得索引器的实例.在newWriter()方法中获取了两个IndexWriter的实例.一个是向文件系统创建的索引器,另一个则向内存中创建索引的索引器,因此对对应的创建了一个RAMDirectory和一贯FSDirectory的对象.这么做的目的是希望减少磁盘的I/O次数,当内存中累积的文档到达一定数量时候,就自动刷新内存,将其写入文件系统中,因此,需要一个内存中最大文档数量的限制,该值就是由私有类变量ramMaxFiles控制,它的默认为64.
  addDocument(File file)是真正将文档加入索引的的代码,在它之中首先要判断当前内存中的文档数量是否已经大雨最大的文档数量.如果已经达到,则调用refreshRam方法刷新内存中的文档到磁盘上.如果未达到,则继续将文档假如内存中.

3:开始建立索引
在代码最后,有一个Main方法,他指定在e:\\source目录上建立索引.当运行它时,就可以执行索引建立的过程





上面测试中initWriter中仅仅调置了一个fsWriter的最大字段长度.如果用户有兴趣,可以调整mergeFactor和maxMergeDocs等参数来查看索引的建立速度