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

相关推荐
龙山云仓4 小时前
No140:AI世间故事-对话康德——先验哲学与AI理性:范畴、道德律与自主性
大数据·人工智能·深度学习·机器学习·全文检索·lucene
TracyCoder1232 天前
ElasticSearch核心引擎Apache Lucene(五):相关性算分 (Scoring)
elasticsearch·apache·lucene
TracyCoder1233 天前
ElasticSearch核心引擎Apache Lucene(四):段 (Segment) 的设计与合并
elasticsearch·apache·lucene
TracyCoder1233 天前
ElasticSearch核心引擎Apache Lucene(三):数值与空间数据索引
elasticsearch·apache·lucene
Elastic 中国社区官方博客3 天前
Elasticsearch:Apache Lucene 2025 年终总结
大数据·人工智能·elasticsearch·搜索引擎·apache·lucene
TracyCoder1233 天前
ElasticSearch核心引擎Apache Lucene(二):正排索引的奥秘
elasticsearch·apache·lucene
TracyCoder1233 天前
ElasticSearch核心引擎Apache Lucene(一):倒排索引底层实现
elasticsearch·apache·lucene
程序员agions23 天前
Unity 游戏开发邪修秘籍:从入门到被策划追杀的艺术
unity·cocoa·lucene
AC赳赳老秦23 天前
Unity游戏开发实战指南:核心逻辑与场景构建详解
开发语言·spring boot·爬虫·搜索引擎·全文检索·lucene·deepseek
木风小助理1 个月前
C# 高效编程:Any () 与 Count () 正确选择
java·solr·lucene