S3 벡터 스토어

S3 벡터 스토어 (S3 Vector Store)

이 섹션에서는 S3VectorStore를 설정해서 문서 임베딩을 저장하고 유사도 검색을 수행하는 방법을 안내해요. AWS S3 Vector Store는 벡터를 규모 있게 저장하고 쿼리하는 것을 지원하는 서버리스 객체 스토리지예요. S3 Vector Store API는 AWS S3 Bucket의 핵심 기능을 확장해 S3를 벡터 데이터베이스로 사용할 수 있게 해 줘요.

출처: 문서

본문

S3 벡터 스토어 (S3 Vector Store)

이 섹션은 S3VectorStore를 설정해 문서 임베딩을 저장하고 유사도 검색을 수행하는 방법을 안내해요.

AWS S3 Vector Store는 벡터를 규모 있게 저장하고 쿼리하는 것을 지원하는 서버리스 객체 스토리지예요. S3 Vector Store API는 AWS S3 Bucket의 핵심 기능을 확장해 S3를 벡터 데이터베이스로 사용할 수 있게 해 줘요:

  • 벡터와 관련 메타데이터를 hashes나 JSON 문서로 저장
  • 벡터 검색
  • 벡터 검색 수행

사전 준비 (Prerequisites)

  1. S3 Vector Store Bucket

  2. 문서 임베딩을 계산할 EmbeddingModel 인스턴스. 여러 옵션이 가능해요:

    • 필요하다면, S3VectorStore가 저장하는 임베딩을 생성하기 위한 EmbeddingModel용 API 키.

자동 설정 (Auto-configuration)

Spring AI는 S3 Vector Store에 대한 Spring Boot 자동 설정을 제공해요. 활성화하려면 프로젝트의 Maven pom.xml 파일에 다음 의존성을 추가하세요:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-s3</artifactId>
</dependency>

또는 Gradle build.gradle 빌드 파일에:

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-s3'
}

참고: 빌드 파일에 Spring AI BOM을 추가하려면 Dependency Management 섹션을 참고해 주세요.

참고: 빌드 파일에 Maven Central 및/또는 Snapshot 저장소를 추가하려면 Artifact Repositories 섹션을 참고해 주세요.

기본값과 구성 옵션을 알려면 벡터 스토어의 구성 파라미터 목록을 살펴보세요. 추가로 구성된 EmbeddingModel 빈이 필요해요. 자세한 내용은 EmbeddingModel 섹션을 참고하세요.

이제 애플리케이션에서 S3VectorStore를 벡터 스토어로 오토와이어할 수 있어요.

@Autowired VectorStore vectorStore;

// ...

List <Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to S3 Vector Store Bucket
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

구성 프로퍼티 (Configuration Properties)

AWS S3 Vector Store에 연결하고 S3VectorStore를 사용하려면 올바른 Credentials와 Region이 제공된 S3VectorsClient의 Bean을 만들어야 해요. spring.ai.vectorstore.s3.*로 시작하는 프로퍼티는 S3VectorStore를 구성하는 데 사용돼요:

Property Description Default Value
spring.ai.vectorstore.s3.index-name 벡터를 저장할 인덱스의 이름 spring-ai-index
spring.ai.vectorstore.s3.vector-bucket-name 벡터가 위치한 bucket의 이름 my-vector-bucket-on-aws

메타데이터 필터링 (Metadata Filtering)

S3 Vector Store에서도 일반적이고 휴대 가능한 메타데이터 필터를 활용할 수 있어요.

예를 들어 텍스트 표현 언어를 사용할 수 있어요:

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("country in ['UK', 'NL'] && year >= 2020").build());

또는 Filter.Expression DSL로 프로그래밍 방식으로:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression(b.and(
                b.in("country", "UK", "NL"),
                b.gte("year", 2020)).build()).build());

참고: 이 (휴대 가능한) 필터 표현식은 자동으로 AWS SDK Java V2 Filter Document object로 변환돼요.

예를 들어 이 휴대 가능한 필터 표현식:

country in ['UK', 'NL'] && year >= 2020

은 S3 Vector Store 필터 형식으로 변환돼요:

{"$and": [{"country": {"$in": ["UK", "NL"]}}, {"year": {"$gte": 2020}}]}

필터 기반 삭제 (Filter-based Deletion)

필터 표현식으로 문서를 삭제할 수도 있어요:

vectorStore.delete("country in ['UK', 'NL'] && year >= 2020");

또는 프로그래밍 방식으로:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.delete(b.and(
        b.in("country", "UK", "NL"),
        b.gte("year", 2020)).build());

참고: S3 Vectors는 서버 측 필터-삭제 API를 제공하지 않아요. 필터 기반 삭제는 인덱스의 모든 벡터를 나열(페이지당 500개)하고 필터 표현식을 로컬에서 평가해요. 큰 인덱스에서는 이 작업이 저장된 전체 벡터 수에 비례해요.

수동 구성 (Manual Configuration)

Spring Boot 자동 설정 대신 S3 Vector Store를 수동 구성할 수 있어요. 이를 위해 프로젝트에 spring-ai-s3-vector-store를 추가해야 해요:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-s3-vector-store</artifactId>
</dependency>

또는 Gradle build.gradle 빌드 파일에:

dependencies {
    implementation 'org.springframework.ai:spring-ai-s3-vector-store'
}

그런 다음 빌더 패턴으로 S3VectorStore 빈을 만드세요:

@Bean
VectorStore s3VectorStore(S3VectorsClient s3VectorsClient, EmbeddingModel embeddingModel) {
    S3VectorStore.Builder builder = new S3VectorStore.Builder(s3VectorsClient, embeddingModel); // Required a must
    builder.indexName(properties.getIndexName()) // Required indexName must be specified
            .vectorBucketName(properties.getVectorBucketName()) // Required vectorBucketName must be specified
            .filterExpressionConverter(yourConverter);  // Optional if you want to override default filterConverter
    return builder.build();
	}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(OpenAiEmbeddingOptions.builder().apiKey(System.getenv("OPENAI_API_KEY")).build());
}

네이티브 클라이언트 접근 (Accessing the Native Client)

S3 Vector Store 구현은 내부 네이티브 S3VectorsClient 클라이언트에 접근을 제공해요:

S3VectorStore vectorStore = context.getBean(S3VectorStore.class);
Optional<S3VectorsClient> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    S3VectorsClient s3Client = nativeClient.get();
    // Use the native client for S3-Vector-Store-specific operations
}

네이티브 클라이언트는 VectorStore 인터페이스로는 노출되지 않는 S3-Vector-Store 특화 기능과 작업에 접근할 수 있게 해 줘요.

더 알아보기 (Learn more)