-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindexes.txt
593 lines (434 loc) · 16.8 KB
/
indexes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
.. _golang-indexes:
=======
Indexes
=======
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code example
:description: Learn how to use indexes in the MongoDB Go Driver to improve query performance and support various operations like updates and deletes.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to use **indexes** in the
{+driver-long+}.
Indexes support the efficient execution of queries in MongoDB. Without
indexes, MongoDB scans *every* document in a collection (a **collection
scan**) to find documents that match your query. Collection scans are
slow and can negatively affect the performance of your application. With
an appropriate index, MongoDB limits the number of documents it
inspects.
.. tip::
You can also use indexes in update operations, delete operations, and
:manual:`certain aggregation pipeline stages
</core/aggregation-pipeline/#pipeline-operators-and-indexes>`.
Query Coverage and Performance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A query in MongoDB can contain the following elements:
.. list-table::
:header-rows: 1
:stub-columns: 1
:widths: 20 20 60
* - Element
- Necessity
- Purpose
* - Query
- **Required**
- Specify the fields and values you're looking for.
* - Options
- **Optional**
- Specify how the query executes.
* - Projection
- **Optional**
- Specify the fields that MongoDB returns.
* - Sort
- **Optional**
- Specify the order MongoDB returns documents.
When you specify these elements in the same index, MongoDB returns
results directly from the index, also called a **covered query**.
.. important:: Sort Criteria
Your sort criteria must match or invert the order of the index.
Consider an index on the field ``name`` in ascending order (A-Z) and ``age`` in descending order (9-0):
.. code-block:: none
:copyable: false
name_1_age_-1
MongoDB uses this index when you sort your data by either:
- ``name`` ascending, ``age`` descending
- ``name`` descending, ``age`` ascending
Specifying a sort order of ``name`` and :guilabel:`age` ascending or :guilabel:`name` and ``age``
descending requires an in-memory sort.
To learn how to ensure your index covers your query criteria and
projection, see :manual:`Query Coverage
</core/query-optimization/#covered-query>`.
Operational Considerations
~~~~~~~~~~~~~~~~~~~~~~~~~~
To improve your query performance, create indexes on fields that appear
often in your queries and operations that return sorted results. Track
index memory and disk usage for capacity planning since
each index that you add consumes disk space and memory. In addition,
when a write operation updates an indexed field, MongoDB
also must update the related index.
Since MongoDB supports dynamic schemas, your application can query
against fields with unknown or arbitrary names. MongoDB 4.2
introduced :manual:`wildcard indexes </core/index-wildcard/>` to help
support these queries. Wildcard indexes are not designed to replace
workload-based index planning.
To learn more about designing your data model and choosing indexes
appropriate for your application, see :manual:`Indexing Strategies
</applications/indexes>` and :manual:`Data Modeling and Indexes
</core/data-model-operations/#indexes>`.
Index Types
-----------
MongoDB supports several index types to support querying your data. The
following sections describe and show how to create the most common index
types. To view a full list of index types, see :manual:`Indexes </indexes/>`.
.. _golang-single-field-index:
Single Field Indexes
~~~~~~~~~~~~~~~~~~~~
Single field indexes holds a reference to a field within a
collection's documents.
This index improves single field queries and sort performance, and
supports TTL indexes that automatically remove documents from a
collection after a certain amount of time.
.. note::
The ``_id_`` index is an example of a single field index. This index
is automatically created on the ``_id`` field when you create a new
collection.
Example
```````
The following example creates an index in ascending order on the
``title`` field in the ``sample_mflix.movies`` collection:
.. io-code-block::
:copyable: true
.. input::
:language: go
coll := client.Database("sample_mflix").Collection("movies")
indexModel := mongo.IndexModel{
Keys: bson.D{{"title", 1}},
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
Name of Index Created: title_1
.. _golang-compound-index:
Compound Indexes
~~~~~~~~~~~~~~~~
Compound indexes hold a reference to multiple fields within a
collection's documents. This index improves query and sort performance.
Example
```````
The following example creates a compound index on the ``fullplot`` and
``title`` fields in the ``sample_mflix.movies`` collection:
.. io-code-block::
:copyable: true
.. input::
:language: go
coll := client.Database("sample_mflix").Collection("movies")
indexModel := mongo.IndexModel{
Keys: bson.D{
{"fullplot", -1},
{"title", 1}
}
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
Name of Index Created: fullplot_-1_title_1
Multikey Indexes (Indexes on Array Fields)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Multikey indexes use the same syntax as a
:ref:`single field index <golang-single-field-index>` and a
:ref:`compound index <golang-compound-index>`. This index improves the
performance of queries that specify an array field as an index.
Example
```````
The following example creates a multikey index on the ``cast``
field in the ``sample_mflix.movies`` collection:
.. io-code-block::
:copyable: true
.. input::
:language: go
coll := client.Database("sample_mflix").Collection("movies")
indexModel := mongo.IndexModel{
Keys: bson.D{{"cast", -1}}
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
Name of Index Created: cast_-1
.. _golang-atlas-search-indexes:
Atlas Search and Atlas Vector Search Indexes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can programmatically manage your Atlas Search and Atlas Vector
Search indexes by using the {+driver-short+}.
The Atlas Search feature enables you to perform full-text searches on
collections hosted on MongoDB Atlas. To learn more about Atlas
Search, see the :atlas:`Atlas Search
</atlas-search/atlas-search-overview/>` documentation.
Atlas Vector Search enables you to perform semantic searches on vector
embeddings stored in Atlas. To learn more about Atlas
Vector Search, see the :atlas:`Atlas Vector Search
</atlas-vector-search/vector-search-overview/>` documentation.
To learn more about how to run Atlas Vector Search queries, see the
:ref:`golang-atlas-vector-search` guide.
The following sections contain code examples that demonstrate how to manage Atlas
Search and Atlas Vector Search indexes.
Create a Search Index
`````````````````````
You can create an Atlas Search or an Atlas Vector Search index by providing
an index definition to the ``SearchIndexView.CreateOne()`` method.
The following example creates an Atlas Search index on the ``plot`` field of the
``sample_mflix.movies`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/indexes/atlasVectorSearch.go
:language: go
:start-after: start-create-atlas-search
:end-before: end-create-atlas-search
:dedent:
The following example creates an Atlas Vector Search index on the ``plot_embedding``
field in the ``sample_mflix.embedded_movies`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/indexes/atlasVectorSearch.go
:language: go
:start-after: start-create-vector-search
:end-before: end-create-vector-search
:dedent:
List a Search Index
```````````````````
You can use the ``SearchIndexView.List()`` method to list an Atlas Search or Atlas
Vector Search index by specifying the name of the index.
The following example lists the details of the specified Atlas Search or Atlas
Vector Search index:
.. literalinclude:: /includes/fundamentals/code-snippets/indexes/atlasVectorSearch.go
:language: go
:start-after: start-list-index
:end-before: end-list-index
:dedent:
Update a Search Index
`````````````````````
You can use the ``SearchIndexView.UpdateOne()`` method to update an Atlas Search
or Atlas Vector Search index by specifying the name of the index and the new
index definition.
The following example updates an Atlas Vector Search index by providing the name
of the index and a new index definition:
.. literalinclude:: /includes/fundamentals/code-snippets/indexes/atlasVectorSearch.go
:language: go
:start-after: start-update-index
:end-before: end-update-index
:dedent:
Delete a Search Index
`````````````````````
You can use the ``SearchIndexView.DropOne()`` method to delete an Atlas Search or
Atlas Vector Search index by specifying the name of the index.
The following example deletes an Atlas Search or Atlas Vector Search
index with the specified name:
.. literalinclude:: /includes/fundamentals/code-snippets/indexes/atlasVectorSearch.go
:language: go
:start-after: start-delete-index
:end-before: end-delete-index
:dedent:
.. _golang-clustered-indexes:
Clustered Indexes
~~~~~~~~~~~~~~~~~
Clustered indexes improve the performance of insert, update, and delete
operations on **clustered collections**. Clustered collections store
documents ordered by the clustered index key value.
To create a clustered index, specify the clustered index option with the
``_id`` field as the key and the unique field as ``true`` when you
create your collection.
Example
```````
The following example creates a clustered index on the ``_id`` field in
the ``db.tea`` collection:
.. code-block:: go
:copyable: true
db := client.Database("db")
cio := bson.D{{"key", bson.D{{"_id", 1}}}, {"unique", true}}
opts := options.CreateCollection().SetClusteredIndex(cio)
db.CreateCollection(context.TODO(), "tea", opts)
.. _golang-text-indexes:
Text Indexes
~~~~~~~~~~~~
Text indexes support text search queries on string content. This index
requires a string field or an array of strings. MongoDB supports text
search for several languages. You can specify the default language as an
option when creating the index.
A collection can only contain one text index. If you want to create a
text index for multiple text fields, you must create a :ref:`compound
index <golang-compound-index>`. The text search runs on all the text fields
within the compound index.
.. tip::
Text indexes differ from the more powerful
:atlas:`Atlas full text search indexes </atlas-search>`.
We recommend Atlas search for Atlas users.
Example
```````
The following example creates a text index on the ``plot`` field with
``italian`` as the default language in the ``sample_mflix.movies``
collection:
.. io-code-block::
:copyable: true
.. input::
:language: go
coll := client.Database("sample_mflix").Collection("movies")
indexModel := mongo.IndexModel{Keys: bson.D{{"plot", "text"}, {"default_language", "italian"}}}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
Name of Index Created: plot_text
.. _golang-geo-indexes:
Geospatial Indexes
~~~~~~~~~~~~~~~~~~
MongoDB supports queries containing geospatial coordinate data by using
**2dsphere indexes**. A ``2dsphere`` index must be in a GeoJSON objects
field.
This index allows you to perform the following:
- Query geospatial data for inclusion, intersection, and proximity.
- Calculation of distances on a Euclidean plane and for working with the
"legacy coordinate pairs" syntax used in MongoDB 2.2 and earlier.
Example
```````
The ``location.geo`` field in a document from the
``sample_mflix.theaters`` collection is a GeoJSON Point object that
describes the coordinates of the theater:
.. code-block:: javascript
:emphasize-lines: 13-16
{
"_id" : ObjectId("59a47286cfa9a3a73e51e75c"),
"theaterId" : 104,
"location" : {
"address" : {
"street1" : "5000 W 147th St",
"city" : "Hawthorne",
"state" : "CA",
"zipcode" : "90250"
},
"geo" : {
"type" : "Point",
"coordinates" : [
-118.36559,
33.897167
]
}
}
}
The following example creates a ``2dsphere`` index on the ``location.geo`` field:
.. important::
Attempting to create a geospatial index on a field that is covered by
a geospatial index results in an error.
.. io-code-block::
:copyable: true
.. input::
:language: go
indexModel := mongo.IndexModel{
Keys: bson.D{{"location.geo", "2dsphere"}}
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
location.geo_2dsphere
.. _golang-unique-indexes:
Unique Indexes
~~~~~~~~~~~~~~
Unique indexes ensure that the indexed fields do not store duplicate
values. By default, MongoDB creates a unique index on the ``_id`` field
during the creation of a collection.
To create a unique index, specify the field or combination of fields
that you want to prevent duplication on and set the ``unique`` option to
``true``.
Example
```````
The following example creates a unique, descending index on the ``theaterId`` field:
.. io-code-block::
:copyable: true
.. input::
:language: go
indexModel := mongo.IndexModel{
Keys: bson.D{{"theaterId", -1}},
Options: options.Index().SetUnique(true),
}
name, err := coll.Indexes().CreateOne(context.TODO(), indexModel)
if err != nil {
panic(err)
}
fmt.Println("Name of Index Created: " + name)
.. output::
:language: none
:visible: false
Name of Index Created: theaterId_-1
.. _golang-remove-index:
Remove an Index
---------------
You can delete any index from a collection except the default unique index on the
``_id`` field. To remove an index, pass the name of your index to the
``DropOne()`` method.
The following example removes an index called ``title_1``
from the ``sample_mflix.movies`` collection:
.. code-block:: go
coll := client.Database("sample_mflix").Collection("movies")
err := coll.Indexes().DropOne(context.TODO(), "title_1")
if err != nil {
panic(err)
}
Additional Information
----------------------
To learn more about the indexes mentioned, see the following
guides:
- :manual:`Single Field Indexes </core/index-single>`
- :manual:`TTL Indexes </core/index-ttl>`
- :manual:`Compound Indexes </core/index-compound>`
- :manual:`Multikey Indexes </core/index-multikey>`
- :manual:`Text Indexes </core/index-text>`
- :manual:`Compound Text Index Restrictions </core/index-text/#std-label-text-index-compound>`
- :manual:`Geospatial Queries </geospatial-queries/>`
- :manual:`GeoJSON Objects </reference/geojson>`
- :manual:`Unique Indexes </core/index-unique>`
- :v5.3:`Clustered Indexes </reference/method/db.createCollection/#std-label-db.createCollection.clusteredIndex>`
- :v5.3:`Clustered Collections </core/clustered-collections/#std-label-clustered-collections>`
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-change-document`
- :ref:`golang-delete-guide`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about the methods discussed in this
guide and related ones, see the following API Documentation:
- `IndexModel <{+api+}/mongo#IndexModel>`__
- `IndexOptions <{+api+}/mongo/options#IndexOptions>`__
- `SetDefaultLanguage()
<{+api+}/mongo/options#IndexOptionsBuilder.SetDefaultLanguage>`__
- `CreateOne() <{+api+}/mongo#IndexView.CreateOne>`__
- `DropOne() <{+api+}/mongo#IndexView.DropOne>`__
- `CreateCollection() <{+api+}/mongo#Database.CreateCollection>`__
- `CreateCollectionOptions <{+api+}/mongo/options#CreateCollectionOptions>`__
- `SearchIndexes <{+api+}/mongo#Collection.SearchIndexes>`__
- `SearchIndexView <{+api+}/mongo#SearchIndexView>`__