MongoDB Atlas 벡터 스토어

MongoDB Atlas 벡터 스토어 (MongoDB Atlas)

이 섹션에서는 Spring AI에서 사용할 벡터 스토어로 MongoDB Atlas를 설정하는 방법을 안내해요. MongoDB Atlas는 AWS, Azure, GCP에서 사용 가능한 MongoDB의 완전 관리형 클라우드 데이터베이스로, MongoDB 문서 데이터에 대한 네이티브 Vector Search와 전체 텍스트 검색을 지원해요.

출처: 문서

본문

MongoDB Atlas

이 섹션은 Spring AI에서 사용할 벡터 스토어로 MongoDB Atlas를 설정하는 방법을 안내해요.

MongoDB Atlas란? (What is MongoDB Atlas?)

MongoDB Atlas는 AWS, Azure, GCP에서 사용 가능한 MongoDB의 완전 관리형 클라우드 데이터베이스예요. Atlas는 MongoDB 문서 데이터에 대한 네이티브 Vector Search와 전체 텍스트 검색을 지원해요.

MongoDB Atlas Vector Search는 임베딩을 MongoDB 문서에 저장하고, 벡터 검색 인덱스를 만들고, 근사 최근접 이웃 알고리즘(Hierarchical Navigable Small Worlds)으로 KNN 검색을 수행할 수 있게 해 줘요. MongoDB 집계 단계에서 $vectorSearch 집계 연산자를 사용해 벡터 임베딩에 대한 검색을 수행할 수 있어요.

사전 준비 (Prerequisites)

  • MongoDB 6.0.11, 7.0.2 이상 버전을 실행하는 Atlas 클러스터. MongoDB Atlas를 시작하려면 여기의 지침을 따르세요. IP 주소가 Atlas 프로젝트의 access list에 포함되어 있는지 확인하세요.
  • Vector Search가 활성화된 실행 중인 MongoDB Atlas 인스턴스
  • 벡터 검색 인덱스가 구성된 Collection
  • id (string), content (string), metadata (document), embedding (vector) 필드가 있는 Collection 스키마
  • 인덱스와 collection 작업에 대한 적절한 접근 권한

자동 설정 (Auto-configuration)

참고: Spring AI auto-configuration과 starter 모듈의 아티팩트 이름에 큰 변화가 있었어요. 자세한 내용은 upgrade notes를 참고해 주세요.

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

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

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

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

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

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

벡터 스토어 구현은 필요한 스키마를 초기화할 수 있지만 application.properties 파일에서 spring.ai.vectorstore.mongodb.initialize-schema=true를 설정해 선택해야 해요. 또는 초기화를 해제하고 MongoDB Atlas UI, Atlas Administration API, Atlas CLI로 인덱스를 수동으로 만들 수도 있어요. 이는 인덱스에 고급 매핑이나 추가 구성이 필요한 경우 유용해요.

참고: 이것은 호환성을 깨는 변경이에요! 이전 버전의 Spring AI에서는 이 스키마 초기화가 기본으로 일어났어요.

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

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

@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 MongoDB Atlas
vectorStore.add(documents);

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

구성 프로퍼티 (Configuration Properties)

MongoDB Atlas에 연결하고 MongoDBAtlasVectorStore를 사용하려면 인스턴스의 접근 세부 정보를 제공해야 해요. 간단한 구성은 Spring Boot의 application.yml로 제공할 수 있어요:

spring:
  data:
    mongodb:
      uri: <mongodb atlas connection string>
      database: <database name>
  ai:
    vectorstore:
      mongodb:
        initialize-schema: true
        collection-name: custom_vector_store
        index-name: custom_vector_index
        path-name: custom_embedding
        metadata-fields-to-filter: author,year

spring.ai.vectorstore.mongodb.*로 시작하는 프로퍼티는 MongoDBAtlasVectorStore를 구성하는 데 사용돼요:

Property Description Default Value
spring.ai.vectorstore.mongodb.initialize-schema 필요한 스키마를 초기화할지 여부 false
spring.ai.vectorstore.mongodb.collection-name 벡터를 저장할 collection의 이름 vector_store
spring.ai.vectorstore.mongodb.index-name 벡터 검색 인덱스의 이름 vector_index
spring.ai.vectorstore.mongodb.path-name 벡터가 저장되는 경로 embedding
spring.ai.vectorstore.mongodb.metadata-fields-to-filter 필터링에 사용할 수 있는 메타데이터 필드의 쉼표로 구분된 목록 empty list

수동 구성 (Manual Configuration)

Spring Boot 자동 설정 대신 MongoDB Atlas 벡터 스토어를 수동 구성할 수 있어요. 이를 위해 프로젝트에 spring-ai-mongodb-atlas-store를 추가해야 해요:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mongodb-atlas-store</artifactId>
</dependency>

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

dependencies {
    implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}

MongoTemplate 빈을 만드세요:

@Bean
public MongoTemplate mongoTemplate() {
    return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}

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

@Bean
public VectorStore vectorStore(MongoTemplate mongoTemplate, EmbeddingModel embeddingModel) {
    return MongoDBAtlasVectorStore.builder(mongoTemplate, embeddingModel)
        .collectionName("custom_vector_store")           // Optional: defaults to "vector_store"
        .vectorIndexName("custom_vector_index")          // Optional: defaults to "vector_index"
        .pathName("custom_embedding")                    // Optional: defaults to "embedding"
        .numCandidates(500)                             // Optional: defaults to 200
        .metadataFieldsToFilter(List.of("author", "year")) // Optional: defaults to empty list
        .initializeSchema(true)                         // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

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

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

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

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

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(5)
        .similarityThreshold(0.7)
        .filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());

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

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(5)
        .similarityThreshold(0.7)
        .filterExpression(b.and(
                b.in("author", "john", "jill"),
                b.eq("article_type", "blog")).build()).build());

참고: 이 (휴대 가능한) 필터 표현식은 자동으로 고유한 MongoDB Atlas 필터 표현식으로 변환돼요.

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

author in ['john', 'jill'] && article_type == 'blog'

은 고유한 MongoDB Atlas 필터 형식으로 변환돼요:

{
  "$and": [
    {
      "$or": [
        { "metadata.author": "john" },
        { "metadata.author": "jill" }
      ]
    },
    {
      "metadata.article_type": "blog"
    }
  ]
}

튜토리얼과 코드 예제 (Tutorials and Code Examples)

Spring AI와 MongoDB 시작하기:

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

MongoDB Atlas Vector Store 구현은 getNativeClient() 메서드를 통해 내부 네이티브 MongoDB 클라이언트(MongoClient)에 접근을 제공해요:

MongoDBAtlasVectorStore vectorStore = context.getBean(MongoDBAtlasVectorStore.class);
Optional<MongoClient> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    MongoClient client = nativeClient.get();
    // Use the native client for MongoDB-specific operations
}

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

더 알아보기 (Learn more)