如何从 lucene 使用 StandardTokenizer 5.x.x

How to use StandardTokenizer from lucene 5.x.x

有很多示例展示了如何像这样使用 StandardTokenizer:

TokenStream tokenStream = new StandardTokenizer(
            Version.LUCENE_36, new StringReader(input));

但在较新的 Lucene 版本中,此构造函数不可用。新构造函数如下所示:

StandardTokenizer(AttributeFactory factory)

这个 AttributeFactory 的作用是什么?我如何在较新版本的 Lucene 中标记字符串?

AttributeFactory 创建了 AttributeImpl,它们是 Attribute 的来源。属性控制 TokenStream 的行为,这是用于 reading/tracking StandardTokenizer.

数据流的底层机制

相对于 AttributeFactory,从 4.x 到 5.x 几乎没有变化 - 在这两个版本中,您可以创建一个 StandardTokenizerAttributeFactory如果您愿意,或者您没有指定,那么 AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY 最终将被使用。

最大的区别在于您还可以将 Reader 作为构造函数的一部分传递给输入流。这意味着在 4.x 中,您必须为每个要处理的输入流创建一个新的 StreamTokenizer,这又必须重新初始化 AttributeFactory.

中的属性

我不是 Lucene 开发人员,但我的猜测是这只是一种重组,以鼓励在多个流的读取过程中重用属性。如果您看一下 TokenStream and the default AttributesFactory 实现的内部结构,就会发现创建和设置属性涉及很多反思。如果我不得不猜测,只是删除了采用 reader 的 StreamTokenizer 构造函数以鼓励重用分词器及其属性,因为这些属性的初始化相对昂贵。

编辑

添加一个迟来的例子 - 很抱歉没有以这个开头:

// Define your attribute factory (or use the default) - same between 4.x and 5.x
AttributeFactory factory = AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY;

// Create the tokenizer and prepare it for reading
//  Lucene 4.x
StandardTokenizer tokenizer = 
        new StandardTokenizer(factory, new StringReader("Tokenize me!"));
tokenizer.reset();
//  Lucene 5.x
StandardTokenizer tokenizer = new StandardTokenizer(factory);
tokenizer.setReader(new StringReader("Tokenizer me!"));
tokenizer.reset();

// Then process tokens - same between 4.x and 5.x
// NOTE: Here I'm adding a single expected attribute to handle string tokens,
//  but you would probably want to do something more meaningful/elegant
CharTermAttribute attr = tokenizer.addAttribute(CharTermAttribute.class);
while(tokenizer.incrementToken()) {
    // Grab the term
    String term = attr.toString();

    // Do something crazy...
}