Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

การสร้าง Multiple Indexes พร้อมกันใน MongoDB

การสร้าง Multiple Indexes พร้อมกันใน MongoDB ด้วย createIndexes()

ใช้ createIndexes() โดยส่ง Array ของ Index Specifications เพื่อสร้างหลาย Index ในคำสั่งเดียว ประหยัดเวลาและ Round Trips

ไวยากรณ์

db.collection.createIndexes([
    { "field1": 1 },
    { "field2": -1 },
    { "field3": 1, "field4": -1 }  // Compound Index
]);

ตัวอย่างสร้าง 5 Indexes พร้อมกัน

> db.multipleIndexesDemo.createIndexes([
    {"First": 1}, 
    {"Second": 1}, 
    {"Third": 1}, 
    {"Fourth": 1}, 
    {"Fifth": 1}
]);

ผลลัพธ์:

{ 
    "createdCollectionAutomatically" : true, 
    "numIndexesBefore" : 1, 
    "numIndexesAfter" : 6, 
    "ok" : 1 
}

คำอธิบาย: numIndexesBefore: 1 (แค่ _id index) -> numIndexesAfter: 6 (_id + 5 indexes ใหม่)

ตรวจสอบ Indexes ที่สร้าง

> db.multipleIndexesDemo.getIndexes();

ผลลัพธ์:

[ 
    { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.multipleIndexesDemo" }, 
    { "v" : 2, "key" : { "First" : 1 }, "name" : "First_1", "ns" : "test.multipleIndexesDemo" }, 
    { "v" : 2, "key" : { "Second" : 1 }, "name" : "Second_1", "ns" : "test.multipleIndexesDemo" }, 
    { "v" : 2, "key" : { "Third" : 1 }, "name" : "Third_1", "ns" : "test.multipleIndexesDemo" }, 
    { "v" : 2, "key" : { "Fourth" : 1 }, "name" : "Fourth_1", "ns" : "test.multipleIndexesDemo" }, 
    { "v" : 2, "key" : { "Fifth" : 1 }, "name" : "Fifth_1", "ns" : "test.multipleIndexesDemo" } 
]

คำอธิบาย Index Properties

  • v : Index Version (v2 เป็น Default)
  • key : Field และ Direction (1 = Ascending, -1 = Descending)
  • name : Index Name (Auto-generated: "field_1" หรือ "field_-1")
  • ns : Namespace (Database.Collection)

ตัวอย่างขั้นสูง: Compound, Unique, Partial, Sparse Indexes

db.collection.createIndexes([
    // Single Field
    { "email": 1 },
    
    // Compound Index
    { "lastName": 1, "firstName": 1 },
    
    // Unique Index
    { "username": 1 }, { unique: true, name: "unique_username" },
    
    // Partial Index (MongoDB 3.2+)
    { "status": 1 }, { 
        partialFilterExpression: { "status": { $in: ["active", "pending"] } },
        name: "partial_active_status"
    },
    
    // Sparse Index (เฉพาะ Document ที่มี Field นี้)
    { "optionalField": 1 }, { 
        sparse: true, 
        name: "sparse_optionalField" 
    },
    
    // TTL Index (Expire Documents)
    { "createdAt": 1 }, { 
        expireAfterSeconds: 2592000,  // 30 days
        name: "ttl_createdAt"
    },
    
    // Text Index
    { "title": "text", "content": "text" }, { 
        name: "text_title_content",
        weights: { title: 10, content: 1 }
    },
    
    // Geospatial Indexes
    { "location": "2dsphere" }, { name: "geo_location" },
    { "coordinates": "2d" }, { name: "geo_coordinates" }
]);

ข้อดีของ createIndexes() แบบ Batch

  • Atomic-ish: สร้างทั้งหมดหรือไม่สร้างเลย (แต่จริงๆ อาจสร้างบางตัวสำเร็จบางตัวล้มเหลว)
  • Single Round Trip: ส่งคำสั่งครั้งเดียว ลด Network Latency
  • Parallel Build (MongoDB 4.2+): สร้าง Index หลายตัวพร้อมกันได้ (background: true)
  • Error Handling: หาก Index ตัวไหน Fail จะ Rollback ตัวที่สร้างแล้ว (ในบาง Version)

Background Index Build (Production)

// Foreground (Default) - Block Write Operations
db.collection.createIndexes([...]);

// Background - Non-blocking (MongoDB 4.2+ ใช้ Parallel Build แทน)
db.collection.createIndexes([...], { background: true });

// MongoDB 4.2+ ไม่ต้องระบุ background: true แล้ว (เป็น Default พฤติกรรมที่ดีกว่า)

การจัดการ Indexes

// ดู Indexes ทั้งหมด
db.collection.getIndexes();

// ลบ Index โดยชื่อ
db.collection.dropIndex("First_1");

// ลบ Index โดย Spec
db.collection.dropIndex({ "First": 1 });

// Rebuild All Indexes
db.collection.reIndex();  // Blocking! ใช้เฉพาะ Maintenance Window

// Index Stats (MongoDB 3.2+)
db.collection.aggregate([{ $indexStats: {} }]);

Best Practices

  • วางแผน Index ตั้งแต่ออกแบบ Schema (Query Patterns First)
  • ใช้ createIndexes() สำหรับ Initial Setup / Migration
  • ตั้งชื่อ Index เองด้วย name option เพื่อจัดการง่ายขึ้น
  • Monitor Index Usage: db.collection.aggregate([{$indexStats: {}}])
  • Drop Unused Indexes เพื่อประหยัด RAM/Disk และเร่ง Write
  • Partial/Sparse Indexes ลดขนาด Index ได้มาก

หมายเหตุ: ensureIndex() ถูก Deprecated ตั้งแต่ MongoDB 3.0 ให้ใช้ createIndex() หรือ createIndexes() แทน