0
# Indexing and Performance
1
2
Index management operations including creation, deletion, and inspection of indexes with support for compound indexes, text indexes, and index options. Indexes improve query performance and enforce constraints.
3
4
## Capabilities
5
6
### Index Creation
7
8
Create single and compound indexes with various options and configurations.
9
10
```python { .api }
11
def create_index(self, key_or_list, cache_for=300, session=None, **kwargs):
12
"""
13
Create an index on the collection.
14
15
Parameters:
16
- key_or_list: str or list, index key specification
17
- cache_for: int, index cache duration (ignored)
18
- session: ClientSession, session to use (ignored)
19
- **kwargs: index options (unique, sparse, etc.)
20
21
Returns:
22
str: index name
23
24
Raises:
25
OperationFailure: if index creation fails
26
"""
27
28
def create_indexes(self, indexes, session=None):
29
"""
30
Create multiple indexes.
31
32
Parameters:
33
- indexes: list, list of IndexModel instances or index specifications
34
- session: ClientSession, session to use (ignored)
35
36
Returns:
37
list: list of created index names
38
39
Raises:
40
OperationFailure: if index creation fails
41
"""
42
```
43
44
**Usage Example:**
45
46
```python
47
from mongomock import ASCENDING, DESCENDING
48
49
collection = mongomock.MongoClient().db.users
50
51
# Create single field index
52
index_name = collection.create_index('email')
53
54
# Create index with direction
55
index_name = collection.create_index([('age', ASCENDING)])
56
57
# Create compound index
58
index_name = collection.create_index([
59
('status', ASCENDING),
60
('created_at', DESCENDING)
61
])
62
63
# Create unique index
64
index_name = collection.create_index('username', unique=True)
65
66
# Create sparse index (only indexes documents with the field)
67
index_name = collection.create_index('phone', sparse=True)
68
69
# Create index with custom name
70
index_name = collection.create_index('email', name='email_unique_idx')
71
72
# Create multiple indexes at once
73
indexes = [
74
[('name', ASCENDING)],
75
[('age', ASCENDING), ('status', ASCENDING)],
76
[('created_at', DESCENDING)]
77
]
78
index_names = collection.create_indexes(indexes)
79
```
80
81
### Index Inspection
82
83
List and examine existing indexes on collections.
84
85
```python { .api }
86
def list_indexes(self, session=None):
87
"""
88
List all indexes on the collection.
89
90
Parameters:
91
- session: ClientSession, session to use (ignored)
92
93
Returns:
94
CommandCursor: cursor over index information documents
95
"""
96
97
def index_information(self, session=None):
98
"""
99
Get detailed information about all indexes.
100
101
Parameters:
102
- session: ClientSession, session to use (ignored)
103
104
Returns:
105
dict: mapping of index names to index information
106
"""
107
```
108
109
**Usage Example:**
110
111
```python
112
collection = mongomock.MongoClient().db.users
113
114
# List all indexes
115
indexes_cursor = collection.list_indexes()
116
for index in indexes_cursor:
117
print(f"Index: {index['name']}, Key: {index['key']}")
118
119
# Get index information dictionary
120
index_info = collection.index_information()
121
for name, info in index_info.items():
122
print(f"Index {name}: {info}")
123
124
# Check if specific index exists
125
if 'email_1' in index_info:
126
print("Email index exists")
127
```
128
129
### Index Deletion
130
131
Remove indexes from collections to free resources or modify index strategy.
132
133
```python { .api }
134
def drop_index(self, index_or_name, session=None):
135
"""
136
Drop a single index.
137
138
Parameters:
139
- index_or_name: str or list, index name or key specification
140
- session: ClientSession, session to use (ignored)
141
142
Returns:
143
None
144
145
Raises:
146
OperationFailure: if index doesn't exist or drop fails
147
"""
148
149
def drop_indexes(self, session=None):
150
"""
151
Drop all indexes except the default _id index.
152
153
Parameters:
154
- session: ClientSession, session to use (ignored)
155
156
Returns:
157
None
158
159
Raises:
160
OperationFailure: if drop operation fails
161
"""
162
```
163
164
**Usage Example:**
165
166
```python
167
collection = mongomock.MongoClient().db.users
168
169
# Drop index by name
170
collection.drop_index('email_1')
171
172
# Drop index by key specification
173
collection.drop_index([('age', 1)])
174
175
# Drop all indexes (except _id)
176
collection.drop_indexes()
177
178
# Handle errors
179
try:
180
collection.drop_index('nonexistent_index')
181
except mongomock.OperationFailure as e:
182
print(f"Index drop failed: {e}")
183
```
184
185
### Index Types and Options
186
187
Support for various MongoDB index types and configuration options.
188
189
**Single Field Indexes:**
190
191
```python
192
# Basic single field index
193
collection.create_index('field_name')
194
195
# Single field with direction
196
collection.create_index([('field_name', DESCENDING)])
197
```
198
199
**Compound Indexes:**
200
201
```python
202
# Multiple field index
203
collection.create_index([
204
('field1', ASCENDING),
205
('field2', DESCENDING),
206
('field3', ASCENDING)
207
])
208
```
209
210
**Index Options:**
211
212
```python
213
# Unique constraint
214
collection.create_index('email', unique=True)
215
216
# Sparse index (only documents with the field)
217
collection.create_index('optional_field', sparse=True)
218
219
# Partial index with filter
220
collection.create_index('status', partialFilterExpression={
221
'status': {'$in': ['active', 'pending']}
222
})
223
224
# TTL index (time-to-live)
225
collection.create_index('expiry_date', expireAfterSeconds=3600)
226
227
# Case-insensitive index
228
collection.create_index('name', collation={
229
'locale': 'en_US',
230
'strength': 2
231
})
232
```
233
234
**Usage Example:**
235
236
```python
237
collection = mongomock.MongoClient().db.users
238
239
# Create various index types
240
collection.create_index('email', unique=True, sparse=True)
241
242
collection.create_index([
243
('department', ASCENDING),
244
('hire_date', DESCENDING)
245
], name='dept_hire_idx')
246
247
# TTL index for session cleanup
248
collection.create_index('last_access', expireAfterSeconds=1800)
249
250
# Partial index for active users only
251
collection.create_index('performance_score',
252
partialFilterExpression={'status': 'active'})
253
```
254
255
### Index Performance Considerations
256
257
Understand index impact on query performance and storage.
258
259
**Query Optimization:**
260
261
```python
262
collection = mongomock.MongoClient().db.users
263
264
# Index supports efficient queries
265
collection.create_index([('status', 1), ('created_at', -1)])
266
267
# Efficient query (uses index)
268
recent_active = collection.find({
269
'status': 'active',
270
'created_at': {'$gte': datetime(2023, 1, 1)}
271
}).sort('created_at', -1)
272
273
# Index prefix usage
274
status_query = collection.find({'status': 'active'}) # Uses index prefix
275
```
276
277
**Index Maintenance:**
278
279
```python
280
# Monitor index usage
281
index_stats = collection.index_information()
282
for name, info in index_stats.items():
283
print(f"Index {name} has key: {info.get('key')}")
284
285
# Rebuild indexes if needed
286
collection.drop_indexes()
287
collection.create_index([('status', 1), ('created_at', -1)])
288
```
289
290
### Index Naming and Management
291
292
Control index naming and organize index strategy.
293
294
```python { .api }
295
# Index naming patterns
296
def gen_index_name(index_list):
297
"""
298
Generate index name from key specification.
299
300
Parameters:
301
- index_list: list, list of (key, direction) tuples
302
303
Returns:
304
str: generated index name
305
"""
306
```
307
308
**Usage Example:**
309
310
```python
311
from mongomock.helpers import gen_index_name
312
313
# Automatic name generation
314
index_spec = [('email', 1), ('status', 1)]
315
auto_name = gen_index_name(index_spec) # 'email_1_status_1'
316
317
# Custom index names
318
collection.create_index('email', name='users_email_unique')
319
collection.create_index([('dept', 1), ('role', 1)], name='dept_role_idx')
320
321
# Descriptive naming convention
322
collection.create_index('created_at', name='users_created_desc',
323
background=True)
324
```
325
326
## Index Utilities
327
328
```python { .api }
329
# Helper functions for index management
330
def create_index_list(key_or_list, direction=None):
331
"""
332
Create standardized index specification.
333
334
Parameters:
335
- key_or_list: str or list, index key specification
336
- direction: int, default direction for string keys
337
338
Returns:
339
list: standardized list of (key, direction) tuples
340
"""
341
```
342
343
**Usage Example:**
344
345
```python
346
from mongomock.helpers import create_index_list
347
348
# Convert various formats to standard format
349
spec1 = create_index_list('email') # [('email', 1)]
350
spec2 = create_index_list('age', -1) # [('age', -1)]
351
spec3 = create_index_list([('name', 1), ('age', -1)]) # unchanged
352
353
# Use in index operations
354
for spec in [spec1, spec2, spec3]:
355
index_name = collection.create_index(spec)
356
print(f"Created index: {index_name}")
357
```
358
359
## Index Constants
360
361
```python { .api }
362
# Sort/Index directions
363
ASCENDING = 1
364
DESCENDING = -1
365
366
# Index types (for documentation)
367
TEXT = 'text'
368
GEOSPHERE = '2dsphere'
369
HASHED = 'hashed'
370
```