文档首页 → 开发应用程序 → Python 驱动程序 → PyMongo
使用索引优化查询
概述
本页,您可以查看可复制的代码示例,展示如何使用 PyMongo 中的常见索引类型。
提示
要了解有关与索引一起工作的更多信息,请参阅与索引一起工作指南。要了解本页上显示的任何索引的更多信息,请参阅每个部分中提供的链接。
要使用本页上的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。确保将代码示例中的所有占位符,例如<连接字符串 URI>
,替换为您的 MongoDB 部署的相关值。
示例应用程序
您可以使用以下示例应用程序测试本页上的代码示例。要使用示例应用程序,请执行以下步骤
确保已安装 PyMongo。
复制以下代码并将其粘贴到新的
.py
文件中。从本页复制代码示例并将其粘贴到文件中指定的行。
1 import pymongo 2 from pymongo import MongoClient 3 4 try: 5 uri = "<connection string URI>" 6 client = MongoClient(uri) 7 8 database = client["<database name>"] 9 collection = database["<collection name>"] 10 11 # start example code here 12 13 # end example code here 14 15 client.close() 16 17 except Exception as e: 18 raise Exception( 19 "The following error occurred: ", e)
单字段索引
result = collection.create_index("<field name>") print(f'Index created: {result}')
要了解有关单字段索引的更多信息,请参阅单字段索引指南。
复合索引
result = collection.create_index([ ("<field name one>", pymongo.ASCENDING), ("<field name two>", pymongo.ASCENDING) ]) print(f"Index created: {result}")
要了解有关复合索引的更多信息,请参阅复合索引指南。
多键索引
result = collection.create_index("<array field name>") print(f'Index created: {result}')
了解多键索引的更多信息,请参阅多键索引指南。
Atlas搜索索引
了解有关Atlas搜索索引的更多信息,请参阅Atlas搜索索引指南。
创建搜索索引
index = { "definition": { "mappings": { "dynamic": True } }, "name": "<index name>", } collection.create_search_index(index)
了解有关创建搜索索引的更多信息,请参阅创建搜索索引指南。
列出搜索索引
results = list(collection.list_search_indexes()) print('Existing search indexes:\n') for index in results: print(index)
了解有关列出搜索索引的更多信息,请参阅列出搜索索引指南。
更新搜索索引
new_index = { "definition": { "mappings": { "dynamic": True } }, "name": "<index name>", } collection.update_search_index("<name of index to update>", new_index) print(f"Search index updated: {result}")
了解有关更新搜索索引的更多信息,请参阅更新搜索索引指南。
删除搜索索引
collection.drop_index("<index name>") print(f"Search index deleted: {result}")
了解有关删除搜索索引的更多信息,请参阅删除搜索索引指南。
文本索引
result = collection.create_index( [( "<field name>", "text")], default_language="english", weights={ "<field name>": 10 } ) print(f"Index created: {result}")
了解有关文本索引的更多信息,请参阅文本索引指南。
地理空间索引
result = collection.create_index([("<GeoJSON object field>", "2dsphere")]) print(f'Index created: {result}')
了解有关地理空间索引的更多信息,请参阅地理空间索引指南。
唯一索引
result = collection.create_index("<field name>", unique=True) print(f"Index created: {result}")
了解有关唯一索引的更多信息,请参阅唯一索引指南。
通配符索引
result = collection.create_index({"$**": pymongo.ASCENDING}) print(f'Index created: {result}')
了解有关通配符索引的更多信息,请参阅通配符索引指南。
聚集索引
collection = database.create_collection("<collection name>", clusteredIndex={ "key": {"_id": 1}, "unique": True })
了解有关聚集索引的更多信息,请参阅聚集索引指南。
移除索引
collection.drop_index("<index_name>")
了解有关移除索引的更多信息,请参阅《使用索引指南》中的移除索引。