19 Ocak 2021 Salı

MongoDB Index

Giriş
İsminin NoSQL olması bizi şaşırtmasın, MongoDB indeksleri destekler.
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.
Indexes are special data structures [1] that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.
Bir başka açıklama şöyle
Keep in mind that MongoDB has a limit of 32MB in holding documents for a sort operation. If you don’t use indexes, then the database is forced to hold a various amount of documents (depending on your database) while sorting. If MongoDB hits the limitation, then the database will return an error or an empty set.
İndex Performansı
Profiler veya explain() kullandıktan sonra index performansı ölçülebilir. Açıklaması şöyle
The MongoDB profiler results revealed our existing indexes are sub-optimal. The totalDocsExamined to nReturned ratio 5:1
1. MongoDB reads 4 times more documents (from disk) than it actually returns
2. 80% of the documents are filtered only after reading from disk
Index Çeşitleri
Açıklaması şöyle
MongoDB has a rich set of indexes to support quick lookups and range scans.
  1. Primary index on the document key field (_id)
  2. Single field index
  3. Compound index
  4. Multikey index
  5. Text Indexes
  6. 2dsphere index
  7. 2d index
  8. geohaystack index is deprecated in MongoDB 5.0.
  9. Hashed index
  10. Partial Index
  11. Wildcard Indexes

Simple Index vs Compound Index
Compound Index iki veya daha fazla createIndex() çağrısı ile yapılır.

Örnek
Index yaratmak için şöyle yaparız
db.getCollection("people")
  .createIndex({ssn:1});
Index kullanmak için şöyle yaparız
db.getCollection("people")
  .find({"ssn":"123"});
Örnek
Şöyle yaparız
db.getCollection("movieTicket")
  .ensureIndex({"showDate":1, "seatNo":1, "status":1});
Index yine aynı sırada kullanılır. Şöyle yaparız. hint() sorgusu index kullanılmasını sağlar.
db.movieTicket.find({"showDate":"", "seatNo": {$in: ['A1', 'A2', 'A3', 'A4']}})
.hint({"seatNo": 1, "showDate": 1, "status": 1});

Hiç yorum yok:

Yorum Gönder