有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Lucene Analyzer而无需索引我的方法合理吗?

我的目标是利用Lucene的许多标记器和过滤器来转换输入文本,但不创建任何索引

例如,给定这个(人为的)输入字符串

" Someone’s - [texté] goes here, foo . "

。。。像这样的Lucene分析仪

Analyzer analyzer = CustomAnalyzer.builder()
        .withTokenizer("icu")
        .addTokenFilter("lowercase")
        .addTokenFilter("icuFolding")
        .build();

我想得到以下输出:

someone's texte goes here foo

下面的Java方法符合我的要求

但我有没有更好的(即更典型和/或更简洁的)方法来做到这一点

我在特别思考我使用TokenStreamCharTermAttribute的方式,因为我以前从未这样使用过它们。感觉笨重

以下是代码:

Lucene 8.3.0进口:

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.custom.CustomAnalyzer;

我的方法是:

private String transform(String input) throws IOException {

    Analyzer analyzer = CustomAnalyzer.builder()
            .withTokenizer("icu")
            .addTokenFilter("lowercase")
            .addTokenFilter("icuFolding")
            .build();

    TokenStream ts = analyzer.tokenStream("myField", new StringReader(input));
    CharTermAttribute charTermAtt = ts.addAttribute(CharTermAttribute.class);

    StringBuilder sb = new StringBuilder();
    try {
        ts.reset();
        while (ts.incrementToken()) {
            sb.append(charTermAtt.toString()).append(" ");
        }
        ts.end();
    } finally {
        ts.close();
    }
    return sb.toString().trim();
}

共 (1) 个答案

  1. # 1 楼答案

    我已经使用这个设置好几个星期了,没有问题。我还没有找到更简洁的方法。我认为问题中的代码是可以的