1

如何在 lucene 全文搜索引擎中实现 Did You Mean 和 Spellchecker 功能。

4

1 回答 1

3

创建索引后,您可以使用拼写检查器使用的字典创建索引:

public void createSpellChekerIndex() throws CorruptIndexException,
        IOException {
    final IndexReader reader = IndexReader.open(this.indexDirectory, true);
    final Dictionary dictionary = new LuceneDictionary(reader,
            LuceneExample.FIELD);
    final SpellChecker spellChecker = new SpellChecker(this.spellDirectory);
    final Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
    final IndexWriterConfig writerConfig = new IndexWriterConfig(
            Version.LUCENE_36, analyzer);
    spellChecker.indexDictionary(dictionary, writerConfig, true);
    spellChecker.close();
}

而不是要求一个建议数组:

public String[] getSuggestions(final String queryString,
        final int numberOfSuggestions, final float accuracy) {
    try {
        final SpellChecker spellChecker = new SpellChecker(
                this.spellDirectory);
        final String[] similarWords = spellChecker.suggestSimilar(
                queryString, numberOfSuggestions, accuracy);
        return similarWords;
    } catch (final Exception e) {
        return new String[0];
    }
}

示例:索引以下文档后:

    luceneExample.index("spell checker");
    luceneExample.index("did you mean");
    luceneExample.index("hello, this is a test");
    luceneExample.index("Lucene is great");

并使用上述方法创建拼写索引,我尝试搜索字符串“lucete”,并寻求建议

 final String query = "lucete";
 final String[] suggestions = luceneExample.getSuggestions(query, 5,
            0.2f);
 System.out.println("Did you mean:\n" + Arrays.toString(suggestions));

这是输出:

Did you mean:
[lucene]
于 2013-09-24T06:49:04.740 回答