2017-06-12 92 views
2

我使用Lucene 6.5.1构建了一个建议API。如何在Lucene中添加单词PlainTextDictionary

我的想法是先建立一个基线字典 - org.apache.lucene.search.spell.Dictionary使用文本文件 - org.apache.lucene.search.spell.PlainTextDictionary但在字典中的单词列表不应该停在那里。

我需要一个终点来添加/附加新单词到这个基线字典,例如,如果在我的初始文本文件中没有遗漏任何单词并且某些用户想要添加它,则他/她应该能够通过提供List<String>使用服务终点来完成该操作。可能有无数的其他原因为现有词典添加一个词。

我无法找到任何直接的方法来实现,使用SpellChecker类。

请建议。

使用SOLR不是这里的一个选项。

回答

0

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