Lucene.Net3.0.3+Apsara Distributed File System分詞器學習使用

來源:互聯網
上載者:User

標籤:title   條件   --   stat   where   多個   hits   card   tle   

一、Lucene.Net介紹                                                                                                

  Lucene.net是Lucene的.net移植版本,是一個開源的全文檢索索引引擎開發包,即它不是一個完整的全文檢索索引引擎,而是一個全文檢索索引引擎的架構,提供了完整的查詢引擎和索引引擎。開發人員可以基於Lucene.net實現全文檢索索引的功能。   

  Lucene.net是Apache軟體基金會贊助的開源項目,基於Apache License協議。   

  Lucene.net並不是一個爬行搜尋引擎,也不會自動地索引內容。我們得先將要索引的文檔中的文本抽取出來,然後再將其加到Lucene.net索引中。標準的步驟是先初始化一個Analyzer、開啟一個IndexWriter、然後再將文檔一個接一個地加進去。一旦完成這些步驟,索引就可以在關閉前得到最佳化,同時所做的改變也會生效。這個過程可能比開發人員習慣的方式更加手工化一些,但卻在資料的索引上給予你更多的靈活性。

二、Apsara Distributed File System分詞器                                        

Apsara Distributed File System分詞是一個中英文分片語件。作者eaglet 曾經開發過KTDictSeg 中文分片語件,擁有大量使用者。作者基於之前分片語件的開發經驗,結合最新的開發技術重新編寫了Apsara Distributed File System分片語件。主要有以下功能:

1、中文未登陸詞識別

2、詞頻優先

3、一元分詞,多元分詞

4、中文人名分詞

5、繁體中文分詞

6、英文分詞

7、使用者自訂規則(字典管理,動態載入字典,關鍵詞高亮)

......

三、安裝                                       

 

 

 四、程式碼分析                                    
1.初始化Apsara Distributed File System分詞的xml引用路徑
        /// <summary>        /// 初始化Apsara Distributed File System分詞的xml引用路徑        /// </summary>        /// <param name="PanGuXmlPath"></param>        public static void InitPanGuXmlPath(string PanGuXmlPath)        {            //定義Apsara Distributed File System分詞的xml引用路徑            PanGu.Segment.Init(PanGuXmlPath);        }    
2.建立索引
        /// <summary>        /// 建立索引        /// </summary>        /// <param name="IndexDic">目錄位址</param>        /// <param name="isCreate">是否重新建立</param>        public static void CreateIndex(string IndexDic, bool isCreate)        {            try            {                //建立索引目錄                if (!System.IO.Directory.Exists(IndexDic))                {                    System.IO.Directory.CreateDirectory(IndexDic);                }                FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NativeFSLockFactory());                //IndexReader:對索引庫進行讀取的類                bool isExist = IndexReader.IndexExists(directory);                //是否存在索引庫檔案夾以及索引庫特徵檔案                if (isExist)                {                    //如果索引目錄被鎖定(比如索引過程中程式異常退出或另一進程在操作索引庫),則解鎖                    //Q:存在問題 如果一個使用者正在對索引庫寫操作 此時是上鎖的 而另一個使用者過來操作時 將鎖解開了 於是產生衝突 --解決方案後續                    if (IndexWriter.IsLocked(directory))                    {                        IndexWriter.Unlock(directory);                    }                }                //IndexWriter第三個參數:true指重新建立索引,false指從當前索引追加....此處為建立索引所以為true                IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), isCreate, Lucene.Net.Index.IndexWriter.MaxFieldLength.LIMITED);                for (int i = 1; i < 150; i++)                {                    //這裡是測試資料                    AddIndex(writer, "我的標題" + i, i + "標題內容是飛大師傅是地方十大飛啊的飛是 安撫愛上地方 愛上地方" + i, DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"));                    AddIndex(writer, "射鵰英雄傳作者金庸" + i, i + "我是歐陽鋒" + i, DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"));                    AddIndex(writer, "天龍八部2" + i, i + "慕容廢墟,上官靜兒,打撒飛艾絲凡愛上,虛竹" + i, DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"));                    AddIndex(writer, "倚天屠龍記2" + i, i + "張無忌機" + i, DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"));                    AddIndex(writer, "三國演義" + i, i + "劉備,張飛,關羽" + i, DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"));                }                writer.Optimize();                writer.Dispose();            }            catch (Exception ex)            {                throw;            }        }

 

