標籤:
Lucene是Apache發布的開源搜尋引擎開發套件,不僅提供了核心的搜尋功能,還提供了許多其他功能外掛程式,例如:拼字檢查功能模組。
搜尋拼字檢查模組實作類別在lucene-suggest-x.xx.x.jar包中,package名為org.apache.lucene.search.spell,其中拼字檢查功能的核心實現有3個類,
分別為:SpellChecker、DirectSpellChecker、WordBreakSpellChecker;
3個類提供了不同的拼字檢查方式,區別如下:
SpellChecker:提供了原始的拼字檢查功能,在拼字檢查前需要重建立立索引(根據txt字典檔案建立索引或者已有索引檔案的某個欄位建立索引),然後才可以進行拼字檢查;
SpellChecker源碼分析查看如下網站:http://www.tuicool.com/articles/naIBjm
DirectSpellChecker:提供了改進的拼字檢查功能,可以直接利用已有索引檔案進行拼字檢查,不需要重建立立索引(solr系統預設採用此種方式進行拼字檢查);
WordBreakSpellChecker:也不需要重建立索引,可以利用已有索引進行拼字檢查。
SpellChecker使用:
建立索引有三種方式:
PlainTextDictionary:用txt檔案初始化索引
LuceneDictionary:用現有索引的某一個欄位初始化索引
HighFrequencyDictionary:用現有索引的某個欄位初始化索引,但每個索引條目必須滿足一定的出現率
1 //新索引目錄 2 String spellIndexPath = “D:\\newPath”; 3 //已有索引目錄 4 String oriIndexPath = "D:\\oriPath"; 5 //字典檔案 6 String dicFilePath = “D:\\txt\\dic.txt”; 7 8 //目錄 9 Directory directory = FSDirectory.open((new File(spellIndexPath)).toPath());10 11 SpellChecker spellChecker = new SpellChecker(directory);12 13 //以下幾步用來初始化索引14 IndexReader reader = DirectoryReader.open(FSDirectory.open((new File(oriIndexPath)).toPath()));15 //利用已有索引16 Dictionary dictionary = new LuceneDictionary(reader, fieldName);17 //或者利用txt字典檔案18 //Dictionary dictionary = new PlainTextDictionary((new File(dicFilePath)).toPath());19 IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());20 spellChecker.indexDictionary(dictionary, config, true);21 22 String queryWord = "beijink";23 int numSug = 10;24 //拼字檢查25 String[] suggestions = spellChecker.suggestSimilar(queryWord, numSug);26 27 reader.close();28 spellChecker.close();29 directory.close();
DirectSpellChecker使用:
1 DirectSpellChecker checker = new DirectSpellChecker();2 String readerPath = "D:\\path";3 IndexReader reader = DirectoryReader.open(FSDirectory.open(4 (new File(readerPath)).toPath()));5 Term term = new Term("fieldname", "querytext");6 int numSug = 10;7 SuggestWord[] suggestions = checker.suggestSimilar(term, numSug, reader);
lucene拼字檢查模組