MongoDB를 DocArray 와 통합할 수 있습니다. DocArray는 Pydantic 문서 스키마를 기반으로 구축된 오픈 소스 Python 라이브러리입니다. DocArray는 Jina AI 에서 개발했습니다. 리눅스 재단 AI 및 데이터 이니셔티브 에서 호스팅합니다. 이 라이브러리는 중첩된 데이터, 비정형 데이터 및 혼합 미디어 데이터를 기본적으로 지원하도록 설계되었습니다.
The MongoDBAtlasDocumentIndex backend allows you to persist DocArray document collections in MongoDB, and you can run MongoDB Vector Search, MongoDB Search, hybrid search, and MQL filter queries against them from the same index object.
팁
Pydantic 데이터 유효성 검사 라이브러리에 대한 자세한 내용은 Pydantic 문서를 참조하세요. 선적 서류 비치.
시작하기
MongoDB를 사용하도록 DocArray를 구성하는 방법에 대한 튜토리얼을 완료하려면 MongoDB DocArray 통합 시작하기를 참조하세요.
설치
DocArray requires PyMongo v4.6.2 or later. To install the latest DocArray and PyMongo versions, select the tab corresponding to your package manager and run the following command:
pip install "docarray[mongodb]"poetry add docarray --extras mongodbuv add "docarray[mongodb]"환경 변수
Before you run the examples on this page, set the MONGODB_URI environment variable to the connection string for your MongoDB deployment.
사용법
To use MongoDB as the storage backend for a DocArray document collection, define a document schema by subclassing BaseDoc, DocArray's base document class. Then, pass your MongoDB connection string and database name to the MongoDBAtlasDocumentIndex constructor.
Select the Basic initialization tab to view a minimal MongoDB and DocArray configuration example, or select the Custom configuration tab to see how to configure the integration with custom settings.
To enable searches on a field, pass an index_name key in that field's json_schema_extra dictionary. For a vector field, specify the embedding dimensionality in the field's type annotation, such as NdArray[768]. The following example defines a schema with a text field and a vector field, then initializes an index typed to that schema:
import osfrom pydantic import Fieldfrom docarray import BaseDocfrom docarray.index import MongoDBAtlasDocumentIndexfrom docarray.typing import NdArray
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="my_database", index_name="articles",)To override DocArray's default search parameters for a field type, pass a DBConfig instance to the MongoDBAtlasDocumentIndex constructor. The instance's default_column_config dictionary maps a column's underlying type, such as an array or a string, to a dictionary of parameter overrides.
다음 예제는 배열 필드에 대한 기본 검색 매개변수를 재정의합니다.
import osfrom pydantic import Fieldfrom docarray import BaseDocfrom docarray.index import MongoDBAtlasDocumentIndexfrom docarray.typing import NdArrayimport bson
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"})
db_config = MongoDBAtlasDocumentIndex.DBConfig( mongo_connection_uri=os.environ["MONGODB_URI"], database_name="my_database", index_name="articles",)db_config.default_column_config[bson.BSONARR]["oversample_factor"] = 10db_config.default_column_config[bson.BSONARR]["max_candidates"] = 10000
index = MongoDBAtlasDocumentIndex[ArticleDoc](db_config=db_config)MongoDB 검색 또는 MongoDB 벡터 검색 쿼리를 실행하기 전에 배포 환경에 해당 인덱스를 생성해야 합니다. 자세한 내용은 이 페이지의 검색 인덱스 섹션을 참조하세요.
방법
This section describes the methods that the MongoDBAtlasDocumentIndex class provides. Each method operates on the collection that you configure when you initialize the index.
The following examples use the ArticleDoc schema and index object from the Basic initialization example, and assume that you've already created the corresponding MongoDB Vector Search and MongoDB Search indexes on your deployment.
index()
The index() method inserts one or more documents into the MongoDB collection.
The following example creates five ArticleDoc documents and inserts them into the collection:
import numpy as npfrom docarray import DocList
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)find()
The find() method runs an approximate nearest-neighbor MongoDB Vector Search query on a single vector field and returns the matching documents together with their similarity scores.
The following example searches the embedding field for the five documents most similar to a query vector:
query_vector = np.random.rand(768)
result = index.find( query=query_vector, search_field="embedding", limit=5,)
for doc, score in zip(result.documents, result.scores): print(f"[{score:.4f}] {doc.title}")find_batched()
The find_batched() method runs a find() operation for multiple query vectors in a single call.
The following example runs three searches on the embedding field in a single call:
queries = np.stack([np.random.rand(768) for _ in range(3)])
result = index.find_batched( queries=queries, search_field="embedding", limit=3,)
for batch_docs, batch_scores in zip(result.documents, result.scores): for doc, score in zip(batch_docs, batch_scores): print(f"[{score:.4f}] {doc.title}")텍스트 검색()
The text_search() method runs an MongoDB Search query against a str field whose json_schema_extra dictionary includes an index_name key.
The following example searches the body field for the documents that best match a text query:
result = index.text_search( query="flightless seabirds", search_field="body",)
for doc, score in zip(result.documents, result.scores): print(f"[{score:.4f}] {doc.title}")텍스트 검색 배치()
The text_search_batched() method runs text_search() for multiple query strings in a single call.
The following example runs three searches on the body field in a single call:
queries = ["flightless seabirds", "nesting site", "dive deeper"]
result = index.text_search_batched( queries=queries, search_field="body", limit=5,)
for query, docs, scores in zip(queries, result.documents, result.scores): print(f"Query: {query!r}") for doc, score in zip(docs, scores): print(f" [{score:.4f}] {doc.title}")filter()
The filter() method filters documents by using a MongoDB Query Language (MQL) expression. This method doesn't require a vector or text index, and it queries collection documents directly.
다음 예제는 제목이 정확히 일치하는 항목과 텍스트 패턴을 기준으로 문서를 필터링합니다.
# Documents whose title exactly matches one of a set of valuesexact_matches = index.filter(filter_query={"title": {"$in": ["Emperor Penguins", "Penguin Habitats"]}})for doc in exact_matches: print(doc.title)
# Documents matching a regular expression on a text fieldpattern_matches = index.filter(filter_query={"title": {"$regex": "Penguin"}})for doc in pattern_matches: print(doc.title)첨자 및 멤버십 구문
MongoDBAtlasDocumentIndex supports Python's subscript and membership syntax for looking up documents by their id value rather than providing separate named methods.
The following example retrieves, checks for, and deletes documents by id value:
# Retrieve a single document by iddoc = index[docs[0].id]
# Retrieve multiple documents by idsome_docs = index[[docs[0].id, docs[1].id]]
# Check whether a document exists in the indexdocs[0] in index
# Delete a single document by iddel index[docs[0].id]
# Delete multiple documents by iddel index[[docs[0].id, docs[1].id]]Both the subscript getter and del accept either a single id string or a sequence of id strings. If any requested id value doesn't exist in the collection, the getter and del raise a KeyError.
QueryBuilder
Use the build_query() method to define hybrid queries that combine vector search, full-text search, and MQL filters into a single MongoDB aggregation pipeline.
The build_query() method returns a QueryBuilder object. Chain method calls on the returned QueryBuilder, call build() to compile the query, then pass the result to the execute_query() method.
다음 예시는 벡터 검색, 텍스트 검색 및 필터를 하나의 하이브리드 쿼리로 결합한 것입니다.
query_vector = np.random.rand(768)
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(query)
for doc, score in zip(result.documents, result.scores): print(f"[{score:.4f}] {doc.title}")중요
인덱스 정의를 수정하세요
To use a field in a filter that you chain to .find(), you must index that field as the filter type in your MongoDB Vector Search index definition. To learn more, see Create a MongoDB Vector Search Index.
When you combine .filter() with .find(), the filter query runs inside the MongoDB Vector Search $vectorSearch stage. This stage supports only a subset of MQL operators. To learn which operators you can use, see Pre-Filter Search Data.
검색 인덱스
The MongoDBAtlasDocumentIndex class doesn't automatically create Search indexes for your schema. You must manually create a MongoDB Search index for each text field and a MongoDB Vector Search index for each vector field that you plan to search. To learn how to create these indexes, see Create a MongoDB Vector Search Index.
The following MongoDB Search index definition covers the body field in the ArticleDoc schema used in the examples on this page:
{ "mappings": { "dynamic": false, "fields": { "body": [ { "type": "string" } ] } }}The following MongoDB Vector Search index definition covers the embedding field:
{ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 768, "similarity": "cosine" } ]}Ensure that the index name matches the index_name value from your schema, such as embedding_vector_index or body_text_index. If a search query references a field whose index_name doesn't match an existing Search index, the query returns an error or no results.
추가 리소스
MongoDB에서 DocArray를 사용하는 방법에 대한 자세한 내용은 다음 자료를 참조하십시오.