文档菜单
文档首页
/ / /
PyMongo

使用索引优化查询

本页内容

  • 概述
  • 示例应用程序
  • 单字段索引
  • 复合索引
  • 多键索引
  • Atlas 搜索索引
  • 创建搜索索引
  • 列出搜索索引
  • 更新搜索索引
  • 删除搜索索引
  • 文本索引
  • 地理空间索引
  • 唯一索引
  • 通配符索引
  • 聚簇索引
  • 删除索引

在本页中,您可以查看可复制的代码示例,展示如何使用 PyMongo 中的常见类型索引。

提示

要了解有关与索引一起工作的更多信息,请参阅与索引一起工作指南。要了解本页上显示的任何索引的更多信息,请参阅每个部分中提供的链接。

要从本页使用示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保将代码示例中的所有占位符(如<连接字符串 URI>)替换为 MongoDB 部署的相关值。

您可以使用以下示例应用程序来测试本页上的代码示例。要使用示例应用程序,请执行以下步骤

  1. 确保您已安装 PyMongo。

  2. 复制以下代码并将其粘贴到一个新的 .py 文件中。

  3. 从本页复制代码示例并将其粘贴到文件中的指定行。

1import pymongo
2from pymongo import MongoClient
3
4try:
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
17except 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 搜索和向量搜索索引指南。

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

要了解更多关于删除索引的信息,请参阅《使用索引指南》中的删除索引

返回

运行数据库命令