【lucene】AttributeSource概述

`AttributeSource` 是 Lucene 分析链(Tokenizer / TokenFilter)的 "属性仓库":

它把 所有需要跨 token 传递的信息(词、偏移、位置、payload ...)抽象成 Attribute 接口,并在 一条 TokenStream 链里共享同一份实例,从而避免每轮 token 创建/拷贝对象,保证 零拷贝 + 高性能。


  1. 核心职责

功能 说明

仓库注册 通过 `addAttribute(Class<T>)` 声明"我要用哪种属性"

实例共享 整个链共用同一份属性对象,TokenFilter 只读/改属性,不重新 new

反射生成 内部用 `Class.newInstance()` 缓存具体实现,避免反射开销


  1. 典型 Attribute 一览

Attribute 接口 实现类 作用

`CharTermAttribute` `CharTermAttributeImpl` 当前 token 字符串

`OffsetAttribute` `OffsetAttributeImpl` 起始/结束偏移

`PositionIncrementAttribute` `PositionIncrementAttributeImpl` 位置增量

`PayloadAttribute` `PayloadAttributeImpl` payload 字节

`TypeAttribute` `TypeAttributeImpl` token 类型


  1. 使用示例(自定义 TokenFilter)

```java

public final class MyFilter extends TokenFilter {

private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

private final OffsetAttribute offAtt = addAttribute(OffsetAttribute.class);

@Override

public boolean incrementToken() throws IOException {

if (!input.incrementToken()) return false;

termAtt.setEmpty().append("prefix_").append(termAtt);

offAtt.setOffset(offAtt.startOffset(), offAtt.endOffset() + 3);

return true;

}

}

```

整个链共享 `termAtt` / `offAtt`,无需拷贝。


  1. 一句话总结

> `AttributeSource` 是 Lucene 的"零拷贝属性仓库",让 TokenStream 链里的所有组件共享同一份 Attribute 实例,实现高效、低 GC 的流式分词。

相关推荐
与火星的孩子对话1 天前
Unity高级开发:反射原理深入解析与实践指南 C#
java·unity·c#·游戏引擎·lucene·反射
risc1234567 天前
【lucene】文档id docid
lucene
risc1234567 天前
【lucene】lucene索引文件的读取器都是单向的只能向前不能后退读
lucene
chenglin01610 天前
ClickHouse、Doris、OpenSearch、Splunk、Solr系统化分析
clickhouse·solr·lucene
Freed&16 天前
倒排索引:Elasticsearch 搜索背后的底层原理
大数据·elasticsearch·搜索引擎·lucene
risc12345616 天前
【lucene】ByteBufferGuard
lucene
risc12345618 天前
【lucene】使用docvalues的案例
lucene
risc12345618 天前
【lucene】currentFrame与staticFrame
lucene
risc12345619 天前
【lucene】IndexOptions
全文检索·lucene
risc12345619 天前
【lucene】SegmentCoreReaders
lucene