what i've learned today

Search index ใน MongoDB

คำนี้อาจหมายถึง 2 อย่างที่ต่างกัน:

1. MongoDB Index ปกติ

เหมาะกับการค้นหาแบบตรงเงื่อนไข เช่น

db.products.find({
  categoryId: "food",
  status: "ACTIVE"
}).sort({ createdAt: -1 })

อาจสร้าง index:

db.products.createIndex({
  categoryId: 1,
  status: 1,
  createdAt: -1
})

ช่วยเรื่อง:

  • filter ด้วย = , ช่วงค่า, วันที่
  • sort
  • unique constraint
  • ลดการทำ COLLSCAN หรือการไล่อ่านทั้ง collection

2. Atlas Search Index

เป็น search engine ที่ MongoDB Atlas เตรียมไว้สำหรับการค้นหาข้อความ คล้าย Elasticsearch เช่น:

  • ค้นหาคำว่า “เสื้อยืดผู้ชาย”
  • autocomplete
  • fuzzy search รองรับการพิมพ์ผิด
  • relevance scoring จัดผลลัพธ์ตามความเกี่ยวข้อง
  • กรองหลายเงื่อนไขและทำ facets
  • ใช้ analyzer แยกและ normalize ข้อความ

ตัวอย่าง:

db.products.aggregate([
  {
    $search: {
      index: "product-search",
      text: {
        query: "รองเท้าวิ่ง",
        path: ["name", "description"]
      }
    }
  }
])

สรุปง่าย ๆ:

ประเภทเหมาะกับ
MongoDB Indexค้นหาแบบตรงค่า, filter, sort และ unique
Atlas Search Indexค้นหาข้อความ, autocomplete, fuzzy และจัดอันดับความเกี่ยวข้อง

Linked from

Nothing links here yet.

← all notes