您可以将 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 集群类型之一:
使用 Python 和 Docker 创建的本地 Atlas 部署。安装
atlas-local-lib-py(pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。安装了Search 和向量搜索的 MongoDB Community 集群。
Python v3.8 或更高版本。
设置环境
在本节中,您将通过安装所需的依赖项、设置环境变量和创建项目文件来准备环境。
设置环境变量。
在您的 docarray-mongodb-project 目录中,创建一个 .env 文件并添加以下代码:
MONGODB_URI="<connection-string>"将 <connection-string> 替换为您的 Atlas 集群或本地部署的连接字符串。
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net重要: 确保连接字符串包含数据库用户的凭证。要学习有关查找连接字符串的更多信息,请参阅通过客户端库连接到集群。
创建项目文件。
在您的 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 Vector Search 和 MongoDB Search 索引。
定义文档架构。
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.
构建索引大约需要一分钟时间。在构建时,索引处于初始同步状态。构建完成后,您可以开始查询集合中的数据。
查询数据
在本节中,您将运行向量搜索、全文搜索以及将两种搜索类型与 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 向量搜索索引。