【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 天前
C# LINQ常用语法
solr·lucene
cyh男10 天前
lucene中AutomatonQuery类的作用
lucene
cyh男10 天前
lucene中的PointRangeQuery和PointInSetQuery有什么区别
lucene
cyh男10 天前
为什么ES中不推荐使用wildcard查询
elasticsearch·lucene
渣渣盟12 天前
中文分词技术全解析
搜索引擎·全文检索·lucene
cyh男24 天前
lucene 8.7.0 版本中的倒排索引、数字、DocValues三种类型的查询性能对比
lucene
cyh男1 个月前
Lucene 8.7.0 版本中dvd、dvm文件详解
lucene
是犹橐籥1 个月前
头歌Educoder答案 Lucene - 全文检索入门
搜索引擎·全文检索·lucene
cyh男1 个月前
Lucene 8.7.0 版本中docFreq、totalTermFreq、getDocCount等方法的含义
lucene
cyh男1 个月前
Lucene 8.7.0 版本中doc、tim、tip、tmd文件详解
lucene