private static void AddIndex(IndexWriter writer, string title, string content, string date)        {            try            {                Document doc = new Document();                doc.Add(new Field("Title", title, Field.Store.YES, Field.Index.NOT_ANALYZED));//儲存且索引                doc.Add(new Field("Content", content, Field.Store.YES, Field.Index.ANALYZED));//儲存且索引                doc.Add(new Field("AddTime", date, Field.Store.YES, Field.Index.NOT_ANALYZED));//儲存且索引                writer.AddDocument(doc);            }            catch (FileNotFoundException fnfe)            {                throw fnfe;            }            catch (Exception ex)            {                throw ex;            }        }

索引器的建構函式參數說明:

IndexDic是索引存放目錄

PanGuAnalyzer是Apsara Distributed File System解析器(由於預設的解析器解析能力不強,所以替換為這個)

IsCreate是索引建立方式(true:重新建立索引,false:從舊的索引執行追加)

Lucene.Net.Index.IndexWriter.MaxFieldLength.LIMITED是檔案長度是否限制

 

3.索引產生的檔案

4.根據關鍵字搜尋

lucene的搜尋相當強大,它提供了很多輔助查詢類,每個類都繼承自Query類,各自完成一種特殊的查詢,你可以像搭積木一樣將它們任意組合使用,完成一些複雜操 作;另外lucene還提供了Sort類對結果進行排序,提供了Filter類對查詢條件進行限制。你或許會不自覺地拿它跟SQL語句進行比 較:“lucene能執行and、or、order by、where、like ‘%xx%’操作嗎?”回答是:“當然沒問題!”

     /// <summary>        /// 從索引搜尋結果        /// </summary>        public static List<Article> SearchIndex(string content, string IndexDic)        {            Dictionary<string, string> dic = new Dictionary<string, string>();            try            {                FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NoLockFactory());                IndexReader reader = IndexReader.Open(directory, true);                IndexSearcher search = new IndexSearcher(reader);                string[] fields = { "Content" };                //建立查詢                PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new PanGuAnalyzer());                wrapper.AddAnalyzer("Content", new PanGuAnalyzer());                QueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, fields, wrapper);                Query query = parser.Parse(content);                TopScoreDocCollector collector = TopScoreDocCollector.Create(10, true);//10--查詢條數                search.Search(query, collector);                var hits = collector.TopDocs().ScoreDocs;                int numTotalHits = collector.TotalHits;                List<Article> list = new List<Article>();                for (int i = 0; i < hits.Length; i++)                {                    var hit = hits[i];                    Document doc = search.Doc(hit.Doc);                    Article model = new Article()                    {                        Title = doc.Get("Title").ToString(),                        Content = doc.Get("Content").ToString(),                        AddTime = doc.Get("AddTime").ToString()                    };                    list.Add(model);                    //list.Add(SetHighlighter(dicKeywords, model));                }                return list;            }            catch (Exception ex)            {                throw;            }        }

介紹各種Query

TermQuery: 首先介紹最基本的查詢,如果你想執行一個這樣的查詢:在content欄位中查詢包含‘劉備的document”,那麼你可以用TermQuery

BooleanQuery :如果你想這麼查詢:在content欄位中包含”劉備“並且在title欄位包含”三國“的document”,那麼你可以建立兩個TermQuery並把它們用BooleanQuery串連起來:

WildcardQuery :如果你想對某單詞進行萬用字元查詢,你可以用WildcardQuery,萬用字元包括’?’匹配一個任一字元和’*’匹配零個或多個任一字元,例如你搜尋’三國*’,你可能找到’三國演義’或者’三國志’

PhraseQuery :你可能對中日關係比較感興趣,想尋找‘中’和‘日’挨得比較近(5個字的距離內)的文章,超過這個距離的不予考慮,

PrefixQuery :如果你想搜以‘中’開頭的詞語,你可以用PrefixQuery:

FuzzyQuery :FuzzyQuery用來搜尋相似的term,使用Levenshtein演算法。

RangeQuery: 另一個常用的Query是RangeQuery,你也許想搜尋時間域從20060101到20060130之間的document,你可以用RangeQuery

Lucene.Net3.0.3+Apsara Distributed File System分詞器學習使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.