MongoDBを DocArray と統合できます Pydanticドキュメントスキーマをベースに構築されたオープンソースのPythonライブラリであるDocArrayは、 Jina AI によって作成されました。 Linux Foundation AI & Dataイニシアチブ が主催しています。 このライブラリは、ネストされたデータ、非構造化データ、および混合メディアデータをネイティブにサポートするように設計されています。
MongoDBAtlasDocumentIndexバックエンドを使用すると、DocArray ドキュメント コレクションを MongoDB に永続化でき、同じインデックス オブジェクトから MongoDB Vector Search、MongoDB Search、ハイブリッド検索、および MQL フィルタ クエリを実行できます。
Tip
Pydanticデータ検証ライブラリの詳細については、 Pydanticを 参照してください。 ドキュメント。
はじめる
DocArrayをMongoDBを使用するように構成するチュートリアルを完了するには、 「MongoDB DocArray統合の開始」を参照してください。
インストール
DocArrayにはPyMongo v 4.6.2以降が必要です。最新のDocArrayとPyMongoをインストールするには、パッケージマネージャーに対応するタブを選択し、次のコマンドを実行してください。
pip install "docarray[mongodb]"poetry add docarray --extras mongodbuv add "docarray[mongodb]"環境変数
このページの例を実行する前に、環境変数MONGODB_URIに、ご使用の MongoDB デプロイメントの接続文字列を設定してください。
使用法
DocArrayドキュメントコレクションのストレージバックエンドとしてMongoDBを使用するには、DocArrayの基本ドキュメントクラスであるBaseDocサブクラス化してドキュメントスキーマを定義します。次に、MongoDB接続文字列とデータベース名をMongoDBAtlasDocumentIndexコンストラクタに渡します。
MongoDBとDocArrayの最小限の設定例を表示するにはBasic initializationタブを選択し、カスタム設定で統合を構成する方法を確認するにはCustom configurationタブを選択してください。
フィールドの検索を有効にするには、そのフィールドの辞書json_schema_extraにindex_nameキーを渡します。ベクトルフィールドの場合は、フィールドの型注釈で埋め込み次元数を指定します(例: NdArray[768] )。次の例では、テキストフィールドとベクトルフィールドを含むスキーマを定義し、そのスキーマに型付けされたインデックスを初期化します。
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",)DocArray のフィールドタイプのデフォルトの検索パラメータをオーバーライドするには、 DBConfigインスタンスをMongoDBAtlasDocumentIndexコンストラクタに渡します。インスタンスのdefault_column_configディクショナリは、配列や文字列などの列の基となる型を、パラメータのオーバーライドのディクショナリにマッピングします。
以下の例は、配列フィールドのデフォルトの検索パラメータを上書きします。
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 Search または MongoDB Vector Search クエリを実行する前に、デプロイメントに該当するインデックスを作成する必要があります。詳細については、このページの「検索インデックス」セクションを参照してください。
メソッド
このセクションでは、 MongoDBAtlasDocumentIndexクラスが提供するメソッドについて説明します。各メソッドは、インデックスの初期化時に設定したコレクションに対して動作します。
以下の例では、 Basic initialization例のArticleDocスキーマとindexオブジェクトを使用し、デプロイメント上で対応する MongoDB Vector Search インデックスと MongoDB Search インデックスが既に作成されていることを前提としています。
index()
index()メソッドは、1 つ以上のドキュメントを MongoDB コレクションに挿入します。
次の例では、5つのArticleDocドキュメントを作成し、コレクションに挿入します。
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()
find()メソッドは、単一のベクトルフィールドに対して近似最近傍法の MongoDB ベクトル検索クエリを実行し、一致するドキュメントとその類似度スコアを返します。
次の例では、 embeddingフィールドを検索して、クエリ ベクトルに最も類似した 5 つのドキュメントを探します。
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()
find_batched()メソッドは、単一の呼び出しで複数のクエリベクトルに対してfind()操作を実行します。
次の例では、 embeddingフィールドに対して 3 つの検索を 1 つの呼び出しで実行します。
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}")テキスト検索()
text_search()メソッドは、 strフィールドに対して MongoDB 検索クエリを実行します。このフィールドのjson_schema_extraディクショナリにはindex_nameキーが含まれています。
次の例では、 bodyフィールドを検索して、テキスト クエリに最も一致するドキュメントを探します。
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}")text_search_batched()
text_search_batched()メソッドは、単一の呼び出しで複数のクエリ文字列に対してtext_search()を実行します。
次の例では、 bodyフィールドに対して 3 つの検索を 1 つの呼び出しで実行します。
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()
filter()メソッドは、MongoDB クエリ言語 (MQL) 式を使用してドキュメントをフィルタリングします。このメソッドは、ベクトルインデックスやテキストインデックスを必要とせず、コレクションドキュメントを直接クエリします。
以下の例では、タイトルの完全一致とテキストパターンに基づいて文書をフィルタリングしています。
# 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 個別の名前付きメソッドを提供するのではなく、 id値でドキュメントを検索するための Python の添え字とメンバーシップ構文をサポートします。
次の例では、 id値に基づいてドキュメントを取得、チェック、削除します。
# 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]]添え字ゲッターとdelはどちらも単一のid文字列またはid文字列のシーケンスを受け入れます。要求されたid値がコレクションに存在しない場合、ゲッターとdel KeyErrorを発生させます。
クエリ ビルダ
build_query()メソッドを使用して、ベクトル検索、全文検索、および MQL フィルタを単一の MongoDB 集計パイプラインに組み合わせたハイブリッドクエリを定義します。
build_query()メソッドはQueryBuilderオブジェクトを返します。チェーンメソッドは返されたQueryBuilderを呼び出し、 build()を呼び出してクエリをコンパイルし、その結果をexecute_query()メソッドに渡します。
次の例では、ベクトル検索、テキスト検索、およびフィルタを単一のハイブリッドクエリに組み合わせています。
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}")重要
インデックス定義を変更する
.find()に連鎖するフィルタでフィールドを使用するには、MongoDB ベクター検索インデックス定義でそのフィールドをfilter型としてインデックス化する必要があります。詳細については、 「MongoDB ベクター検索インデックスの作成」を参照してください。
.filter()と.find()を組み合わせると、フィルタクエリはMongoDBベクトル検索$vectorSearchステージ内で実行されます。このステージでは、MQL演算子のサブセットのみがサポートされています。使用可能な演算子については、 「検索データの事前フィルタ」を参照してください。
検索インデックス
MongoDBAtlasDocumentIndexクラスは、スキーマの検索インデックスを自動的に作成しません。検索対象とするテキストフィールドごとに MongoDB 検索インデックスを、ベクターフィールドごとに MongoDB ベクトル検索インデックスを手動で作成する必要があります。これらのインデックスの作成方法については、 「MongoDB ベクトル検索インデックスの作成」を参照してください。
以下の MongoDB 検索インデックス定義は、このページの例で使用されているArticleDocスキーマのbodyフィールドを対象としています。
{ "mappings": { "dynamic": false, "fields": { "body": [ { "type": "string" } ] } }}以下のMongoDBベクター検索インデックス定義は、 embeddingフィールドを対象としています。
{ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 768, "similarity": "cosine" } ]}インデックス名が、スキーマのindex_name値embedding_vector_indexやbody_text_indexなど)と一致していることを確認してください。検索クエリが、 index_nameが既存の検索インデックスと一致しないフィールドを参照している場合、クエリはエラーを返すか、結果が返されません。
追加リソース
DocArrayをMongoDBで使用する方法の詳細については、以下のリソースを参照してください。