MongoDB를 DocArray와 통합하면 다양한 형식의 문서 컬렉션을 저장하고 MongoDB의 검색 기능을 사용하여 검색할 수 있습니다. 이 튜토리얼에서는 DocArray를 구성하여 문서 컬렉션의 저장소 백엔드로 MongoDB를 사용하도록 설정한 다음, 해당 컬렉션에 대해 벡터 검색, 전체 텍스트 검색 및 하이브리드 쿼리를 실행합니다. 이 튜토리얼에서 수행하는 작업은 다음과 같습니다.
환경을 설정합니다.
MongoDB 컬렉션과 인덱스를 구성하세요.
벡터 검색, 전문 검색 및 하이브리드 쿼리를 정의하십시오.
파일 실행합니다.
배경
DocArray is an open-source Python library for representing, sending, and storing multimodal data by using Pydantic-based document schemas. The MongoDBAtlasDocumentIndex class persists a DocArray document schema in a MongoDB collection and routes search queries to the corresponding MongoDB Vector Search or MongoDB Search index.
DocArray는 이러한 인덱스를 자동으로 생성하지 않습니다. 검색 쿼리를 실행하려면 스키마에 정의된 각 벡터 필드에 대한 MongoDB 벡터 검색 인덱스와 각 텍스트 필드에 대한 MongoDB 검색 인덱스를 생성해야 합니다. 이 튜토리얼에서는 두 인덱스를 모두 생성하는 단계를 설명합니다.
전제 조건
이 튜토리얼을 완료하려면 다음 리소스가 있어야 합니다:
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 버전 6.0.11을 실행하는 Atlas 클러스터, 7.0.2 이상. 당신의 IP 주소가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Python과 Docker를 사용하여 만든 로컬 Atlas 배포서버입니다.
atlas-local-lib-py(pip install atlas-local-lib-py)를 설치하여 로컬 배포서버를 프로그래밍으로 만들고 관리할 수 있습니다. 자세한 내용은 atlas-local-lib-py 리포지토리를 참조하십시오.검색 및 벡터 검색이 설치된 MongoDB Community 클러스터.
Python v3.8 이상.
환경 설정
이 섹션에서는 필수 종속성을 설치하고, 환경 변수를 설정하고, 프로젝트 파일을 생성하여 환경을 준비합니다.
환경 변수를 설정합니다.
docarray-mongodb-project 디렉토리에서 .env 파일을 만들고 다음 코드를 추가합니다.
MONGODB_URI="<connection-string>"<connection-string>을 Atlas 클러스터 또는 로컬 Atlas 배포서버의 연결 문자열로 교체합니다.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net중요한: 연결 문자열 에 데이터베이스 사용자의 자격 증명 포함되어 있는지 확인하세요. 연결 문자열 찾는 방법에 대해 자세히 학습하려면 클라이언트 라이브러리를 통해 클러스터에 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true학습 내용은 연결 문자열을 참조하세요.
프로젝트 파일 만들기
docarray-mongodb-project 디렉토리에서 main.py이라는 파일을 만듭니다. 환경 변수를 로드하기 위해 다음 코드를 이 파일에 추가합니다:
import osfrom dotenv import load_dotenvimport numpy as npfrom pydantic import Fieldfrom docarray import BaseDoc, DocListfrom docarray.index import MongoDBAtlasDocumentIndexfrom docarray.typing import NdArray
load_dotenv()다음 단계에서는 이 파일에 코드를 추가하여 스키마를 정의하고, 인덱스를 생성하고, 데이터를 쿼리합니다.
MongoDB 컬렉션을 구성하세요
이 섹션에서는 MongoDB 컬렉션에 대한 문서 스키마를 정의하고, 해당 컬렉션에 문서를 삽입하고, 검색 쿼리에 필요한 MongoDB 벡터 검색 및 MongoDB 검색 인덱스를 생성합니다.
문서 스키마를 정의하세요.
Add the following code to your main.py file to define a schema with a text field and a vector field, then connect that schema to a MongoDB collection:
class ArticleDoc(BaseDoc): title: str body: str = Field(json_schema_extra={"index_name": "body_text_index"}) embedding: NdArray[768] = Field(json_schema_extra={"index_name": "embedding_vector_index"})
index = MongoDBAtlasDocumentIndex[ArticleDoc]( mongo_connection_uri=os.environ["MONGODB_URI"], database_name="docarray_tutorial", index_name="articles",)The index_name key in each field's json_schema_extra dictionary sets the name of the MongoDB Vector Search or MongoDB Search index that covers that field. The vector field's type annotation, NdArray[768], sets the embedding dimensionality.
문서를 컬렉션에 추가하세요.
Add the following code to your main.py file to create five documents and insert them into your collection:
docs = DocList[ArticleDoc]( [ ArticleDoc( title="Emperor Penguins", body="Emperor penguins are the tallest and heaviest of all penguin species, standing up to 4 feet.", embedding=np.random.rand(768), ), ArticleDoc( title="Penguin Habitats", body="Penguins are flightless seabirds that live almost exclusively below the equator. Some island-dwellers can be found in warmer climates.", embedding=np.random.rand(768), ), ArticleDoc( title="Penguins of Patagonia", body="Patagonia is home to five penguin species: Magellanic, Humboldt, Gentoo, Southern Rockhopper, and King.", embedding=np.random.rand(768), ), ArticleDoc( title="Penguin Diving Depths", body="Emperor penguins can dive deeper than any other bird, reaching depths of over 500 meters.", embedding=np.random.rand(768), ), ArticleDoc( title="Penguin Nesting Habits", body="Some penguin species mate for life and return to the same nesting site every year.", embedding=np.random.rand(768), ), ])
index.index(docs)print(f"Indexed {len(docs)} documents.")This tutorial uses randomly generated vectors as a placeholder for the embedding field. In production, generate this vector from an embedding model.
검색 인덱스를 생성합니다.
Add the following code to your main.py file to create a MongoDB Vector Search index on the embedding field and a MongoDB Search index on the body field:
import timefrom pymongo.mongo_client import MongoClientfrom pymongo.operations import SearchIndexModel
client = MongoClient(os.environ["MONGODB_URI"])collection = client["docarray_tutorial"]["articles"]
vector_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 768, "similarity": "cosine", }, { "type": "filter", "path": "title", }, ] }, name="embedding_vector_index", type="vectorSearch",)
text_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": False, "fields": { "body": [ {"type": "string"}, ], }, } }, name="body_text_index",)
collection.create_search_index(model=vector_index_model)collection.create_search_index(model=text_index_model)
print("\nWaiting for the MongoDB Vector Search index to finish building...")time.sleep(60)
client.close()The vector index definition also indexes the title field as the filter type. In a future step, you will combine a filter on the title field with a vector search, which requires this filter type index.
인덱스 빌드 데 약 1분 정도 소요됩니다. 빌드되는 동안 인덱스는 초기 동기화 상태입니다. 빌드가 완료되면 컬렉션 의 데이터 쿼리를 시작할 수 있습니다.
데이터 쿼리
이 섹션에서는 벡터 검색, 전체 텍스트 검색, 그리고 MQL 필터를 사용하여 두 가지 검색 유형을 결합한 하이브리드 쿼리를 실행합니다.
벡터 검색 쿼리를 실행합니다.
Add the following code to your main.py file to search the embedding field for the documents most similar to a query vector:
query_vector = np.random.rand(768)
result = index.find( query=query_vector, search_field="embedding", limit=5,)
print("\nVector search results:")for doc, score in zip(result.documents, result.scores): print(f" [{score:.4f}] {doc.title}")Because query_vector is also a randomly generated vector, the ranking and scores in your output differ from the example output in this tutorial.
전체 텍스트 검색 쿼리를 실행합니다.
Add the following code to your main.py file to search the body field for documents that match a text query:
result = index.text_search( query="flightless seabirds", search_field="body",)
print("\nFull-text search results:")for doc, score in zip(result.documents, result.scores): print(f" [{score:.4f}] {doc.title}")하이브리드 쿼리를 실행합니다.
Add this code to your main.py file to run a query that performs the following tasks:
Searches the
embeddingfield for vectors similar toquery_vectorSearches the
bodyfield for the text"flightless seabirds"Filters the combined results for documents whose
titlevalue isEmperor PenguinsorPenguin Habitats
hybrid_query = ( index.build_query() .find(query=query_vector, search_field="embedding") .text_search(query="flightless seabirds", search_field="body") .filter(query={"title": {"$in": ["Emperor Penguins", "Penguin Habitats"]}}) .build(limit=5))
result = index.execute_query(hybrid_query)
print("\nHybrid query results:")for doc, score in zip(result.documents, result.scores): print(f" [{score:.4f}] {doc.title}")파일 실행
main.py 파일을 실행하려면 docarray-mongodb-project 디렉토리에서 다음 명령을 실행하세요:
python main.py명령이 성공적으로 실행되면 출력은 다음과 유사합니다.
Indexed 5 documents.
Waiting for the MongoDB Vector Search index to finish building...
Vector search results: [0.8853] Penguin Diving Depths [0.8775] Emperor Penguins [0.8766] Penguin Habitats [0.8744] Penguin Nesting Habits [0.8672] Penguins of Patagonia
Full-text search results: [1.1433] Penguin Habitats
Hybrid query results: [0.6429] Penguin Habitats [0.1667] Emperor Penguins다음 단계
To learn more about the MongoDBAtlasDocumentIndex class, including its full parameter and method reference, see Integrate MongoDB with DocArray.
이 튜토리얼에서 생성하는 MongoDB 벡터 검색 및 MongoDB 검색 인덱스에 대한 자세한 내용은 MongoDB 벡터 검색 인덱스 생성하기를 참조하세요.