Alibaba Cloud OpenSearch Vector Store

Alibaba Cloud OpenSearch Vector Store

Alibaba Cloud OpenSearch Vector Search Edition을 LlamaIndex 벡터 스토어로 사용하는 노트북이에요. 인덱스 생성, 기존 스토어 연결, 메타데이터 필터링까지 살펴볼게요.

출처: 문서

본문

Alibaba Cloud OpenSearch Vector Search Edition은 Alibaba Group이 개발한 대규모 분산 검색 엔진입니다. Taobao, Tmall, Cainiao, Youku 및 중국 본토 외 지역의 고객에게 제공되는 기타 전자상거래 플랫폼을 포함한 Alibaba Group 전체에 검색 서비스를 제공합니다. 또한 Alibaba Cloud OpenSearch의 기본 엔진이기도 합니다. 수년간의 개발을 거쳐 높은 가용성, 높은 신시성, 비용 효율성에 대한 비즈니스 요구를 충족하게 되었습니다. 또한 자동화된 O&M 시스템을 제공하므로 비즈니스 특성에 따라 커스텀 검색 서비스를 구축할 수 있습니다.

실행하려면 인스턴스가 있어야 합니다.

Setup

이 노트북을 colab에서 여는 경우 LlamaIndex 🦙를 설치해야 할 수 있습니다.

%pip install llama-index-vector-stores-alibabacloud-opensearch
%pip install llama-index
import logging
import sys


logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

OpenAI 액세스 키 제공

OpenAI로 임베딩을 사용하려면 OpenAI API 키를 제공해야 합니다:

import openai


OPENAI_API_KEY = getpass.getpass("OpenAI API Key:")
openai.api_key = OPENAI_API_KEY

데이터 다운로드

!mkdir -p 'data/paul_graham/'
!wget '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'

문서 로드

from llama_index.core import SimpleDirectoryReader
from IPython.display import Markdown, display
# load documents
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
print(f"Total documents: {len(documents)}")

Alibaba Cloud OpenSearch Vector Store 객체 생성

다음 단계를 실행하려면 Alibaba Cloud OpenSearch Vector Service 인스턴스가 있어야 하고, 테이블을 구성해야 합니다.

# if run fllowing cells raise async io exception, run this
import nest_asyncio


nest_asyncio.apply()
# initialize without metadata filter
from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.vector_stores.alibabacloud_opensearch import (
    AlibabaCloudOpenSearchStore,
    AlibabaCloudOpenSearchConfig,
)


config = AlibabaCloudOpenSearchConfig(
    endpoint="*****",
    instance_id="*****",
    username="your_username",
    password="your_password",
    table_name="llama",
)


vector_store = AlibabaCloudOpenSearchStore(config)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context
)

인덱스 쿼리

# set Logging to DEBUG for more detailed outputs
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
display(Markdown(f"<b>{response}</b>"))

기존 스토어에 연결

이 스토어는 Alibaba Cloud OpenSearch에 기반을 두므로 정의상 영구적입니다. 따라서 이전에 생성·채워진 스토어에 연결하려면 다음과 같이 합니다:

from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.alibabacloud_opensearch import (
    AlibabaCloudOpenSearchStore,
    AlibabaCloudOpenSearchConfig,
)


config = AlibabaCloudOpenSearchConfig(
    endpoint="***",
    instance_id="***",
    username="your_username",
    password="your_password",
    table_name="llama",
)


vector_store = AlibabaCloudOpenSearchStore(config)


# Create index from existing stored vectors
index = VectorStoreIndex.from_vector_store(vector_store)
query_engine = index.as_query_engine()
response = query_engine.query(
    "What did the author study prior to working on AI?"
)


display(Markdown(f"<b>{response}</b>"))

메타데이터 필터링

Alibaba Cloud OpenSearch 벡터 스토어는 쿼리 시점에 메타데이터 필터링을 지원합니다. 아래 셀들은 완전히 새로운 테이블에서 이 기능을 보여줍니다.

이 데모에서는 간결함을 위해 단일 소스 문서(../data/paul_graham/paul_graham_essay.txt 텍스트 파일)를 로드합니다. 그럼에도 문서에 커스텀 메타데이터를 붙여, 문서에 첨부된 메타데이터 조건으로 쿼리를 제한하는 방법을 보여줍니다.

from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.vector_stores.alibabacloud_opensearch import (
    AlibabaCloudOpenSearchStore,
    AlibabaCloudOpenSearchConfig,
)


config = AlibabaCloudOpenSearchConfig(
    endpoint="****",
    instance_id="****",
    username="your_username",
    password="your_password",
    table_name="llama",
)


md_storage_context = StorageContext.from_defaults(
    vector_store=AlibabaCloudOpenSearchStore(config)
)




def my_file_metadata(file_name: str):
    """Depending on the input file name, associate a different metadata."""
    if "essay" in file_name:
        source_type = "essay"
    elif "dinosaur" in file_name:
        # this (unfortunately) will not happen in this demo
        source_type = "dinos"
    else:
        source_type = "other"
    return {"source_type": source_type}




# Load documents and build index
md_documents = SimpleDirectoryReader(
    "../data/paul_graham", file_metadata=my_file_metadata
).load_data()
md_index = VectorStoreIndex.from_documents(
    md_documents, storage_context=md_storage_context
)

쿼리 엔진에 필터를 추가합니다:

from llama_index.core.vector_stores import MetadataFilter, MetadataFilters


md_query_engine = md_index.as_query_engine(
    filters=MetadataFilters(
        filters=[MetadataFilter(key="source_type", value="essay")]
    )
)
md_response = md_query_engine.query(
    "How long it took the author to write his thesis?"
)


display(Markdown(f"<b>{md_response}</b>"))

필터링이 실제 작동하는지 테스트하려면 "dinos" 문서만 사용하도록 바꿔 보세요… 이번에는 답변이 없을 거예요 :)

더 알아보기 (Learn more)