瞭解Document
結構是關鍵。我簡單地複製了SpellChecker
類(getMin
,getMax
,createDocument
& addGram
)的四種私有方法,並寫下類似如下的內容。
我不確定它的100%正確,但它的添加單詞和添加的單詞在匹配中返回。
@Override
public Boolean addWords(Set<String> words) throws IOException{
synchronized(modifyCurrentIndexLock){
IndexWriterConfig wConfig = new IndexWriterConfig(new SimpleAnalyzer());
wConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
try(Directory spellIndex = FSDirectory.open(new File(indexLocation).toPath());
SpellChecker spellchecker = new SpellChecker(spellIndex);
IndexWriter writer = new IndexWriter(spellIndex, wConfig);)
{
for(String word:words){
if(!spellchecker.exist(word)){
logger.debug("Word -> "+word +" doesn't exist in dictionary to trying to add to index");
Document doc = createDocument(word, getMin(word.length()), getMax(word.length()));
writer.addDocument(doc);
writer.commit();
}
}
logger.debug("All valid words added to dictionary");
return true;
}
}
}
其中,
indexLocation
& modifyCurrentIndexLock
是類的實例字段。