IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(), true);
这个例子中我们总是重新创建索引(In this example we always create the index from scratch),但这不是必须的,你也可以打开一个已有的索引并添加文档进去。你还可以通过删除然后添加它们的新版本来更新现存的文档(译注:这里应该是指对象的创建)第2 - 12行:添加文档我们为每一个HTML文档添加两个字段到索引: "text" 字段,容纳HTML文件的文本内容(去除了标记),文本数据本身并不会存储在索引中 "path" 字段,容纳文件路径,它将会被(索引并)完整的存入索引中
public void AddHtmlDocument(string path)
{
Document doc = new Document();
string rawText;
using (StreamReader sr = new StreamReader(path, System.Text.Encoding.Default))
{
rawText = parseHtml(sr.ReadToEnd());
}
doc.Add(Field.UnStored("text", rawText));
doc.Add(Field.Keyword("path", path));
writer.AddDocument(doc);
}
第13 - 14行:优化并保存索引 添加完文档后,你需要关闭索引器。使用优化将会提高搜索性能。writer.Optimize();
writer.Close();
第15行:打开索引搜索在做任何搜索之前,你需要打开索引。directory参数是存储索引的目录路径。
IndexSearcher searcher = new IndexSearcher(directory);
第16 - 27行:搜索现在,我们解析查询了("text"是默认搜索字段)
Query query = QueryParser.Parse(q, "text", new StandardAnalyzer());
Hits hits = searcher.Search(query);
变量hits是搜索结果文档的集合,我们将通过它来将结果存储到DataTable
DataTable dt = new DataTable();
dt.Columns.Add("path", typeof(string));
dt.Columns.Add("sample", typeof(string));
for (int i = 0; i < hits.Length(); i++)
{
// get the document from index
Document doc = hits.Doc(i);
// get the document filename
// we can't get the text from the index because we didn't store it there
DataRow row = dt.NewRow();
row["path"] = doc.Get("path");
dt.Rows.Add(row);
}
第28 - 37行:高亮Lines 28 - 37: Query Highlighting 我们先创建一个高亮器对象highlighter,并将使用加黑(bold)字体来高亮显示(<B>查询词</B>)。
QueryHighlightExtractor highlighter = new
QueryHighlightExtractor(query, new StandardAnalyzer(), "<B>", "</B>");
通过对结果遍历,我们将载入原文中最相似的部分。
for (int i = 0; i < hits.Length(); i++)
{
// ...
string plainText;
using (StreamReader sr = new StreamReader(doc.Get("filename"),
System.Text.Encoding.Default))
{
plainText = parseHtml(sr.ReadToEnd());
}
row["sample"] = highlighter.GetBestFragments(plainText, 80, 2, "...");
// ...
}
资源DotLucene download Run DotLucene online demo DotLucene online demo notes DotLucene documentation