2013-05-16 156 views
1

我有一個網站給用戶提供數據。我想爲我的自動完成使用Lucene.Net。事情是我想能夠返回正確拼寫錯誤的結果。我發現Lucene.Net具有拼寫檢查功能,可以顯示其他詞語。但它返回的話,我需要的ID,以獲得更多的信息該項目。當我從拼寫檢查器得到結果後還需要對常規索引執行另一個查詢嗎?還是有更好的方法?C#Lucene.Net拼寫檢查器

回答

3

您將需要搜索它,它不能這樣做,因爲拼寫檢查工作在與您沒有鏈接的單獨索引上主要索引您創建的建議。

它很容易做到壽:

RAMDirectory dir = new RAMDirectory(); 
IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED); 

Document d = new Document(); 
Field textField = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED); 
d.Add(textField); 
Field idField = new Field("id", "", Field.Store.YES, Field.Index.NOT_ANALYZED); 
d.Add(idField); 

textField.SetValue("this is a document with a some words"); 
idField.SetValue("42"); 
iw.AddDocument(d); 

iw.Commit(); 
IndexReader reader = iw.GetReader(); 

SpellChecker.Net.Search.Spell.SpellChecker speller = new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory()); 
speller.IndexDictionary(new LuceneDictionary(reader, "text")); 
string [] suggestions = speller.SuggestSimilar("dcument", 5); 


IndexSearcher searcher = new IndexSearcher(reader); 
foreach (string suggestion in suggestions) 
{ 
    TopDocs docs = searcher.Search(new TermQuery(new Term("text", suggestion)), null, Int32.MaxValue); 
    foreach (var doc in docs.ScoreDocs) 
    { 
     Console.WriteLine(searcher.Doc(doc.Doc).Get("id")); 
    } 
} 

reader.Dispose(); 
iw.Dispose(); 
+0

你的答案看起來有趣,易於實現。當試圖得到一些錯誤,如:「類型'Lucene.Net.Store.Directory'是在未引用的程序集中定義的。您必須添加對程序集'Lucene.Net,Version = 2.0.0.4的引用, Culture = neutral,PublicKeyToken = null'「。和「不能從'Lucene.Net.Store.RAMDirectory'轉換爲Lucene.Net.Store.Directory'」。我正在引用lucene.net版本3.0.3.0。有任何想法嗎? – Gidi

+0

好像你在引用衝突的程序集,嘗試刪除所有引用,並得到Lucene.Net 3.0.3和Lucene.Net 3.0.3 Contrib,並做一個乾淨的重建。我建議你從Nuget獲得程序集。我用nuget構建了3.0.3的例子 –

+0

好吧,我修正了這個問題。我不明白你爲什麼需要「RAMDirectory dir = new RAMDirectory();」我看不到你用它。它是否必須指向索引目錄?我試過這樣,它返回空結果。 – Gidi