使用Luncene.Net及相关技术初步实现搜索
使用Luncene.Net及相关技术初步实现搜索
一、简介
Lucene.Net是由Java版本的Lucene移植过来的,所有的类、方法都几乎和Lucene一模一样,因此使用时参考Lucene 即可。
Lucene.Net只是一个全文检索开发包,不是一个成型的搜索引擎,它的功能就是:把数据扔给Lucene.Net ,查询数据的时候从Lucene.Net 查询数据,可以看做是提供了全文检索功能的一个数据库。Lucene.Net不管文本数据怎么来的。用户可以基于Lucene.Net开发满足自己需求的搜索引擎。 Lucene.Net只能对文本信息进行检索。如果不是文本信息,要转换为文本信息,比如要检索Excel文件,就要用NPOI把Excel读取成字符串,然后把字符串扔给Lucene.Net。Lucene.Net会把扔给它的文本切词保存,加快检索速度。midomi.com

二、分词
分词是核心的算法,搜索引擎内部保存的就是一个个的“词(Word)”。英文分词很简单,按照空格分隔就可以。中文则麻烦,把“北京,Hi欢迎你们大家” 拆成“北京 Hi 欢迎 你们 大家”。
“the”,“,”,“和”,“啊”,“的”等对于搜索来说无意义的词一般都属于不参与分词的无意义单词(noise word)。
Lucene.Net中不同的分词算法就是不同的类。所有分词算法类都从Analyzer类继承,不同的分词算法有不同的优缺点。
(*)内置的StandardAnalyzer是将英文按照空格、标点符号等进行分词,将中文按照单个字进行分词,一个汉字算一个词。代码见备注
(*)二元分词算法,每两个汉字算一个单词,“欢迎你们大家”会分词为“欢迎 迎你 你们 们大 大家”,网上找到的一个二元分词算法CJKAnalyzer。面试的时候能说出不同的分词算法的差异。
基于词库的分词算法,基于一个词库进行分词,可以提高分词的成功率。有庖丁解牛、盘古分词等。效率低。
2.1StandardAnalyzer示例
Analyzer analyzer = new StandardAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("",new StringReader("北京,Hi欢迎你们大家"));
Lucene.Net.Analysis.Token token = null;
while ((token = tokenStream.Next()) != null)
{
Console.WriteLine(token.TermText());
}
三、盘古分词算法的使用
具体用法参考《PanguMannual.pdf》
打开PanGu4Lucene\WebDemo\Bin,将Dictionaries添加到项目根路径(改名为Dict),添加对PanGu.dll(同目录下不要有Pangu.xml,那个默认的配置文件的选项对于分词结果有很多无用信息)、PanGu.Lucene.Analyzer.dll的引用
把上节代码的Analyzer用PanGuAnalyzer代替
运行报错?通用技巧:把Dict目录下的文件“复制到输出目录”设定为“如果较新则复制”。
(*)Dictionaries下几个txt文件简介
词库的编辑,使用DictManage.exe,对单词编辑的时候要先查找。工作的项目中要将行业单词添加到词库中,比如餐饮搜索、租房搜索、视频搜索等。
3.1示例代码(与上面的StandardAnalyzer分词不同就只有第一句):
Analyzer analyzer = new PanGuAnalyzer();//盘古分词检索
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(TextBox1.Text));
Lucene.Net.Analysis.Token token = null;
while ((token = tokenStream.Next()) != null)
{
//Console.WriteLine(token.TermText());
Response.Write(token.TermText() + "<br/>");
}
四、Lucene.Net核心类简介
Directory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirectory(文件中)、RAMDirectory (内存中)。使用的时候别和IO里的Directory弄混了。
创建FSDirectory的方法,FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath),new NativeFSLockFactory()), path索引的文件夹路径
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表示如何保存索引词之间的距离。“北京欢迎你们大家”,索引中是如何保存“北京”和“大家”之间“隔多少单词”。方便只检索在一定距离之内的词。
- 为什么要把帖子的url做为一个Field,因为要在搜索展示的时候先帖子地址取出来构建超链接,所以Field.Store.YES;一般不需要对url进行检索,所以Field.Index.NOT_ANALYZED
案例:对1000至1100号帖子进行索引。“只要能看懂例子和文档,稍作修改即可实现自己的需求”
5.1示例代码:
1、对数据进行索引
string indexPath = "c:/temp";//创建索引的目录(temp是要自己建立的)
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath),new NativeFSLockFactory());
bool isUpdate = IndexReader.IndexExists(directory);
if (isUpdate)
{
//如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
if (IndexWriter.IsLocked(directory))
{
IndexWriter.Unlock(directory);
}
}
IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
for (int i = 1000; i < 1100; i++)//这里是对1000~1100的贴子进行索引
{
string txt = File.ReadAllText(@"C:\MxDownload\dnt_3.1.0_sqlserver\upload_files\文章\" + i + ".txt");
Document document = new Document();
document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index. NOT_ANALYZED));
document.Add(new Field("body", txt, Field.Store.YES, Field.Index. ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(document);
Console.WriteLine("索引"+i+"完毕");
}
writer.Close();
directory.Close();//不要忘了Close,否则索引结果搜不到
注意:上面的for循环只是对1000~1100的贴子进行索引,如果要爬从第一篇到最后一篇贴子,应该怎么办?(如何取得最后一篇帖子)可以对RSS进行分析,因为RSS中就是放的最新的贴子,我们可以从中找到最大的ID
六、搜索
IndexSearcher是进行搜索的类,构造函数传递一个IndexReader。IndexSearcher的void Search(Query query, Filter filter, Collector results)方法用来搜索,Query是查询条件, filter目前传递null, results是检索结果,TopScoreDocCollector.create(1000, true)方法创建一个Collector,1000表示最多结果条数,Collector就是一个结果收集器。
Query有很多子类,PhraseQuery是一个子类。 PhraseQuery用来进行多个关键词的检索,调用Add方法添加关键词,query.Add(new Term("字段名", 关键词)),PhraseQuery. SetSlop(int slop)用来设置关键词之间的最大距离,默认是0,设置了Slop以后哪怕文档中两个关键词之间没有紧挨着也能找到。
- query.Add(new Term("字段名", 关键词))
- query.Add(new Term("字段名", 关键词2))
- 类似于:where 字段名 contains 关键词 and 字段名 contais 关键词2
调用TopScoreDocCollector的GetTotalHits()方法得到搜索结果条数,调用Hits的TopDocs TopDocs(int start, int howMany)得到一个范围内的结果(分页),TopDocs的scoreDocs字段是结果ScoreDoc数组, ScoreDoc 的doc字段为Lucene.Net为文档分配的id(为降低内存占用,只先返回文档id),根据这个id调用searcher的Doc方法就能拿到Document了(放进去的是Document,取出来的也是Document);调用doc.Get("字段名")可以得到文档指定字段的值,注意只有Store.YES的字段才能得到,因为Store.NO的没有保存全部内容,只保存了分割后的词。
编写检索功能,搜索“网站 志愿者”。练习分词,用户不用空格。如果确定用盘古分词,那么用盘古的Segment类更方便。
检索不出来的可能的原因:路径问题,分词是否正确、盘古分词如果指定忽略大小写,则需要统一按照小写进行搜索
6.1示例代码:
string kw = Console.ReadLine();
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory,true);
IndexSearcher searcher = new IndexSearcher(reader);
PhraseQuery query = new PhraseQuery();
foreach (string word in kw.Split(' '))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("body", word));
}
query.SetSlop(100);
TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
searcher.Search(query, null, collector);
ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
for (int i = 0; i < docs.Length; i++)
{
int docId = docs[i].doc;
Document doc = searcher.Doc(docId);
Console.WriteLine(doc.Get("number"));
Console.WriteLine(doc.Get("body"));
}
七、网页采集
复习WebClient的用法,调用DownloadString方法下载页面。抓取DiscuzNT!的900至1000贴。乱码怎么办?乱码的唯一原因“编码不一致”。
WebClient抓取到的是页面的源代码,如何得到页面的标题、文字、超链接呢?
用mshtml进行html的解析,IE就是使用mshtml进行网页解析的。添加对Microsoft.mshtml的引用(如果是VS2010,修改这个引用的“嵌入互操作类型”为False。(*)“复制本地”设置为True、“特定版本”设置为False,这样在没有安装VS的机器中也可以用。)
- HTMLDocumentClass doc = new HTMLDocumentClass();
- doc.designMode = "on"; //不让解析引擎去尝试运行javascript
- doc.IHTMLDocument2_write(要解析的代码);
- doc.close();最后要关闭
- doc.title、doc.body.innerText,更多用法自己探索。
- 所有Dom方法都能在mshtml中调用
网页中解析出来的是html代码,如何只让它解析有意义的部分
方法1:doc.body.innerText,得到整个页面的文字信息。然后找特征值“介于【字体大小】和【收藏】之间的内容”,这是目前很多采集器的方案。“火车头采集器”、DEDEcms采集器等。存在的问题,必须找到确切的特征,否则可能会误判。
方法2:
- IHTMLElement firstpost = doc.getElementById("firstpost");
- if (firstpost != null)
- {
- Body = firstpost.innerText;
- }
- 补充:http://www.cnblogs.com/rupeng/archive/2010/06/29/1767933.html
备注
1、乱码解决方法:webClient.Encoding = Encoding.UTF8;
2、 mshtml及其他的HTML解析器 参考 http://www.cnblogs.com/rupeng/archive/2010/06/26/1765840.html
八、高亮显示
高亮显示,只显示包含关键词的部分。参考盘古分词的文档。
从网上、文档找来的代码不用细读每行代码,先把它拿过来运行通过再说。
不用每次改代码都重启,在项目的属性页面的Web中选中“启用编辑并继续(Enable Edit and Continue)”
8.1示例代码
private static String highLight(string keyword,String content)
{
PanGu.HighLight.SimpleHTMLFormatter formatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color='red'>", "</font>");
PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(formatter, new Segment());
highlighter.FragmentSize = 500;
string msg = highlighter.GetBestFragment(keyword,content);
if (string.IsNullOrEmpty(msg))
{
return content;
}
else
{
return msg;
}
}
调用:
String hightlightTitle = highLight(keyword, title);
String hightlightBody = HttpUtility.HtmlEncode(body);//防止XSS攻击
hightlightBody = highLight(keyword, hightlightBody);
九、重复索引
为什么不用每次索引之前清空索引库,因为时间很长,这段时间内用户就搜不到东西了。
在AddDocument之前先移除旧有文档:
indexWriter.DeleteDocuments(new Term("url", aurl));//删除旧的收录//注意DeleteDocuments不是静态方法
删除索引中所有url字段的值等于aurl的Document,相当于delete from tttt where url=@url。
易错:url不要设置Analized,否则DeleteDocuments会删不掉,因为把url当成一个词匹配了,当然没有。
异常处理!!!不要因为一个的异常导致整个索引失败。
最后:综合出完整的一个示例代码(用的是盘古分词):
第一部分
创建索引(以asp.net中一个按钮的点击事件为例)
protected void btn_SetSuoYin_Click(object sender, EventArgs e)
{
//用Log4Net记录日志(关于Log4Net参见上一篇文章)
ILog logger = LogManager.GetLogger(typeof(test_TestSearch));
//在C盘建立索引目录
string indexPath = "c:/index";
//在文件中创建索引(还可以在数据库中创建索引,参考前面第五节)
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
//检查目录是否被锁定,如果锁定了,则先解锁
bool isUpdate = IndexReader.IndexExists(directory);
if (isUpdate)
{
//如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
if (IndexWriter.IsLocked(directory))
{
IndexWriter.Unlock(directory);
}
}
//创建一个写入的对象(其中有一个isUpdate参数,代表是否自动创建)
IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
//创建WebClient对象,用于从
WebClient wc = new WebClient();
//指写编码类型,否则会出现乱码
wc.Encoding = Encoding.UTF8;
//从RSS中获取最大贴子的ID
int maxId = GetMaxId();
for (int i = 1; i < maxId; i++)
{
//每次重新建立索引之前,都先把之前建立的删除。(因为没有update方法,所以先删除,再添加)
//注意:不能先一次性把所有的索引全部删除掉,然后再建立,因为建立的时间很长,会造成这一段时间内,用户无法搜索
writer.DeleteDocuments(new Term("number", i.ToString()));
string url = "http://localhost:8080/showtopic-" + i + ".aspx";
string html = wc.DownloadString(url);
//为了只检索贴子有意义的那部分,这里引用的是Html解析器(IE就是用的这个解析器)
HTMLDocumentClass doc = new HTMLDocumentClass();
doc.designMode = "on"; //不让解析引擎去尝试运行javascript
doc.IHTMLDocument2_write(html);
doc.close();//最后要关闭
string title = doc.title;
string body = doc.body.innerText;
//文档对象,就相当于一个数据库表,用document.add 加入的就是每一个字段
Document document = new Document();
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, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(document);
logger.Debug("索引" + i + "完毕");
}
logger.Debug("全部索引完毕");
writer.Close();
directory.Close();//不要忘了Close,否则索引结果搜不到
}
从rss中获取最大贴子的ID(RSS中是最新的贴子,最新帖子的ID也就是最大的)
private int GetMaxId()
{
XDocument xdoc = XDocument.Load("http://localhost:8080/tools/rss.aspx");
XElement channel = xdoc.Root.Element("channel");
XElement firsItem = channel.Elements("item").First();
XElement link = firsItem.Element("link");
string url = link.Value;
Match match = Regex.Match(url, @"showtopic-(\d+)\.aspx");
int maxId = 1000;//默认先设置成1000;
if (match.Success)
{
maxId = Convert.ToInt32(match.Groups[1].Value);
}
return maxId;
}
第二部分:
开始检索(以一个文本框为输入点击一个按键进行搜索):
protected void btn_search_Click(object sender, EventArgs e)
{
string indexPath = "c:/index";
//从用户的输入获取关键字
string kw = txb_words.Text;
//打开索引库,创建读操作对象
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory, true);
IndexSearcher searcher = new IndexSearcher(reader);
PhraseQuery query = new PhraseQuery();
//盘古分词检索
Analyzer analyzer = new PanGuAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(this.txb_words.Text));
Lucene.Net.Analysis.Token token = null;
while ((token = tokenStream.Next()) != null)
{
query.Add(new Term("body", token.TermText()));
}
query.SetSlop(100);//分词后的两个关键词之前最大可以间隔100个不相关的字
TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
searcher.Search(query, null, collector);
//两个参数,起始行数与一页中一共有多少条数据。
ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
//这个地方的contentModel是外部的一个类,相当于三层架构中的model
List<contentModel> contentList = new List<contentModel>();
for (int i = 0; i < docs.Length; i++)
{
int docId = docs[i].doc;
Document doc = searcher.Doc(docId);//根据ID查找DOC
String hightlightTitle = highLight(txb_words.Text, doc.Get("title"));
String hightlightBody = HttpUtility.HtmlEncode(doc.Get("body"));//防止XSS攻击
hightlightBody = highLight(txb_words.Text, hightlightBody);
contentModel cm = new contentModel();
cm.Number = doc.Get("number");
cm.Title = hightlightTitle;
cm.Body = hightlightBody;
contentList.Add(cm);
}
前台放一个repeater进行呈现
Repeater1.DataSource = contentList;
Repeater1.DataBind();
}
前台放repeater的代码:
<ul style=" list-style:none">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li>
<a href='http://localhost:8080/showtopic-<%#Eval("Number") %>.aspx'><%#Eval("Title") %></a>
</li>
<li>
<%#Eval("Body") %>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
最后放上效果图一张:

以上资料来自杨老师的PPT

浙公网安备 33010602011771号