가이드: 기존 Pinecone 벡터 저장소로 벡터 저장소 인덱스 사용하기

가이드: 기존 Pinecone 벡터 저장소로 벡터 저장소 인덱스 사용하기 (Using Vector Store Index with Existing Pinecone Vector Store)

Pinecone에 이미 데이터가 들어 있는데 LlamaIndex를 얹고 싶다면, 이 가이드의 흐름을 그대로 따라 하면 돼요. 벡터 저장소 인덱스를 기존 Pinecone 컬렉션에 연결해, 이미 저장된 벡터를 그대로 검색할 수 있답니다. 'text' 필드로 쓸 프로퍼티를 잘 선택하는 게 핵심 포인트예요.

출처: 문서

본문

콜랩 노트북에서 열고 있다면 LlamaIndex 설치가 필요할 거예요 🦙.

%pip install llama-index-embeddings-openai
%pip install llama-index-vector-stores-pinecone
!pip install llama-index
import os
import pinecone
api_key = os.environ["PINECONE_API_KEY"]
pinecone.init(api_key=api_key, environment="eu-west1-gcp")

기존 Pinecone 벡터 저장소 준비하기 (Prepare Sample "Existing" Pinecone Vector Store)

인덱스 생성 (Create index)

indexes = pinecone.list_indexes()
print(indexes)
['quickstart-index']
if "quickstart-index" not in indexes:
    # dimensions are for text-embedding-ada-002
    pinecone.create_index(
        "quickstart-index", dimension=1536, metric="euclidean", pod_type="p1"
    )
pinecone_index = pinecone.Index("quickstart-index")
pinecone_index.delete(deleteAll="true")
{}

샘플 데이터 정의 (Define sample data)

4개의 샘플 책을 만듭니다.

books = [
    {
        "title": "To Kill a Mockingbird",
        "author": "Harper Lee",
        "content": (
            "To Kill a Mockingbird is a novel by Harper Lee published in"
            " 1960..."
        ),
        "year": 1960,
    },
    {
        "title": "1984",
        "author": "George Orwell",
        "content": (
            "1984 is a dystopian novel by George Orwell published in 1949..."
        ),
        "year": 1949,
    },
    {
        "title": "The Great Gatsby",
        "author": "F. Scott Fitzgerald",
        "content": (
            "The Great Gatsby is a novel by F. Scott Fitzgerald published in"
            " 1925..."
        ),
        "year": 1925,
    },
    {
        "title": "Pride and Prejudice",
        "author": "Jane Austen",
        "content": (
            "Pride and Prejudice is a novel by Jane Austen published in"
            " 1813..."
        ),
        "year": 1813,
    },
]

데이터 추가 (Add data)

샘플 책을 Pinecone에 추가합니다(배열의 content 필드를 임베딩해서).

import uuid
from llama_index.embeddings.openai import OpenAIEmbedding


embed_model = OpenAIEmbedding()
entries = []
for book in books:
    vector = embed_model.get_text_embedding(book["content"])
    entries.append(
        {"id": str(uuid.uuid4()), "values": vector, "metadata": book}
    )
pinecone_index.upsert(entries)
{'upserted_count': 4}

기존 Pinecone 벡터 저장소에 대해 쿼리하기 (Query Against "Existing" Pinecone Vector Store)

from llama_index.vector_stores.pinecone import PineconeVectorStore
from llama_index.core import VectorStoreIndex
from llama_index.core.response.pprint_utils import pprint_source_node

'text' 필드로 사용할 클래스 프로퍼티를 올바르게 선택해야 합니다.

vector_store = PineconeVectorStore(
    pinecone_index=pinecone_index, text_key="content"
)
retriever = VectorStoreIndex.from_vector_store(vector_store).as_retriever(
    similarity_top_k=1
)
nodes = retriever.retrieve("What is that book about a bird again?")

검색된 노드를 살펴봅시다. 책 데이터가 LlamaIndex Node 객체로 로드되었고, "content" 필드가 주요 텍스트로 사용되었음을 확인할 수 있습니다.

pprint_source_node(nodes[0])
Document ID: 07e47f1d-cb90-431b-89c7-35462afcda28
Similarity: 0.797243237
Text: author: Harper Lee title: To Kill a Mockingbird year: 1960.0  To
Kill a Mockingbird is a novel by Harper Lee published in 1960......

나머지 필드는 메타데이터(metadata)로 로드되어야 합니다.

nodes[0].node.metadata
{'author': 'Harper Lee', 'title': 'To Kill a Mockingbird', 'year': 1960.0}

더 알아보기 (Learn more)