İsminin NoSQL olması bizi şaşırtmasın, MongoDB indeksleri destekler.
Bir başka açıklama şöyleIndexes 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.
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:11. MongoDB reads 4 times more documents (from disk) than it actually returns2. 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.
- Primary index on the document key field (_id)
- Single field index
- Compound index
- Multikey index
- Text Indexes
- 2dsphere index
- 2d index
- geohaystack index is deprecated in MongoDB 5.0.
- Hashed index
- Partial Index
- 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
Index yine aynı sırada kullanılır. Şöyle yaparız. hint() sorgusu index kullanılmasını sağlar.db.getCollection("movieTicket").ensureIndex({"showDate":1, "seatNo":1, "status":1});
db.movieTicket.find({"showDate":"", "seatNo": {$in: ['A1', 'A2', 'A3', 'A4']}})
.hint({"seatNo": 1, "showDate": 1, "status": 1});
Hiç yorum yok:
Yorum Gönder