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

การสร้างดัชนีสำหรับฟิลด์ข้อความยาวเพื่อเพิ่มความเร็วคิวรีใน MongoDB

เพิ่มประสิทธิภาพการค้นหาข้อความด้วย Index และ $regex

สำหรับฟิลด์ที่เก็บข้อความยาว สามารถสร้างดัชนีทั่วไป (single field index) ได้ แต่การค้นหาด้วย $regex จะใช้ดัชนีได้ก็ต่อเมื่อ regex เป็น "prefix pattern" (ขึ้นต้นด้วยข้อความคงที่) เท่านั้น

ตัวอย่างสร้างดัชนีและข้อมูล

> db.demo46.createIndex({ "Name": 1 });
> db.demo46.insertOne({ "Name": "John Smith" });
> db.demo46.insertOne({ "Name": "John Doe" });
> db.demo46.insertOne({ "Name": "Chris Brown" });

แสดงข้อมูลทั้งหมด

> db.demo46.find();

ผลลัพธ์:

{ "_id": ObjectId("..."), "Name": "John Smith" }
{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "Chris Brown" }

คำสั่งค้นหาขึ้นต้นด้วย "John" (ใช้ดัชนีได้)

> db.demo46.find({ Name: { $regex: /^John/ } });

ผลลัพธ์ที่ได้

{ "_id": ObjectId("..."), "Name": "John Doe" }
{ "_id": ObjectId("..."), "Name": "John Smith" }

ข้อสังเกตสำคัญ

  • /^John/ (ขึ้นต้นด้วย John) -> ใช้ดัชนีได้ (Index Scan)
  • /John/ (มี John อยู่ตรงไหนก็ได้) -> ไม่ใช้ดัชนีได้ (Collection Scan)
  • /John$/ (ลงท้ายด้วย John) -> ไม่ใช้ดัชนีได้

แนวทางแก้ไขสำหรับการค้นหาข้อความเต็มรูปแบบ

หากต้องการค้นหาข้อความแบบเต็มรูปแบบ (Full Text Search) ควรใช้ Text Index แทน:

> db.demo46.createIndex({ "Name": "text" });
> db.demo46.find({ $text: { $search: "John" } });

Text Index รองรับการค้นหาคำ ไม่ใช่แค่ prefix pattern และมีฟีเจอร์เช่น weighting, language stemming ฯลฯ