Skip to content

Commit db1f9ec

Browse files
DOCSP-45670 Indexes guide (#49)
(cherry picked from commit 548b9bd)
1 parent 0671213 commit db1f9ec

File tree

5 files changed

+254
-1
lines changed

5 files changed

+254
-1
lines changed

snooty.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ not-available = "N/A"
4040
package = "MongoDB.EntityFrameworkCore"
4141
api-root = "https://mongodb.github.io/mongo-efcore-provider/{+full-version+}/api"
4242
driver-api-root = "https://mongodb.github.io/mongo-csharp-driver/3.0.0/api"
43+
driver-docs-root = "https://www.mongodb.com/docs/drivers/csharp/current"
4344

4445
[[banners]]
4546
targets = ["index.txt"]

source/fundamentals.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,9 @@ Fundamentals
1515
Query Data </fundamentals/query-data>
1616
Write Data </fundamentals/write-data>
1717
Optimistic Concurrency </fundamentals/optimistic-concurrency>
18+
Indexes </fundamentals/indexes>
1819

1920
- :ref:`entity-framework-configure`
21+
- :ref:`entity-framework-query-data`
22+
- :ref:`entity-framework-write-data`
23+
- :ref:`entity-framework-indexes`

source/fundamentals/indexes.txt

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
.. _entity-framework-indexes:
2+
3+
=============================
4+
Optimize Queries with Indexes
5+
=============================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: EF, EF Core, index, optimization, code example
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to define **indexes** in the {+provider-short+}.
24+
Indexes can improve the efficiency of queries and add additional functionality
25+
to querying and storing documents.
26+
27+
Without indexes, MongoDB must scan every document in a collection to find the
28+
documents that match each query. These collection scans are slow and can
29+
negatively affect the performance of your application. However, if you create an
30+
index that covers a query, MongoDB can use the index to limit the
31+
documents it must inspect.
32+
33+
To improve query performance, build indexes on fields that appear often in your
34+
application's queries and operations that return sorted results. Each index that
35+
you add consumes disk space and memory when active, so we recommend that you
36+
track index memory and disk usage for capacity planning.
37+
38+
Create an Index
39+
---------------
40+
41+
The {+provider-short+} supports the following types of indexes:
42+
43+
- :ref:`Single field indexes <entity-framework-single-field-index>`
44+
- :ref:`Compound indexes <entity-framework-compound-index>`
45+
- :ref:`Unique indexes <entity-framework-unique-index>`
46+
47+
The examples in this guide use the sample application created in the
48+
:ref:`<entity-framework-quickstart>` guide. After you set up the quick start
49+
application, you can run the examples in this guide by adding the code to the
50+
``OnModelCreating()`` method of the ``PlanetDbContext``, as shown in the following
51+
example:
52+
53+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
54+
:language: csharp
55+
:start-after: start-model-creating
56+
:end-before: end-model-creating
57+
58+
.. note::
59+
60+
The {+provider-short+} creates your indexes when you call the
61+
``dbContext.Database.EnsureCreated()`` method. You cannot modify or delete indexes by
62+
using the provider after they are created. If you
63+
need to modify or delete an index in your application, you must use the
64+
{+csharp-driver-short+} directly.
65+
66+
To learn more about working with indexes in the driver, see the `Indexes
67+
<{+driver-docs-root+}/fundamentals/indexes/>`__ guide in the {+csharp-driver-short+}
68+
documentation.
69+
70+
The following sections show how to create each of the preceding types of indexes.
71+
72+
.. _entity-framework-single-field-index:
73+
74+
Single Field Index
75+
~~~~~~~~~~~~~~~~~~
76+
77+
:manual:`Single Field Indexes </core/indexes/index-types/index-single/>` are
78+
indexes with a reference to a single field within a collection's documents. They
79+
improve single field query and sort performance. The ``_id_`` index is an
80+
example of a single field index.
81+
82+
You can create a single field index by calling the ``HasIndex()`` method with a
83+
lambda expression that specifies the field to index. The following example
84+
creates a single field index on a ``Planet`` entity:
85+
86+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
87+
:language: csharp
88+
:start-after: start-single-field-index
89+
:end-before: end-single-field-index
90+
91+
.. _entity-framework-compound-index:
92+
93+
Compound Index
94+
~~~~~~~~~~~~~~
95+
96+
:manual:`Compound indexes </core/indexes/index-types/index-compound>` are
97+
indexes that cover multiple fields within a collection's documents.
98+
These indexes improve multi-field query and sort performance.
99+
100+
You can create a compound index by calling the ``HasIndex()`` method with a
101+
lambda expression that specifies the fields to index. The following example
102+
creates a compound index on a ``Planet`` entity:
103+
104+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
105+
:language: csharp
106+
:start-after: start-compound-index
107+
:end-before: end-compound-index
108+
109+
.. _entity-framework-unique-index:
110+
111+
Unique Index
112+
~~~~~~~~~~~~
113+
114+
Unique indexes ensure that multiple documents don't contain the same value for the
115+
indexed field. By default, MongoDB creates a unique index on the ``_id`` field
116+
during the creation of a collection. You cannot modify or remove this index.
117+
118+
You can create a unique index by creating an index by using the
119+
``HasIndex()`` methods as shown in the preceding sections, then chaining the
120+
``IsUnique()`` method. The following example creates a unique index on a
121+
``Planet`` entity:
122+
123+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
124+
:language: csharp
125+
:start-after: start-unique-index
126+
:end-before: end-unique-index
127+
128+
Index Options
129+
-------------
130+
131+
You can specify options when creating your index to customize the index
132+
name, properties, or index type. The following
133+
sections describe some of the options that you can specify.
134+
135+
Named Index
136+
~~~~~~~~~~~
137+
138+
By default, MongoDB creates an index with a generated name based on the fields
139+
and options for the index. To specify a custom name
140+
for the index, pass in the name as a string when you create the index. The
141+
following example creates a compound index on the ``Planet`` entity with the
142+
name ``"named_order"``:
143+
144+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
145+
:language: csharp
146+
:start-after: start-named-index
147+
:end-before: end-named-index
148+
149+
Index Order
150+
~~~~~~~~~~~
151+
152+
By default, MongoDB creates indexes in ascending order. You can call the
153+
``IsDescending()`` method when creating a new index to create the index in
154+
descending order. The following example creates a descending index on a
155+
``Planet`` entity:
156+
157+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
158+
:language: csharp
159+
:start-after: start-descending-index
160+
:end-before: end-descending-index
161+
162+
.. note::
163+
164+
Using a descending single field index might negatively impact index
165+
performance. For best performance, use only ascending indexes.
166+
167+
MongoDB-Specific Options
168+
~~~~~~~~~~~~~~~~~~~~~~~~
169+
170+
You can specify additional MongoDB-specific options when creating an index by using the
171+
``HasCreateIndexOptions()`` method and passing in an instance of the
172+
``CreateIndexOptions`` class of the {+csharp-driver-short+}. You can pass in any
173+
options that the ``CreateIndexOptions`` class supports. To learn more about
174+
the supported options, see the `CreateIndexOptions
175+
<{+driver-api-root+}/MongoDB.Driver/MongoDB.Driver.CreateIndexOptions.html>`__ API
176+
documentation.
177+
178+
The following example creates an index and specifies the ``Sparse`` option to
179+
create a :manual:`Sparse Index </core/index-sparse/>`:
180+
181+
.. literalinclude:: /includes/fundamentals/code-examples/indexes.cs
182+
:language: csharp
183+
:start-after: start-sparse-index
184+
:end-before: end-sparse-index
185+
186+
Additional Information
187+
----------------------
188+
189+
For more information about indexes in MongoDB, see the :manual:`Indexes
190+
</core/indexes/>` guide in the {+mdb-server+} manual.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// start-model-creating
2+
protected override void OnModelCreating(ModelBuilder modelBuilder)
3+
{
4+
base.OnModelCreating(modelBuilder);
5+
6+
// Paste example code here
7+
8+
}
9+
// end-model-creating
10+
11+
// start-single-field-index
12+
modelBuilder.Entity<Planet>(p =>
13+
{
14+
p.HasIndex(p => p.orderFromSun);
15+
p.ToCollection("planets");
16+
});
17+
// end-single-field-index
18+
19+
// start-compound-index
20+
modelBuilder.Entity<Planet>(p =>
21+
{
22+
p.HasIndex(p => new { p.orderFromSun, p.name });
23+
p.ToCollection("planets");
24+
});
25+
// end-compound-index
26+
27+
// start-unique-index
28+
modelBuilder.Entity<Planet>(p =>
29+
{
30+
p.HasIndex(p => p.orderFromSun).IsUnique();
31+
p.ToCollection("planets");
32+
});
33+
// end-unique-index
34+
35+
// start-descending-index
36+
modelBuilder.Entity<Planet>(p =>
37+
{
38+
p.HasIndex(p => p.orderFromSun).IsDescending();
39+
p.ToCollection("planets");
40+
});
41+
// end-descending-index
42+
43+
// start-named-index
44+
modelBuilder.Entity<Planet>(p =>
45+
{
46+
p.HasIndex(p => new { p.orderFromSun, p.name }, "named_order");
47+
p.ToCollection("planets");
48+
});
49+
// end-named-index
50+
51+
// start-sparse-index
52+
modelBuilder.Entity<Planet>(p =>
53+
{
54+
p.HasIndex(p => p.orderFromSun)
55+
.HasCreateIndexOptions(new CreateIndexOptions() { Sparse = true });
56+
p.ToCollection("planets");
57+
});
58+
// end-sparse-index

source/upgrade.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ changes. However, the underlying {+csharp-driver-short+} introduces many
5858
potentially breaking changes in the v3.0 release, which might affect your
5959
application. To learn more about the breaking changes in v3.0 of the
6060
{+csharp-driver-short+}, see the `Upgrade to Version 3.0 guide
61-
<https://www.mongodb.com/docs/drivers/csharp/current/upgrade/v3/>`__
61+
<{+driver-docs-root+}/upgrade/v3/>`__
6262
in the {+csharp-driver-short+} documentation.
6363

6464

0 commit comments

Comments
 (0)