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

相关推荐
cyh男1 天前
Lucene 8.7.0 版本中docFreq、totalTermFreq、getDocCount等方法的含义
lucene
cyh男2 天前
Lucene 8.7.0 版本中doc、tim、tip、tmd文件详解
lucene
极限实验室10 天前
搜索百科(1):Lucene —— 打开现代搜索世界的第一扇门
搜索引擎·lucene
一路向北North12 天前
lucene渲染未命中最匹配的关键词和内容
搜索引擎·全文检索·lucene
risc12345622 天前
【lucene】advanceshallow就是遍历跳表的,可以看作是跳表的遍历器
lucene
cyh男22 天前
Lucene 8.7.0 版本的索引文件格式
搜索引擎·全文检索·lucene
risc12345623 天前
【lucene核心】impacts的由来
lucene
在未来等你24 天前
Elasticsearch面试精讲 Day 5:倒排索引原理与实现
elasticsearch·搜索引擎·面试·全文检索·lucene·分词·倒排索引
risc12345625 天前
【lucene】 中的impactsenum与impactsdisi有啥区别?
lucene
risc12345625 天前
【lucene】如何评测一款分析器Analyzer
lucene