对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

将 MongoDB 与 DocArray 集成

您可以将 MongoDB 与 DocArray 集成。 DocArray 是一个基于 Pydantic 文档模式构建的开源 Python 库,由 Jina AI 创建。 并由 Linux 基金会人工智能与数据计划 托管 该库旨在原生支持嵌套、非结构化和混合媒体数据。

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 文档。 文档。

要完成配置 DocArray 以使用 MongoDB 的教程,请参阅 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]"

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",)

在运行 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.

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)

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}")

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}")

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.

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.

要了解有关将 DocArray 与 MongoDB 结合使用的更多信息,请参阅以下资源: