Lucene.Net
Lucene.net是Lucene的.net移植版本,是一个开源的全文检索引擎开发包,即它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,是一个Library.你也可以把它理解为一个将索引,搜索功能封装的很好的一套简单易用的API(提供了完整的查询引擎和索引引擎)。利用这套API你可以做很多有关搜索的事情,而且很方便.。开发人员可以基于Lucene.net实现全文检索的功能。
注意:Lucene.Net只能对文本信息进行检索。如果不是文本信息,要转换为文本信息,比如要检索Excel文件,就要用NPOI把Excel读取成字符串,然后把字符串扔给Lucene.Net。Lucene.Net会把扔给它的文本切词保存,加快检索速度。
更多概念性的知识可以参考这篇博文:http://blog.csdn.net/xiucool/archive/2008/11/28/3397182.aspx
这个小Demo样例展示:
ok,接下来就细细详解下士怎样一步一步实现这个效果的。
Lucene.Net 核心——分词算法(Analyzer)
学习Lucune.Net,分词是核心。当然最理想状态下是能自己扩展分词,但这要很高的算法要求。Lucene.Net中不同的分词算法就是不同的类。所有分词算法类都从Analyzer类继承,不同的分词算法有不同的优缺点。
- 内置的StandardAnalyzer是将英文按照空格、标点符号等进行分词,将中文按照单个字进行分词,一个汉字算一个词
- Analyzer analyzer = new StandardAnalyzer();
- TokenStream tokenStream = analyzer.TokenStream("",new StringReader("Hello Lucene.Net,我1爱1你China"));
- Lucene.Net.Analysis.Token token = null;
- while ((token = tokenStream.Next()) != null)
- {
- Console.WriteLine(token.TermText());
- }
复制代码 分词后结果:
- 二元分词算法,每两个汉字算一个单词,“我爱你China”会分词为“我爱 爱你 china”,点击查看二元分词算法CJKAnalyzer。
- Analyzer analyzer = new CJKAnalyzer();
- TokenStream tokenStream = analyzer.TokenStream("", new StringReader("我爱你中国China中华人名共和国"));
- Lucene.Net.Analysis.Token token = null;
- while ((token = tokenStream.Next()) != null)
- {
- Response.Write(token.TermText()+"<br/>");
- }
复制代码
这时,你肯定在想,上面没有一个好用的,二元分词算法乱枪打鸟,很想自己扩展Analyzer,但并不是算法上的专业人士。怎么办?
Lucene.Net核心类简介(一)
- Directory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirectory(文件中)、RAMDirectory (内存中)。
- IndexReader对索引进行读取的类,对IndexWriter进行写的类。
- IndexReader的静态方法bool IndexExists(Directory directory)判断目录directory是否是一个索引目录。IndexWriter的bool IsLocked(Directory directory) 判断目录是否锁定,在对目录写之前会先把目录锁定。两个IndexWriter没法同时写一个索引文件。IndexWriter在进行写操作的时候会自动加锁,close的时候会自动解锁。IndexWriter.Unlock方法手动解锁(比如还没来得及close IndexWriter 程序就崩溃了,可能造成一直被锁定)。
创建索引库操作:
- 构造函数:IndexWriter(Directory dir, Analyzer a, bool create, MaxFieldLength mfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。
- void AddDocument(Document doc),向索引中添加文档(Insert)。Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一条记录,Field相当于字段。
- Field类的构造函数 Field(string name, string value, Field.Store store, Field.Index index, Field.TermVector termVector): name表示字段名; value表示字段值; store表示是否存储value值,可选值 Field.Store.YES存储, Field.Store.NO不存储, Field.Store.COMPRESS压缩存储;默认只保存分词以后的一堆词,而不保存分词之前的内容,搜索的时候无法根据分词后的东西还原原文,因此如果要显示原文(比如文章正文)则需要设置存储。 index表示如何创建索引,可选值Field.Index. NOT_ANALYZED ,不创建索引,Field.Index. ANALYZED,创建索引;创建索引的字段才可以比较好的检索。是否碎尸万段!是否需要按照这个字段进行“全文检索”。 termVector表示如何保存索引词之间的距离。“北京欢迎你们大家”,索引中是如何保存“北京”和“大家”之间“隔多少单词”。方便只检索在一定距离之内的词。
- private void CreateIndex()
- {
- //索引库存放在这个文件夹里
- string indexPath = ConfigurationManager.AppSettings["pathIndex"];
- //Directory表示索引文件保存的地方,是抽象类,两个子类FSDirectory表示文件中,RAMDirectory 表示存储在内存中
- FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
- //判断目录directory是否是一个索引目录。
- bool isUpdate = IndexReader.IndexExists(directory);
- logger.Debug("索引库存在状态:"+isUpdate);
- if (isUpdate)
- {
- if (IndexWriter.IsLocked(directory))
- {
- IndexWriter.Unlock(directory);
- }
- }
- //第三个参数为是否创建索引文件夹,Bool Create,如果为True,则新创建的索引会覆盖掉原来的索引文件,反之,则不必创建,更新即可。
- IndexWriter write = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED);
- WebClient wc = new WebClient();
- //编码,防止乱码
- wc.Encoding = Encoding.UTF8;
- int maxID;
- try
- {
- //读取rss,获得第一个item中的链接的编号部分就是最大的帖子编号
- maxID = GetMaxID();
- }
- catch (WebException webEx)
- {
- logger.Error("获得最大帖子号出错",webEx);
- return;
-
- }
- for (int i = 1; i <= maxID; i++)
- {
- try
- {
- string url = "http://localhost:8080/showtopic-" + i + ".aspx";
- logger.Debug("开始下载:"+url);
- string html = wc.DownloadString(url);
- HTMLDocumentClass doc = new HTMLDocumentClass();
- doc.designMode = "on";//不让解析引擎尝试去执行
- doc.IHTMLDocument2_write(html);
- doc.close();
- string title = doc.title;
- string body = doc.body.innerText;
- //为避免重复索引,先输出number=i的记录,在重新添加
- write.DeleteDocuments(new Term("number", i.ToString()));
- Document document = new Document();
- //Field为字段,只有对全文检索的字段才分词,Field.Store是否存储
- document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
- document.Add(new Field("title", title, Field.Store.YES, Field.Index.NOT_ANALYZED));
- document.Add(new Field("body", body, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
- write.AddDocument(document);
- logger.Debug("索引" + i.ToString() + "完毕");
- }
- catch (WebException webEx)
- {
- logger.Error("下载"+i.ToString()+"失败",webEx);
- }
- }
- write.Close();
- directory.Close();
- logger.Debug("全部索引完毕");
- }
- //取最大帖子号
- private int GetMaxID()
- {
- XDocument xdoc = XDocument.Load("Http://localhost:8080/tools/rss.aspx");
- XElement channel = xdoc.Root.Element("channel");
- XElement fitstItem = channel.Elements("item").First();
- XElement link = fitstItem.Element("link");
- Match match = Regex.Match(link.Value, @"http://localhost:8080/showtopic-(\d+)\.aspx");
- string id = match.Groups[1].Value;
- return Convert.ToInt32(id);
- }
复制代码
- 搜索建议,类似于Baidu搜索时下拉提示框,Jquery UI模拟,下面是获取根据搜索数量最多的进行排序,得到IEnumerable集合
[code] public IEnumerable GetSuggestion(string kw) { DataTable dt = SqlHelper.ExecuteDataTable(@"select top 5 Keyword,count(*) as searchcount from keywords where datediff(day,searchdatetime,getdate()) |