使用Lucene.net進行全文尋找多關鍵字匹配

來源:互聯網
上載者:User

標籤:Lucene   blog   http   ar   io   os   使用   sp   for   

Lucene是一個開源的搜尋引擎,開發語言是Java,Lucene.net是它的.NET版本。可以在C#中方便的調用。

Lucene.net目前最新版本是3.0.3,你可以從官方網站下載到最新版本:http://lucenenet.apache.org/

使用Lucene.net進行全文尋找首先要根據資料建立索引,然後再根據索引來尋找關鍵字。本文不做任何原理性的解釋,需要深入研究的請自行Google之。

建立索引

還是直接上代碼的比較好:

            IndexWriter writer = new IndexWriter(FSDirectory.Open(new DirectoryInfo(indexDirectory)),                    analyzer, true, IndexWriter.MaxFieldLength.LIMITED);            for (int i = 0; i < files.Count(); i++)            {                FileInfo fileInfo = files[i];                StreamReader reader = new StreamReader(fileInfo.FullName);                OutputMessage("正在索引檔案[" + fileInfo.Name + "]");                Document doc = new Document();                doc.Add(new Field("FileName", fileInfo.Name, Field.Store.YES, Field.Index.ANALYZED));                doc.Add(new Field("Author", reader.ReadLine(), Field.Store.YES, Field.Index.ANALYZED));                doc.Add(new Field("Content", reader.ReadToEnd(), Field.Store.NO, Field.Index.ANALYZED));                doc.Add(new Field("Path", fileInfo.FullName, Field.Store.YES, Field.Index.NO));                writer.AddDocument(doc);                writer.Optimize();            }            writer.Dispose();

在上面的代碼中,我們對文字檔進行了索引,每一個檔案都儲存了FileName(檔案名稱)、Author(作者)、Content(內容)、Path(檔案路徑)幾個欄位。跟資料庫中的欄位很相似。

 

使用中文分詞

目前中文分詞有Lucene.Net.Analysis.Cn.ChineseAnalyzer 和Apsara Distributed File System分詞,我們在測試中使用前者,更方便我們做測試。

Lucene.Net.Analysis.Cn.ChineseAnalyzer包含在原始碼中,你可以把它複製到你的原始碼中,也可以編譯以後引用。我這裡為了方便,直接複製到原始碼中的。建議在實際使用的時候,編譯然後添加引用。

 

全文尋找

還是上代碼吧,看上去更直接。

            IndexReader reader = null;            IndexSearcher searcher = null;            try            {                reader = IndexReader.Open(FSDirectory.Open(new DirectoryInfo(indexDirectory)), true);                searcher = new IndexSearcher(reader);                //建立查詢                PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(analyzer);                wrapper.AddAnalyzer("FileName", analyzer);                wrapper.AddAnalyzer("Author", analyzer);                wrapper.AddAnalyzer("Content", analyzer);                string[] fields = {"FileName", "Author", "Content"};                QueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, fields, wrapper);                Query query = parser.Parse(keyword);                TopScoreDocCollector collector = TopScoreDocCollector.Create(num, true);                searcher.Search(query, collector);                var hits = collector.TopDocs().ScoreDocs;                int numTotalHits = collector.TotalHits;                OutputMessage("尋找 " + keyword + " ...共找到 " + numTotalHits + "個匹配的文檔");                //以後就可以對擷取到的collector資料進行操作                for (int i = 0; i < hits.Count(); i++)                {                    var hit = hits[i];                    Document doc = searcher.Doc(hit.Doc);                    Field fileNameField = doc.GetField("FileName");                    Field authorField = doc.GetField("Author");                    Field pathField = doc.GetField("Path");                    OutputMessage(fileNameField.StringValue + "[" + authorField.StringValue + "],匹配指數:" + Math.Round(hit.Score * 100, 2) + "%");                    OutputMessage(pathField.StringValue);                    OutputMessage(string.Empty);                }            }            finally            {                if (searcher != null)                    searcher.Dispose();                if (reader != null)                    reader.Dispose();            }

上面的這段代碼可以是實現多關鍵字的尋找。需要說明的是,貌似在得到檢索到的文檔的地方,跟之前的版本有一些不同(我拷貝別人的代碼沒辦法直接運行)……

另外,此處檢索的行數受到num的影響,但返回的總行數是不受影響的,如果需要得到總行數,可以在第一次檢索以後得到總行數,然後將總行數賦值給num,在進行新一次的檢索。

按照慣例,附上原始碼  

 

使用Lucene.net進行全文尋找多關鍵字匹配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.