了解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
是类的实例字段。