1.ESR: equality, sort, range
ESR is a naming convention for the ordering rule section 10 introduced: put Equality fields first, Sort fields second, Range fields last, when designing a compound index for a specific query. It is a repeatable procedure, not a one-off insight.
Key features
- E — equality: exact-match fields, e.g. { status: "shipped" }
- S — sort: fields the query calls .sort() on
- R — range: $gt/$gte/$lt/$lte/$in-with-many-values fields
- Write the compound index in E, S, R order, regardless of the order fields appear in the query
- A field never used as equality, sort, or range in the target query does not belong in this index
Classifying a query's fields for ESR
- read the query — find + sort
- label each field — E, S, or R
- index in E-S-R order — regardless of query field order
Command
// For a target query: db.createIndex({ <equality fields>: 1, <sort fields>: dir, <range fields>: 1 })ESR: classify each field as Equality, Sort, or Range for the target query, then build the compound index in that order — regardless of how the query happens to be written.