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

หลีกเลี่ยงปัญหาประสิทธิภาพ Regex ใน MongoDB ด้วย Text Index

การใช้ Regular Expression ($regex) อย่างไม่ถูกต้องอาจทำให้คิวรีช้าเพราะไม่ใช้ดัชนีได้ วิธีแก้คือสร้าง Text Index และใช้ $text search แทน

> db.demo531.createIndex({"CountryName": "text", "Name": "text"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo531.insertOne({CountryName: "US", "Name": "Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b60ef4dcbee04fbbbf2") }
> db.demo531.insertOne({CountryName: "UK", "Name": "David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b6cef4dcbee04fbbbf3") }
> db.demo531.insertOne({CountryName: "AUS", "Name": "chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2b74ef4dcbee04fbbbf4") }
> db.demo531.insertOne({CountryName: "US", "Name": "CHRIS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2badef4dcbee04fbbbf5") }

แสดงข้อมูล:

> db.demo531.find();
{ "_id" : ObjectId("5e8b2b60ef4dcbee04fbbbf2"), "CountryName" : "US", "Name" : "Chris" }
{ "_id" : ObjectId("5e8b2b6cef4dcbee04fbbbf3"), "CountryName" : "UK", "Name" : "David" }
{ "_id" : ObjectId("5e8b2b74ef4dcbee04fbbbf4"), "CountryName" : "AUS", "Name" : "chris" }
{ "_id" : ObjectId("5e8b2badef4dcbee04fbbbf5"), "CountryName" : "US", "Name" : "CHRIS" }

คิวรีค้นหา "chris" ใน Name โดย CountryName = "US" (ใช้ Text Search)

> db.demo531.find({CountryName: "US", "Name": {$regex: "chris", $options: "i"}}).limit(4);

ผลลัพธ์ (Regex ก็ยังทำงาน แต้อาจช้ากว่า Text Search):


วิธีที่ดีกว่า: ใช้ $text Search

> db.demo531.find({$text: {$search: "chris"}, CountryName: "US"});

เปรียบเทียบ

แนวทางปฏิบัติ: สร้าง Text Index บนฟิลด์ที่ค้นหาบ่อย ใช้ $text สำหรับ full-text search, ใช้ $regex ^pattern สำหรับ prefix search

วิธีใช้ดัชนีได้Case InsensitivePartial Match
$regex (ไม่มี ^)ไม่ได้ได้ (option i)ได้
$regex (มี ^)ได้ได้ (option i)ได้ (prefix only)
$text searchได้ (Text Index)ได้ได้ (word boundary)