Elasticsearch
Elasticsearch
이번엔 Elasticsearch를 LlamaIndex의 벡터 저장소로 활용하는 기본 예제를 살펴볼게요. Elasticsearch는 전문 검색과 벡터 검색을 모두 지원하는 검색 데이터베이스라서, 문서를 청크로 나누고 임베딩해 저장한 뒤 쿼리하는 전형적인 RAG 흐름을 구성하기 좋아요. 오픈소스 임베딩 모델로 진행하니 별도 비용 없이 따라 해 볼 수 있답니다.
출처: 문서
본문
Elasticsearch 는 전문(full text) 검색과 벡터 검색을 지원하는 검색 데이터베이스입니다.
기본 예제 (Basic Example)
이 기본 예제에서는 Paul Graham 에세이를 가져와 청크로 나누고, 오픈소스 임베딩 모델을 사용해 임베딩한 뒤 Elasticsearch에 로드하고 쿼리합니다. 다양한 검색 전략을 사용하는 예제는 Elasticsearch Vector Store 문서를 참고하세요.
콜랩 노트북에서 열고 있다면 LlamaIndex 설치가 필요할 거예요 🦙.
%pip install -qU llama-index-vector-stores-elasticsearch llama-index-embeddings-huggingface llama-index
# import
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.elasticsearch import ElasticsearchStore
from llama_index.core import StorageContext
# set up OpenAI
import os
import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
데이터 다운로드
!mkdir -p 'data/paul_graham/'
!wget -nv 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
2024-05-13 15:10:43 URL:https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt [75042/75042] -> "data/paul_graham/paul_graham_essay.txt" [1]
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import Settings
# define embedding function
Settings.embed_model = HuggingFaceEmbedding(
model_name="BAAI/bge-small-en-v1.5"
)
# load documents
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
# define index
vector_store = ElasticsearchStore(
es_url="http://localhost:9200", # see Elasticsearch Vector Store for more authentication options
index_name="paul_graham_essay",
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
# Query Data
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)
The author worked on writing and programming outside of school. They wrote short stories and tried writing programs on an IBM 1401 computer. They also built a microcomputer kit and started programming on it, writing simple games and a word processor.