这部分包含对文本的索引生成以及对数据库数据的索引生成,下面只对数据库索引生成的关键代码进行介绍:
下面这段代码实现对数据库里存储的记录创建索引。主要通过Lucene提供的方法来协助实现。
public Indexer(string indexDir)
IndexWriter writer = new IndexWriter(indexDir, new StandardAnalyzer(), true);
在创建索引库时,会合并多个Segments文件。此方式有助于减少索引文件数量,减少同时打开的文件数量。
writer.SetUseCompoundFile(false);
System.IO.Directory.Delete(iDexDir,true);
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
int docNum = writer.DocCount();
Console.WriteLine("Index Finished. {0} Documents takes {1} second.",
docNum, ((TimeSpan)(end - start)).TotalSeconds);
使用Lucene提供的方法对数据库中的每条记录建立索引实现如下:
Document doc = new Document();
Console.WriteLine("Indexing {0} ", row["title"].ToString());
doc.Add(Field.Text("contents", row["content"].ToString()));
doc.Add(Field.Keyword("title", row["title"].ToString()));
doc.Add(Field.Keyword("mata",row["mata"].ToString()));
doc.Add(Field.Keyword("CreateDate",row["CreateDate"].ToString()));
doc.Add(Field.Keyword("Url",row["Url"].ToString()));
doc.Add(Field.Keyword("ID",row["ID"].ToString()));