Lucene.Net 使用模糊搜尋

摘要:Lucene.Net 使用模糊搜尋

當我們想要搜尋 Lucene.Net 時 , 可是卻輸入錯誤的字串如 Luce.Net , 可是

 

搜尋結果仍然會出現 Lucene.Net 的搜尋結果 , Fuzzy Query 就是能找到相似度高的結果

 

在 Lucene.Net 裡面的 Fuzzy Query 就是達成這樣的事情 

 

Step 1 : Build RAMDirectory 

 

static RAMDirectory dir = new RAMDirectory();

 

Step 2 : Build Index

 

public void BuildIndex()
    {
        IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);

        Document doc = new Document();
        doc.Add(new Field("PROD_ID", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
        doc.Add(new Field("PROD_Name", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
        
        for (int i = 1; i <= 10; i++)
        {
            doc.GetField("PROD_ID").SetValue(Guid.NewGuid().ToString());
            doc.GetField("PROD_Name").SetValue("Lucene.Net" + i.ToString());
            iw.AddDocument(doc);
        }
        iw.Optimize();
        iw.Commit();
        iw.Close();
    }

 

Step 3 : Search 

 

private void Search(string KeyWord)
    {

        IndexSearcher search = new IndexSearcher(dir, true);

        QueryParser parser = new QueryParser(Version.LUCENE_30, "PROD_Name", new StandardAnalyzer(Version.LUCENE_30));

        parser.AllowLeadingWildcard = true;

        Query query = new FuzzyQuery(new Term("PROD_Name", KeyWord), 0.5F);

        var hits = search.Search(query, null, search.MaxDoc).ScoreDocs;

        foreach (var res in hits)
        {
            Response.Write(string.Format("PROD_ID:{0} / PROD_Name{1}"
                                        , search.Doc(res.Doc).Get("PROD_ID").ToString()
                                        , search.Doc(res.Doc).Get("PROD_Name").ToString() + "
"));
        }
    }

 

Step 4 : 執行

 

        BuildIndex();
        Search("Luce.net");

 

Result : 

 

當 Search 階段的 FuzzyQuery 第二個 minimumSimilarity 參數是 0.5 時 , 這時搜尋結果還是空白 , 

 

但是若是 輸入 0.4 時 , 這時候已經可以看到我們所建立的 Index 都還是被搜尋出來  , 

 

minimumSimilarity 參數值介於  0f ~ 1.0f 之間(等於1會 throw exception)  , 值越高則越要求字的相似度