Spring AI 1.1.4 + pgvector 간단 예제 (RAG 구조)

Spring AI 1.1.4에서는 PostgreSQL 기반 벡터 데이터베이스인 pgvector를 활용해서
RAG(Retrieval-Augmented Generation) 구조를 쉽게 구현할 수 있다.

전체 구조는 다음과 같다:

문서 → 임베딩 생성 → pgvector 저장 → 질문 → 유사도 검색 → LLM 응답 생성


1. 의존성 설정 (Spring AI 1.1.4)

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'

    // Spring AI OpenAI
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter:1.1.4'

    // pgvector Vector Store
    implementation 'org.springframework.ai:spring-ai-pgvector-store-spring-boot-starter:1.1.4'

    // PostgreSQL
    runtimeOnly 'org.postgresql:postgresql'
}

2. application.yml 설정

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/ai_db
    username: postgres
    password: password

  ai:
    openai:
      api-key: YOUR_OPENAI_API_KEY

    vectorstore:
      pgvector:
        initialize-schema: true

3. pgvector 테이블 구조

Spring AI 1.1.4에서는 자동 생성이 가능하지만 내부 구조는 다음과 같다.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE vector_store (
    id UUID PRIMARY KEY,
    content TEXT,
    embedding VECTOR(1536),
    metadata JSONB
);

embedding 컬럼이 핵심이며, AI 임베딩 벡터가 저장된다.


4. 문서 저장 (Embedding 생성 및 저장)

@Service
public class DocumentService {

    private final VectorStore vectorStore;

    public DocumentService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    public void saveDocument(String text) {

        Document document = new Document(text);

        vectorStore.add(List.of(document));
    }
}

동작 과정:

  • 텍스트 입력
  • Spring AI가 embedding 생성
  • pgvector에 자동 저장

5. 유사 문서 검색

@Service
public class SearchService {

    private final VectorStore vectorStore;

    public SearchService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    public List<Document> search(String query) {

        return vectorStore.similaritySearch(
                SearchRequest.query(query).withTopK(3)
        );
    }
}

동작 과정:

  • 질문을 embedding으로 변환
  • pgvector에서 유사도 검색
  • 가장 관련 높은 문서 반환

6. RAG 기반 챗봇 예제

@RestController
public class ChatController {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    public ChatController(ChatClient chatClient, VectorStore vectorStore) {
        this.chatClient = chatClient;
        this.vectorStore = vectorStore;
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String question) {

        List<Document> docs =
                vectorStore.similaritySearch(
                        SearchRequest.query(question).withTopK(3)
                );

        String context = docs.stream()
                .map(Document::getContent)
                .reduce("", (a, b) -> a + "\n" + b);

        String prompt = """
                다음 정보를 기반으로 질문에 답하세요.

                [참고 정보]
                %s

                [질문]
                %s
                """.formatted(context, question);

        return chatClient.prompt()
                .user(prompt)
                .call()
                .content();
    }
}

전체 동작 흐름

  1. 문서 저장 단계
  • 텍스트 입력
  • embedding 생성
  • pgvector 저장
  1. 질문 처리 단계
  • 질문 입력
  • embedding 변환
  • 유사 문서 검색
  1. 응답 생성 단계
  • 검색된 문서 + 질문 결합
  • LLM 호출
  • 최종 답변 생성

핵심 포인트

Spring AI 1.1.4는 벡터 검색과 LLM 연동을 하나의 구조로 통합해준다.

개발자는 다음만 신경 쓰면 된다:

  • 문서 넣기
  • 질문 던지기

나머지 embedding, 검색, LLM 호출은 Spring AI가 처리한다.


한 줄 정리

Spring AI 1.1.4 + pgvector = PostgreSQL을 AI 검색 엔진으로 바꾸는 가장 간단한 방법

 

반응형

'Java' 카테고리의 다른 글

RAG란 무엇인가?  (0) 2026.04.20
Java 21 Virtual Thread란 무엇인가?  (0) 2026.04.20
TurboQuant란 무엇인가?  (0) 2026.04.20
Spring AI 소개 및 핵심 정리  (0) 2026.04.20
부동소수 & 고정소수  (1) 2024.10.21
블로그 이미지

visualp

c#, java

,