LangChain / RAG / Vector DBs · 강의

임베딩 저장 및 검색

문서 청크에서 임베딩을 생성하고 나중에 검색할 수 있도록 벡터 데이터베이스에 저장하는 과정을 구현합니다.

레슨 3/411개 단계

임베딩 저장 및 검색은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Storing & Retrieving Embeddings

Welcome to Lesson 3! In this lesson, we'll connect the dots between text chunks and vector databases.

You'll learn how to generate numerical representations (embeddings) from your document chunks and then store them efficiently in a vector database for quick and accurate retrieval.

Recap: Chunks & Embeddings

Before we dive in, let's quickly recap. From previous lessons, you know:

  • Document Chunks: Large documents are split into smaller, manageable pieces to fit LLM context windows and improve retrieval granularity.
  • Text Embeddings: These are numerical vectors that capture the semantic meaning of text. Similar texts have similar embeddings.

Our goal now is to turn those chunks into embeddings and make them searchable!

The Storage & Retrieval Flow

Here's the typical workflow for getting your data ready for RAG:

  1. Load & Split: Ingest raw documents and break them into chunks.
  2. Embed: Convert each text chunk into an embedding vector using an embedding model.
  3. Store: Save these embedding vectors (along with their original text chunks and metadata) in a vector database.
  4. Retrieve: When a user asks a question, embed the query, search the vector database for similar embeddings, and retrieve the most relevant chunks.

Initializing an Embedding Model

First, we need an embedding model. LangChain provides interfaces for many models, including those from OpenAI, Cohere, and local models like those from Hugging Face.

For this example, we'll use a local Hugging Face model to avoid needing an API key. This model turns text into a vector of numbers.

from langchain_community.embeddings import HuggingFaceEmbeddings

# Initialize a local embedding model
# This might download the model the first time
embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

print("Embedding model initialized successfully!")

Generating Embeddings from Text

Once our embedding model is ready, we can feed it text chunks. The model will then output a list of numbers (our embedding vector) for each chunk.

These vectors are what the vector database will use to find similar pieces of information.

from langchain_community.embeddings import HuggingFaceEmbeddings

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

texts_to_embed = [
    "The quick brown fox jumps over the lazy dog.",
    "A canine named Fido is taking a nap."
]

# Generate embeddings for the texts
vectors = embeddings_model.embed_documents(texts_to_embed)

print(f"Number of vectors generated: {len(vectors)}")
print(f"Dimension of each vector: {len(vectors[0])}")
# print(f"First vector (partial): {vectors[0][:5]}...") # Too long for mobile

Introducing Vector Stores

A vector store is a specialized database designed to efficiently store and query high-dimensional vectors. It's built to quickly find vectors that are 'close' to a given query vector.

Think of it as a super-fast index for semantic meaning. When you search, it doesn't look for keywords; it looks for meaning.

LangChain supports many vector stores, from simple in-memory ones like FAISS to robust cloud services like Pinecone or Chroma.

Storing Embeddings with FAISS

Let's use FAISS, an in-memory vector store, to demonstrate storage. We'll take our text chunks and their embeddings and add them to FAISS. FAISS handles the indexing for fast search.

In a real application, you'd load chunks from documents first, then embed them, and finally store them. Here, we'll create simple documents directly.

from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# Create some example documents (text chunks with optional metadata)
documents = [
    Document(page_content="The capital of France is Paris.", metadata={"source": "geo"}),
    Document(page_content="Eiffel Tower is a landmark in Paris.", metadata={"source": "tourism"}),
    Document(page_content="Python is a popular programming language.", metadata={"source": "tech"}),
    Document(page_content="Coding with Python is fun and versatile.", metadata={"source": "tech"})
]

# Create a FAISS vector store from the documents and embeddings model
vectorstore = FAISS.from_documents(documents, embeddings_model)

print("Documents successfully stored in FAISS vector store!")

Performing a Similarity Search

Now that our documents are embedded and stored, we can query the vector store to find the most semantically similar documents to our question.

The vector store will embed your query, compare its vector to all stored vectors, and return the top 'k' (e.g., top 4) most similar documents.

from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

documents = [
    Document(page_content="The capital of France is Paris.", metadata={"source": "geo"}),
    Document(page_content="Eiffel Tower is a landmark in Paris.", metadata={"source": "tourism"}),
    Document(page_content="Python is a popular programming language.", metadata={"source": "tech"}),
    Document(page_content="Coding with Python is fun and versatile.", metadata={"source": "tech"})
]
vectorstore = FAISS.from_documents(documents, embeddings_model)

query = "What is the main city of France?"

# Perform a similarity search
retrieved_docs = vectorstore.similarity_search(query, k=2)

print(f"Query: '{query}'\n")
print("Top 2 retrieved documents:")
for i, doc in enumerate(retrieved_docs):
    print(f"{i+1}. Content: '{doc.page_content}' (Source: {doc.metadata['source']})")

Metadata is Your Friend

Notice in the previous example how we included metadata with our documents? This is incredibly powerful!

  • Filtering: You can filter searches based on metadata (e.g., only search documents from a specific author or date).
  • Context: Metadata helps the LLM understand the source and relevance of the retrieved chunk, improving answer quality.
  • Debugging: It's easier to trace where information came from.

Always consider what metadata is useful to store alongside your text chunks.

Quick Check

You've learned about the steps to prepare your data for a RAG system. What is the correct sequence for storing and retrieving information?

Recap: Storing & Retrieving

Great job! In this lesson, you've mastered the critical steps of preparing your data for a RAG system:

  • Initializing an embedding model to convert text into numerical vectors.
  • Understanding the role of a vector store for efficient storage and similarity search.
  • Implementing the process of generating embeddings and storing them (e.g., using FAISS).
  • Performing similarity searches to retrieve relevant document chunks based on a query.
  • Recognizing the importance of metadata for richer context and filtering.

These skills are fundamental to building effective RAG applications!

무료로 시작

AI 튜터와 함께 LangChain / RAG / Vector DBs을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
48

자주 묻는 질문

“임베딩 저장 및 검색” 강의는 무료인가요?

네 — “임베딩 저장 및 검색” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

“임베딩 저장 및 검색”에서 뭘 배우나요?

문서 청크에서 임베딩을 생성하고 나중에 검색할 수 있도록 벡터 데이터베이스에 저장하는 과정을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 LangChain / RAG / Vector DBs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“임베딩 저장 및 검색” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 LangChain / RAG / Vector DBs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 텍스트 임베딩 이해
  2. 벡터 데이터베이스 입문
  3. 임베딩 저장 및 검색
  4. 임베딩 유사도 측정하기
← LangChain / RAG / Vector DBs(으)로 돌아가기