การกำหนด schema

MongoDB เบื้องต้นใน Python

Filip Schouwenaars

Machine Learning Researcher

จาก schema แบบยืดหยุ่นสู่การตรวจสอบ

  • MongoDB ให้จัดเก็บข้อมูลโดยไม่ต้องมี schema แบบตายตัว
  • เหมาะสำหรับการสร้างต้นแบบอย่างรวดเร็วและปรับเปลี่ยน data model
mov.insert_one({
    "title": "knives out",
    "genre": ["comedy", "crime", "drama"],
    "year": 2019, # oops
    "rating": 7.9,
})

mov.find_one({ "title": "knives out", "release_year": 2019 })
  • เมื่อ schema ชัดเจนแล้ว ควรกำหนด validation ด้วย
MongoDB เบื้องต้นใน Python

กำหนด schema ด้วย pydantic

  • ไลบรารีสำหรับตรวจสอบข้อมูล
  • กำหนดฟิลด์ที่ต้องการและชนิดข้อมูล
  • เป็น blueprint สำหรับทุก document
from pydantic import BaseModel
from typing import Optional

class Movie(BaseModel):
    title: str
    genre: list[str]
    release_year: int
    rating: float
    won_oscar: Optional[bool] = None
MongoDB เบื้องต้นใน Python

การแทรกข้อมูลด้วย typed data model

# Before
new_movie = {
  "title": "knives out",
  "genre": ["comedy", "crime", "drama"],
  "year": 2019, # oops
  "rating": 7.9,
}
# No output
  • ไม่มีการตรวจสอบรูปแบบข้อมูล
# Now
new_movie = Movie(
  title = "knives out",
  genre = ["comedy", "crime", "drama"],
  year = 2019, # oops
  rating = 7.9,
)
pydantic.error_wrappers.ValidationError:
1 validation error for Movie
release_year: field required
  • ตรวจจับการพิมพ์ผิดและฟิลด์ที่ขาดหายไปก่อนที่จะบันทึกลง collection!
MongoDB เบื้องต้นใน Python

แก้ไขข้อผิดพลาด

from pydantic import BaseModel
from typing import Optional

class Movie(BaseModel):
    title: str
    genre: list[str]
    release_year: int
    rating: float
    won_oscar: Optional[bool] = None 
# Correct set of fields and field values
new_movie = Movie(
  title = "knives out",
  genre = ["comedy", "crime", "drama"],
  release_year = 2019,
  rating = 7.9,
)

mov.insert_one(dict(new_movie))
InsertOneResult(...)
MongoDB เบื้องต้นใน Python

การตรวจสอบ schema ในตัวของ MongoDB

client.film.create_collection(
  "movies_v2",
  validator={
    "$jsonSchema": {
      "required": ["title", "genre", "release_year", "rating"],
      "properties": {
        "title": { "bsonType": "string" },
        "genre": { 
          "bsonType": "array",
          "items": { "bsonType": "string" }
        },
        "release_year": { "bsonType": "int" },
        "rating": { "bsonType": "double" },
        "won_oscar": { "bsonType": "bool" }
      }
    }
  }
)
MongoDB เบื้องต้นใน Python

ทดสอบการตรวจสอบ schema ในตัวของ MongoDB

client.film.movies_v2.insert_one({
  "title": "knives out",
  "genre": ["comedy", "crime", "drama"],
  "year": 2019, # oops
  "rating": 7.9,
})
pymongo.errors.WriteError: Document failed validation, [...]
'missingProperties': ['release_year'], 'errmsg': 'Document failed validation'}
  • ตรวจสอบ schema ในระดับฐานข้อมูล
  • ครอบคลุมทุกแอปพลิเคชันที่เข้าถึง MongoDB
MongoDB เบื้องต้นใน Python

สรุป

  • การตรวจสอบฝั่งแอปพลิเคชัน: pydantic.BaseModel
  • การตรวจสอบฝั่งฐานข้อมูล: schema validation ในตัวของ MongoDB
  • ป้องกันความผิดพลาด
  • บังคับใช้โครงสร้างข้อมูล
MongoDB เบื้องต้นใน Python

มาฝึกกันเถอะ!

MongoDB เบื้องต้นใน Python

Preparing Video For Download...