主题
Amazon S3 Vectors
Amazon S3 Vectors 嵌入存储与 Amazon S3 Vectors 集成,这是 Amazon S3 中一项专为大规模存储与查询向量嵌入而设计的向量存储能力。
Maven 依赖
xml
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-s3-vectors</artifactId>
<version>${latest version here}</version>
</dependency>1
2
3
4
5
2
3
4
5
API
S3VectorsEmbeddingStore
特性
- 存储带元数据的嵌入
- 使用余弦或欧氏距离的向量相似度搜索
- 按元数据字段过滤搜索结果
- 首次插入嵌入时自动创建索引
- 支持标准 AWS 凭据提供者
用量
基本配置
java
S3VectorsEmbeddingStore embeddingStore = S3VectorsEmbeddingStore.builder()
.vectorBucketName("my-vector-bucket") // S3 Vectors bucket name (required)
.indexName("my-index") // Index name within the bucket (required)
.region("us-west-2") // AWS region (default: us-east-1)
.distanceMetric(DistanceMetric.COSINE) // Distance metric (default: COSINE)
.createIndexIfNotExists(true) // Auto-create index (default: true)
.timeout(Duration.ofSeconds(60)) // API call timeout (default: 30 seconds)
.credentialsProvider(myCredentialsProvider) // Custom AWS credentials
.build();1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
使用已有的 S3VectorsClient
如果你已经有一个配置好的 S3VectorsClient,可以直接把它传给 builder:
java
S3VectorsClient customClient = S3VectorsClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(myCredentialsProvider)
.build();
S3VectorsEmbeddingStore embeddingStore = S3VectorsEmbeddingStore.builder()
.s3VectorsClient(customClient)
.vectorBucketName("my-vector-bucket")
.indexName("my-index")
.build();1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
距离度量
S3 Vectors 嵌入存储支持两种距离度量。距离值会被自动转换为 [0, 1] 区间内的相关性分数,其中 1 表示最相关的匹配。
余弦距离(默认)
最适合: 文本嵌入、语义相似度搜索
- 衡量向量之间夹角的余弦
- 转换为相关性分数:
score = (1 - distance + 1) / 2 - 结果与向量的模长无关
java
.distanceMetric(DistanceMetric.COSINE) // Default, recommended for text embeddings1
欧氏距离
最适合: 当方向与模长都很重要时
- 衡量向量之间的直线距离
- 范围:[0, ∞)
- 转换为相关性分数:
score = 1 / (1 + distance)
java
.distanceMetric(DistanceMetric.EUCLIDEAN)1
过滤
S3 Vectors 嵌入存储支持按元数据字段过滤搜索结果。
支持的过滤操作
isEqualTo:相等比较isNotEqualTo:不相等比较isGreaterThan:大于比较isGreaterThanOrEqualTo:大于等于比较isLessThan:小于比较isLessThanOrEqualTo:小于等于比较isIn:IN 运算(多值)isNotIn:NOT IN 运算And:逻辑与Or:逻辑或Not:逻辑非
实现细节
凭据
默认情况下,存储使用 DefaultCredentialsProvider,它遵循标准的 AWS 凭据解析链(环境变量、系统属性、凭据文件、EC2 实例配置文件等)。你可以通过 builder 提供一个自定义的 AwsCredentialsProvider。
索引创建
当 createIndexIfNotExists 设为 true(默认)时,索引会在首次插入嵌入时自动创建。索引的维度与距离度量会依据所添加的第一个嵌入以及配置的距离度量来设定。
资源清理
S3VectorsEmbeddingStore 实现了 AutoCloseable。用完后调用 close() 以释放底层 S3VectorsClient 的资源,或使用 try-with-resources。
限制
- 最大结果数:S3 Vectors 将每次查询的搜索结果限制为 100(topK 范围:1-100)
- 按过滤条件移除:不支持
removeAll(Filter);请改用removeAll(Collection<String> ids) - 全部移除:
removeAll()会删除整个索引