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();
}
}