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

Full Text Search ใน MongoDB ด้วย $text และ Text Index

การค้นหาข้อความเต็ม (Full Text Search) ใน MongoDB ใช้ $text operator ซึ่งต้องสร้าง Text Index ก่อน

> db.demo654.createIndex({Name: "text"});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo654.insertOne({"Name": "John Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04e924deddd72997713c8") }
> db.demo654.insertOne({"Name": "Chris Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04e9d4deddd72997713c9") }
> db.demo654.insertOne({"Name": "John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04ea54deddd72997713ca") }
> db.demo654.insertOne({"Name": "David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04eb24deddd72997713cb") }

แสดงข้อมูล:

> db.demo654.find();

คิวรี Full Text Search คำว่า "John"

> db.demo654.find({$text: {$search: "John"}});

ผลลัพธ์ - เจอ John Doe และ John Smith (เรียงตาม text score):


คุณสมบัติ $text Search

  • Case insensitive - ไม่สนใจตัวพิมพ์เล็ก/ใหญ่
  • Word stemming - "running" จะ match "run" (ภาษาอังกฤษ)
  • Phrase search - "John Doe" (คำพูดเต็ม)
  • Exclusion - -Smith (ยกเว้นคำว่า Smith)
  • Score sorting - เรียงตาม relevance score อัตโนมัติ

ดู Text Score

db.demo654.find(
  {$text: {$search: "John"}},
  {score: {$meta: "textScore"}}
).sort({score: {$meta: "textScore"}});

ข้อจำกัด

  • คอลเลกชันมีได้ Text Index เพียง 1 ตัว (แต่ครอบหลายฟิลด์ได้)
  • ไม่รองรับภาษาไทยการ stemming (ต้องใช้ regex หรือ external search engine)
  • ต้องการการค้นหาขั้นสูง ควรใช้ Elasticsearch, MeiliSearch, Typesense