您的位置:首页 > 其它

Lucene.Net核心类简介,创建索引,搜索,Lucene高亮组建演示,Rss获得最新帖子,只索引帖子的有意义部分,在AddDocument之前先移除旧有文档.

2011-05-19 00:37 645 查看
Directory表示索引文件(Luncene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirector(文件中),RAMDirectory(内存中).

创建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(Director dir,Analyzer a,bool create,MaxFieldLength mfl)因为indexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件.

void AddDocument(Document doc),向索引中添加文档(insert).Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一跳记录,Field相当于字段.

Fileld类的构造函数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.

 private ILog logger = LogManager.GetLogger(typeof(text_创建索引));
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
// 1、对数据进行索引
string indexPath = "c:/ceshi";
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);
WebClient wc = new WebClient();
//wc.Encoding = Encoding.UTF8;//否则可能会有乱码问题!!
int maxId = GetMaxId();
for (int i = 1; i < maxId; i++)
{
string url = "http://www.discuz.net/thread-" + i + "-1-1.html";
string html = wc.DownloadString(url);
HTMLDocumentClass doc = new HTMLDocumentClass();
doc.designMode = "on"; //不让解析引擎去尝试运行javascript
doc.IHTMLDocument2_write(html);
string title = doc.title;
string body = doc.body.innerText;//去掉标签
//为避免重复索引,所以先删除number=i的记录,再重新添加.
writer.DeleteDocuments(new Term("number", i.ToString()));
Document document = new Document();
//只有对需要全文检索的字段才ANALYZED
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.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
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 + "完毕"));
}

writer.Close();
directory.Close();//不要忘了Close,否则索引结果搜不到
logger.Debug("全部索引完毕!");

}
protected void Button2_Click(object sender, EventArgs e)
{
string indexPath = "c:/ceshi";
string kw = TextBox1.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();
foreach (string word in CommonHelper.SplitWord(TextBox1.Text))//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
{
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;
List<SearchResult> listResult = new List<SearchResult>();

for (int i = 0; i < docs.Length; i++)
{
//取到文档的编号(主键,这个是Luncene.net分配的)
int docId = docs[i].doc;
//检索结果中只有文档的id,如果要取Document,则需要Doc再去取
//降低内容占用
Document doc = searcher.Doc(docId);

string number = doc.Get("number");
string title = doc.Get("title");
string body = doc.Get("body");
SearchResult result = new SearchResult();
result.Number = number;
result.Title = title;
//高亮--------------------------------------
//创建HTMLFormatter,参数为高亮单词的前后缀
PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter =
new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>");
//创建Highlighter ,输入HTMLFormatter 和盘古分词对象Semgent
PanGu.HighLight.Highlighter highlighter =
new PanGu.HighLight.Highlighter(simpleHTMLFormatter,
new Segment());
//设置每个摘要段的字符数
highlighter.FragmentSize = 50;
//获取最匹配的摘要段
String bodyPreview = highlighter.GetBestFragment(TextBox1.Text, body);
result.BodyPreview = bodyPreview;
Response.Write(number + "<br/>");
Response.Write(title + "<br/>");
Response.Write("<hr/>");
listResult.Add(result);
}
Repeater1.DataSource = listResult;
Repeater1.DataBind();

}
private int GetMaxId()
{
XDocument xdoc = XDocument.Load("http://www.discuz.net/forum.php?mod=rss&fid=21&auth=0");
XElement channel = xdoc.Root.Element("channel");
XElement firstItem = channel.Elements("item").First();
XElement link = firstItem.Element("link");
Match match = Regex.Match(link.Value, @"viewthread&tid=(\d+)\\");
string id = match.Groups[1].Value;
return Convert.ToInt32(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的没有保存全部内容,只保存了分割后的词。
检索不出来的可能的原因:路径问题,分词是否正确、盘古分词如果指定忽略大小写,则需要统一按照小写进行搜索

网页采集
WebClient抓取到的是页面的源代码,如何得到页面的标题、文字、超链接呢?
用mshtml进行html的解析,IE就是使用mshtml进行网页解析的。添加对Microsoft.mshtml的引用(如果是VS2010,修改这个引用的“嵌入互操作类型”为False。(*)“复制本地”设置为True、“特定版本”设置为False,这样在没有安装VS的机器中也可以用。)
HTMLDocumentClass doc = new HTMLDocumentClass();
doc.designMode = "on"; //不让解析引擎去尝试运行javascript
doc.IHTMLDocument2_write(要解析的代码);
doc.title、doc.body.innerText,更多用法自己探索。
所有Dom方法都能在mshtml中调用

解决: 最大帖子编号
最大贴,可以读取rss的内容:tools/rss.aspx,使用Linq To XML分析RSS。
最大帖子编号:因为RSS中就是最新帖子信息,所以读取RSS的一个item的link就是帖子地址,用正则表达式就可以分析出最大帖子编号

解决:只索引帖子的有意义部分
方法1:doc.body.innerText,得到整个页面的文字信息。然后找特征值“介于【字体大小】和【收藏】之间的内容”,这是目前很多采集器的方案。“火车头采集器”、DEDEcms采集器等。存在的问题,必须找到确切的特征,否则可能会误判。
方法2:
IHTMLElement firstpost = doc.getElementById("firstpost");
if (firstpost != null)
{
Body = firstpost.innerText;
}
补充:/article/4807414.html

为什么不用每次索引之前清空索引库,因为时间很长,这段时间内用户就搜不到东西了。
在AddDocument之前先移除旧有文档:
indexWriter.DeleteDocuments(new Term("url", aurl));//删除旧的收录//注意DeleteDocuments不是静态方法
删除索引中所有url字段的值等于aurl的Document,相当于delete from tttt where url=@url

易错:url不要设置Analized,否则DeleteDocuments会删不掉,因为把url当成一个词匹配了,当然没有。
异常处理!!!不要因为一个的异常导致整个索引失败。

加空格:

 public class CommonHelper
{
public static string[] SplitWord(string str)
{
List<string> list = new List<string>();
Analyzer analyzer = new PanGuAnalyzer();
// Analyzer analyzer = new CJKTokenizer();
// Analyzer analyzer = new StandardAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(str));
Lucene.Net.Analysis.Token token = null;
while ((token = tokenStream.Next()) != null)
{
list.Add(token.TermText() );
}
return list.ToArray();
}
}


 public class SearchResult
{
public string Number { get; set; }
public string Title { get; set; }
public string BodyPreview { get;set;}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