摘要:Lucene.Net 使用RAMDirectory 建立 Index
2015/1/21 更新
Lucene.Net 除了能夠將 Index 建立在硬碟上面 , 同時擁有將 Index
建立在記憶體裡面的能力 , 在存取及建立 Index 的速度也比建立在
硬碟上的 Index 更快 , 但是仍要考慮系統的單一 Process 有記憶體上的限制 ,
網路上有許多討論的文章 , 其中將其當作 測試的用途居多 , 請參考下列網址 :
http://stackoverflow.com/questions/673887/using-ramdirectory
http://stackoverflow.com/questions/1582377/need-to-know-pros-and-cons-of-using-ramdirectory
筆者認為在系統初始化時 , 可能需要載入一些初始值 , 我們可以利用
RAMDirectory ( Directory dir ) 這個建構子將我們硬碟上的 Index 放入到記憶體上面運作 , 會是不錯的做法
How to Build Index :
static RAMDirectory dir = new RAMDirectory();
private void BuildIndex() {
IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30),true, IndexWriter.MaxFieldLength.UNLIMITED);
for (int i = 1; i <= 1000; i++) {
Document doc = new Document();
Field field = new Field("ID", Guid.NewGuid().ToString(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO);
Field field2 = new Field("Name", "holmes" + i.ToString(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO);
doc.Add(field);
doc.Add(field2);
iw.AddDocument(doc);
}
iw.Optimize();
iw.Commit();
iw.Close();
}
How to search Index :
public void Search(string KeyWord)
{
IndexSearcher search = new IndexSearcher(dir, true);
QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Name", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30));
Query query = parser.Parse(KeyWord);
var hits = search.Search(query, null, search.MaxDoc).ScoreDocs;
foreach (var res in hits)
{
Response.Write(string.Format("ID:{0} / DESC:{1}"
, search.Doc(res.Doc).Get("ID").ToString()
, search.Doc(res.Doc).Get("Name").ToString() + "
"));
}
}
protected void Page_Load(object sender, EventArgs e)
{
BuildIndex();
Search("holm*");
}