尽管使用了 StopAnalyzer 和 StopFilter,Apache Lucene 不会过滤停用词

Apache Lucene doesn't filter stop words despite the usage of StopAnalyzer and StopFilter

我有一个基于 Apache Lucene 5.5 / 6.0 的模块可以检索关键字。一切正常,除了一件事——Lucene 不过滤停用词。

我尝试使用两种不同的方法启用停用词过滤。

方法 #1:

tokenStream = new StopFilter(new ASCIIFoldingFilter(new ClassicFilter(new LowerCaseFilter(stdToken))), EnglishAnalyzer.getDefaultStopSet());
tokenStream.reset();

方法#2:

tokenStream = new StopFilter(new ClassicFilter(new LowerCaseFilter(stdToken)), StopAnalyzer.ENGLISH_STOP_WORDS_SET);
tokenStream.reset();

完整代码可在此处获得:

我的问题:

  1. 为什么 Lucene 不过滤停用词?
  2. 如何在 Lucene 5.5 / 6.0 中启用停用词过滤?

刚刚测试了方法 1 和方法 2,它们似乎都可以很好地过滤掉停用词。以下是我的测试方式:

public static void main(String[] args) throws IOException, ParseException, org.apache.lucene.queryparser.surround.parser.ParseException 
{
     StandardTokenizer stdToken = new StandardTokenizer();
     stdToken.setReader(new StringReader("Some stuff that is in need of analysis"));
     TokenStream tokenStream;

     //You're code starts here
     tokenStream = new StopFilter(new ASCIIFoldingFilter(new ClassicFilter(new LowerCaseFilter(stdToken))), EnglishAnalyzer.getDefaultStopSet());
     tokenStream.reset();
     //And ends here

     CharTermAttribute token = tokenStream.getAttribute(CharTermAttribute.class);
     while (tokenStream.incrementToken()) {
         System.out.println(token.toString());
     }
     tokenStream.close();
}

结果:

some
stuff
need
analysis

这消除了我样本中的四个停用词。

陷阱在默认的 Lucene 停用词列表中,我预料到了,它要广泛得多。

这是默认尝试加载自定义停用词列表的代码,如果失败则使用标准停用词列表:

CharArraySet stopWordsSet;

try {
    // use customized stop words list
    String stopWordsDictionary = FileUtils.readFileToString(new File(%PATH_TO_FILE%));
    stopWordsSet = WordlistLoader.getWordSet(new StringReader(stopWordsDictionary));
} catch (FileNotFoundException e) {
    // use standard stop words list
    stopWordsSet = CharArraySet.copy(StandardAnalyzer.STOP_WORDS_SET);
}

tokenStream = new StopFilter(new ASCIIFoldingFilter(new ClassicFilter(new LowerCaseFilter(stdToken))), stopWordsSet);
tokenStream.reset();