2017-06-12 29 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是類的實例字段。

相關問題