【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 的流式分词。

相关推荐
risc1234562 天前
【lucene】向量搜索底层文件关系梳理
lucene
risc1234565 天前
【Lucene】架构
lucene
risc1234565 天前
【Lucene】lucene的searcher.search查询机制
lucene
lrh302510 天前
Custom SRP - Custom Render Pipeline
搜索引擎·全文检索·lucene
risc12345614 天前
BKD 树(Block KD-Tree)Lucene
java·数据结构·lucene
risc12345616 天前
【Lucene/Elasticsearch】**Query Rewrite** 机制
elasticsearch·jenkins·lucene
Elastic 中国社区官方博客18 天前
Elasticsearch 字符串包含子字符串:高级查询技巧
大数据·数据库·elasticsearch·搜索引擎·全文检索·lucene
zfj3213 个月前
Lucene多种数据类型使用说明
java·mybatis·lucene
事橙19993 个月前
Ubuntu18 登录界面死循环 Ubuntu进不了桌面
linux·ubuntu·lucene