1.使用定时框架Quartz.Net创建索引库,引用类库文件有Common.Logging.dll、Lucene.Net.dll,PanGu.dll,PanGu.HighLight.dll,PanGu.Lucene.Analyzer.dll,Quartz.dll
public class IndexJob:IJob
{
public void Execute(JobExecutionContext context)
{
//第一个版本应该保存body和title,搜索结果形成超链接,不显示正文。
string indexPath = "e:/index";
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;//否则下载的是乱码
//todo:读取rss,获得第一个item中的链接的编号部分就是最大的帖子编号
List<string> listUrl = new List<string>();
listUrl.Add("http://www.baidu.com");
listUrl.Add("http://www.google.com.cn");
listUrl.Add("http://cn.bing.com/");
for (int i = 0; i < listUrl.Count; i++)
{
string url = listUrl[i];
string html = wc.DownloadString(url);
try
{
html = wc.DownloadString(url);
}
catch (WebException ex)
{
//写入错误日志或者重新请求下载
html = wc.DownloadString(url);
}
HTMLDocumentClass doc = new HTMLDocumentClass();
doc.designMode = "on"; //不让解析引擎去尝试运行javascript
doc.IHTMLDocument2_write(html);
doc.close();
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("url", url, 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);
}
writer.Close();
directory.Close();//不要忘了Close,否则索引结果搜不到
}
2.在Glabal.asax.cs文件中初始化并启动和关闭定时操作
private IScheduler sched;
protected void Application_Start(object sender, EventArgs e)
{
//每隔一段时间执行任务
ISchedulerFactory sf = new StdSchedulerFactory();
sched = sf.GetScheduler();
JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob为实现了IJob接口的类
DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);//5秒后开始第一次运行
// TimeSpan interval = TimeSpan.FromHours(1);//每隔1小时执行一次
//Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null,
// SimpleTrigger.RepeatIndefinitely, interval);//每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定
Trigger trigger = TriggerUtils.MakeDailyTrigger("trigger1", 11, 56);
trigger.JobName = "job1";
trigger.JobGroup = "group1";
trigger.Group = "group1";
sched.AddJob(job, true);
sched.ScheduleJob(trigger);
sched.Start();
}
protected void Application_End(object sender, EventArgs e)
{
// 要关闭任务定时则需要
sched.Shutdown(true);
}
3.从创建的索引文件中读取数据
protected void Button3_Click(object sender, EventArgs e)
{
string indexPath = "e:/index";
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();
//todo:把用户输入的关键词进行拆词
foreach (string word in CommonHelper.SplitWord(TextBox1.Text))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("body", word));
}
//query.Add(new Term("body","计算机"));
//query.Add(new Term("body", "专业"));
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++)
{
int docId = docs[i].doc;//取到文档的编号(主键,这个是Lucene .net分配的)
//检索结果中只有文档的id,如果要取Document,则需要Doc再去取
//降低内容占用
Document doc = searcher.Doc(docId);//根据id找Document
string number = doc.Get("number");
string url = doc.Get("url");
string title = doc.Get("title");
string body = doc.Get("body");
SearchResult result = new SearchResult();
result.Number = number;
result.Title = title;
result.Url = url;
result.BodyPreview = Preview(body, TextBox1.Text);
listResult.Add(result);
}
repeaterResult.DataSource = listResult;
repeaterResult.DataBind();
}
private static string Preview(string body, string keyword)
{
//创建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 = 100;
//获取最匹配的摘要段
String bodyPreview = highlighter.GetBestFragment(keyword, body);
return bodyPreview;
}
public class SearchResult
{
public string Number { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string BodyPreview { get; set; }
}
public class CommonHelper
{
public static string[] SplitWord(string str)
{
List<string> list = new List<string>();
Analyzer analyzer = new PanGuAnalyzer();
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();
}
}
directory =FSDirectory.Open(newDirectoryInfo(indexPath),newNativeFSLockFactory()),
path索引的文件夹路径
IndexExists(Directory
directory)判断目录directory是否是一个索引目录。IndexWriter的bool
IsLocked(Directory
directory)判断目录是否锁定,在对目录写之前会先把目录锁定。两个IndexWriter没法同时写一个索引文件。IndexWriter在进行写操作的时候会自动加锁,close的时候会自动解锁。IndexWriter.Unlock方法手动解锁(比如还没来得及closeIndexWriter程序就崩溃了,可能造成一直被锁定)。
create,MaxFieldLengthmfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。
create,MaxFieldLengthmfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。
Field(string name, string value,Field.Storestore,Field.Indexindex,
Field.TermVectortermVector):
name表示字段名;value表示字段值;
index表示如何创建索引,可选值Field.Index. NOT_ANALYZED
为什么要把帖子的url做为一个Field,因为要在搜索展示的时候先帖子地址取出来构建超链接,所以Field.Store.YES;一般不需要对url进行检索,所以Field.Index.NOT_ANALYZED
Filterfilter,
Collector results)方法用来搜索,Query是查询条件,
filter目前传递null,
results是检索结果,TopScoreDocCollector.create(1000, true)方法创建一个Collector,1000表示最多结果条数,Collector就是一个结果收集器。
PhraseQuery用来进行多个关键词的检索,调用Add方法添加关键词,query.Add(new Term("字段名",关键词)),PhraseQuery.
SetSlop(int
slop)用来设置关键词之间的最大距离,默认是0,设置了Slop以后哪怕文档中两个关键词之间没有紧挨着也能找到。
调用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的没有保存全部内容,只保存了分割后的词。
doc = new HTMLDocumentClass();
SELECT KeyWord,count(*)
SearchCount FROM so_KeywordLog where KeyWord
like @kw and datediff(day,searchdatetime,getdate())<7 group byKeyWord order by count(*) desc