Amazon S3 벡터 스토어
그만큼S3Vectors클래스는 다음을 사용하여 벡터 검색을 제공합니다.Amazon S3 벡터(미리 보기). 벡터를 저장합니다.벡터 양동이유사성 검색을 수행합니다.벡터 인덱스, JSON 기반 메타데이터 필터 포함.
Amazon S3 벡터는 미리 보기 서비스입니다. 미리 보기 기능은 예고 없이 변경되거나 제거될 수 있으며 AWS SLA가 적용되지 않습니다. 동작, 한도, 지역별 가용성은 언제든지 변경될 수 있습니다. 이 라이브러리는 AWS와 보조를 맞추기 위해 주요 변경 사항을 도입할 수 있습니다.
설치설치에 대한 직접 링크
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/s3vectors@latest
pnpm add @mastra/s3vectors@latest
yarn add @mastra/s3vectors@latest
bun add @mastra/s3vectors@latest
사용예사용예에 대한 직접 링크
import { S3Vectors } from '@mastra/s3vectors'
const store = new S3Vectors({
vectorBucketName: process.env.S3_VECTORS_BUCKET_NAME!, // e.g. "my-vector-bucket"
clientConfig: {
region: process.env.AWS_REGION!, // credentials use the default AWS provider chain
},
// Optional: mark large/long-text fields as non-filterable at index creation time
nonFilterableMetadataKeys: ['content'],
})
// Create an index (names are normalized: "_" → "-" and lowercased)
await store.createIndex({
indexName: 'my_index',
dimension: 1536,
metric: 'cosine', // "euclidean" also supported; "dotproduct" is NOT supported
})
// Upsert vectors (ids auto-generated if omitted). Date values in metadata are serialized to epoch ms.
const ids = await store.upsert({
indexName: 'my_index',
vectors: [
[0.1, 0.2 /* … */],
[0.3, 0.4 /* … */],
],
metadata: [
{
text: 'doc1',
genre: 'documentary',
year: 2023,
createdAt: new Date('2024-01-01'),
},
{ text: 'doc2', genre: 'comedy', year: 2021 },
],
})
// Query with metadata filters (implicit AND is canonicalized)
const results = await store.query({
indexName: 'my-index',
queryVector: [0.1, 0.2 /* … */],
topK: 10, // Service-side limits may apply (commonly 30)
filter: { genre: { $in: ['documentary', 'comedy'] }, year: { $gte: 2020 } },
includeVector: false, // set true to include raw vectors (may trigger a secondary fetch)
})
// Clean up resources (closes the underlying HTTP handler)
await store.disconnect()
생성자 옵션생성자 옵션에 대한 직접 링크
vectorBucketName:
clientConfig?:
region, credentials)입니다.nonFilterableMetadataKeys?:
content 같은 대용량 텍스트 필드에 사용하세요.행동 양식행동 양식에 대한 직접 링크
createIndex()createindex에 대한 직접 링크
구성된 벡터 버킷에 새 벡터 인덱스를 생성합니다. 인덱스가 이미 존재하는 경우 호출은 스키마의 유효성을 검사하고 작동하지 않습니다(기존 지표 및 차원은 유지됨).
indexName:
dimension:
metric?:
dotproduct를 지원하지 않습니다.upsert()upsert에 대한 직접 링크
벡터를 추가하거나 대체합니다(전체 레코드 삽입). ids를 제공하지 않으면 UUID가 생성됩니다.
indexName:
vectors:
metadata?:
ids?:
query()query에 대한 직접 링크
선택적 메타데이터 필터링을 사용하여 최근접 이웃을 검색합니다.
indexName:
queryVector:
topK?:
filter?:
$and, $or, $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists를 지원하는 JSON 기반 메타데이터 필터입니다.includeVector?:
결과에는 기반 거리 순위를 유지하면서 값이 클수록 더 좋도록 score = 1/(1 + distance)가 포함됩니다.
describeIndex()describeindex에 대한 직접 링크
인덱스에 대한 정보를 반환합니다.
indexName:
보고:
interface IndexStats {
dimension: number
count: number // computed via ListVectors pagination (O(n))
metric: 'cosine' | 'euclidean'
}
deleteIndex()deleteindex에 대한 직접 링크
인덱스와 해당 데이터를 삭제합니다.
indexName:
listIndexes()listindexes에 대한 직접 링크
구성된 벡터 버킷의 모든 인덱스를 나열합니다.
보고:Promise<string[]>
updateVector()updatevector에 대한 직접 링크
인덱스 내의 특정 ID에 대한 벡터 또는 메타데이터를 업데이트합니다.
indexName:
id:
update:
update.vector?:
update.metadata?:
deleteVector()deletevector에 대한 직접 링크
ID별로 특정 벡터를 삭제합니다.
indexName:
id:
disconnect()disconnect에 대한 직접 링크
기본 AWS SDK HTTP 핸들러를 닫아 소켓을 확보합니다.
응답 유형응답 유형에 대한 직접 링크
쿼리 결과는 다음 형식으로 반환됩니다.
interface QueryResult {
id: string
score: number // 1/(1 + distance)
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}
필터 구문필터 구문에 대한 직접 링크
S3 벡터는 연산자 및 값 유형의 엄격한 하위 집합을 지원합니다. Mastra 필터 번역기:
- 암시적 AND를 정규화합니다.:
{a:1,b:2}→{ $and: [{a:1},{b:2}] }. - 날짜 값을 정규화합니다. 숫자 비교와 배열 요소에 사용할 수 있도록 epoch ms로 변환합니다.
- 동등 비교 위치에서는 날짜를 허용하지 않습니다. (
field: value또는$eq/$ne). 동등 비교 값은 string | number | boolean이어야 합니다. - 동등 비교에서는 null/undefined를 거부합니다. 배열 동등 비교는 지원하지 않습니다(
$in/$nin사용). - 최상위 논리 연산자로는 **
$and/$or**만 허용됩니다. - 논리 연산자에는 직접 연산자가 아닌 필드 조건이 포함되어야 합니다. 지원되는 연산자:
- 논리:
$and,$or(비어 있지 않은 배열) - 기본:
$eq,$ne(string | number | boolean) - 숫자:
$gt,$gte,$lt,$lte(number 또는Date→ epoch ms) - 집합:
$in,$nin(string | number | boolean으로 구성된 비어 있지 않은 배열,Date→ epoch ms) - 존재 여부:
$exists(boolean) 지원되지 않음/허용되지 않음(거부됨):$not,$nor,$regex,$all,$elemMatch,$size,$text, etc.
예:
// Implicit AND
{ genre: { $in: ["documentary", "comedy"] }, year: { $gte: 2020 } }
// Explicit logicals and ranges
{
$and: [
{ price: { $gte: 100, $lte: 1000 } },
{ $or: [{ stock: { $gt: 0 } }, { preorder: true }] }
]
}
// Dates in range (converted to epoch ms)
{ timestamp: { $gt: new Date("2024-01-01T00:00:00Z") } }
인덱스 생성 시 nonFilterableMetadataKeys를 설정하면 해당 키는 저장되지만 필터에서는 사용할 수 없습니다.
오류 처리오류 처리에 대한 직접 링크
상점에서는 포착할 수 있는 입력된 오류를 발생시킵니다.
try {
await store.query({
indexName: 'index-name',
queryVector: queryVector,
})
} catch (error) {
if (error instanceof VectorStoreError) {
console.log(error.code) // 'connection_failed' | 'invalid_dimension' | etc
console.log(error.details) // Additional error context
}
}
환경변수환경변수에 대한 직접 링크
앱을 연결할 때 일반적인 환경 변수:
S3_VECTORS_BUCKET_NAME: S3 벡터 버킷 이름(vectorBucketName을 채우는 데 사용).AWS_REGION: S3 벡터 버킷의 AWS 리전입니다.- AWS 자격 증명: 표준 AWS SDK Provider 체인(
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_PROFILE등)을 통해 제공합니다.
모범 사례모범 사례에 대한 직접 링크
- 임베딩 Model과 일치하도록 측정 방식(
cosine또는euclidean)을 설정하세요.dotproduct는 지원되지 않습니다. - 필터링 가능한 메타데이터는 작고 구조화된 형태(string/number/boolean)로 유지하세요. 대용량 텍스트(예:
content)는 필터링 불가능으로 저장하세요. - 중첩된 메타데이터에는 점으로 구분된 경로를 사용하고, 복잡한 로직에는 명시적인
$and/$or를 사용하세요. - 자주 실행되는 경로에서
describeIndex()를 호출하지 마세요.count는 페이지가 매겨진ListVectors를 사용하여 계산됩니다(O(n)). - 원시 벡터가 필요할 때만
includeVector: true를 사용하세요.