0Pricing
Serverless Backend with AWS Lambda & API Gateway · درس

تصميم جداول DynamoDB

تعلّم أفضل الممارسات لتصميم مخططات جداول DynamoDB الفعّالة، مع التركيز على مفاتيح التقسيم ومفاتيح الترتيب لتحقيق أفضل أداء

تصميم جداول DynamoDB درس مجاني في Serverless Backend with AWS Lambda & API Gateway على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Serverless Backend with AWS Lambda & API Gateway، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Serverless Backend with AWS Lambda & API Gateway 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why DynamoDB Design Matters

Welcome to designing DynamoDB tables! Unlike traditional relational databases, DynamoDB is a NoSQL database that requires a different approach to schema design.

  • Its serverless nature and performance at scale depend heavily on how you design your tables and choose your keys.
  • A well-designed table ensures fast, consistent performance and cost efficiency.
  • A poor design can lead to slow queries, high costs, and operational headaches.

The Partition Key (PK)

Every item in a DynamoDB table is uniquely identified by its primary key. The first part of any primary key is the Partition Key (sometimes called a Hash Key).

  • DynamoDB uses the Partition Key's value as input to an internal hash function.
  • This function determines the physical partition (storage location) where your data is stored.
  • Good Partition Keys distribute data evenly across partitions, preventing 'hot spots' and ensuring scalability.

The Sort Key (SK)

The second part of a primary key, if you choose to have one, is the Sort Key (sometimes called a Range Key).

  • Items with the same Partition Key are grouped together and sorted by their Sort Key value.
  • This allows for efficient range queries (e.g., 'all orders from a user within a date range').
  • The combination of Partition Key and Sort Key must be unique for each item in the table.

Understanding Primary Keys

A table's primary key can be either a simple primary key (only a Partition Key) or a composite primary key (a Partition Key and a Sort Key).

  • Simple Primary Key: Ideal when each item needs a unique identifier, like a userId for a Users table.
  • Composite Primary Key: Best for one-to-many relationships or when you need to query items that share a common partition key but differ by a secondary identifier, like userId and orderId for an Orders table.

Simple PK in Action

Let's consider a Users table where each user has a unique userId. We can use userId as the simple Partition Key. Here's how an item might be added:

import boto3

# This client is conceptual for illustration.
# In a real app, it would connect to your DynamoDB table.
class MockDynamoDBTable:
    def __init__(self, name):
        self.name = name
        self.items = {}

    def put_item(self, Item):
        pk = Item['userId']
        if pk in self.items:
            print(f"Warning: Item with userId '{pk}' already exists. Overwriting.")
        self.items[pk] = Item
        print(f"Item added/updated in '{self.name}': {Item}")

# Simulate a DynamoDB table named 'Users'
table = MockDynamoDBTable('Users')

def add_user_item():
    table.put_item(
        Item={
            'userId': 'user123',
            'username': 'Alice',
            'email': 'alice@example.com'
        }
    )

if __name__ == "__main__":
    add_user_item()

Composite PK in Action

Now, imagine an Orders table where a user can have multiple orders. We'd use userId as the Partition Key and orderId as the Sort Key. This allows us to retrieve all orders for a specific user, sorted by orderId.

import boto3

# This client is conceptual for illustration.
# In a real app, it would connect to your DynamoDB table.
class MockDynamoDBTable:
    def __init__(self, name):
        self.name = name
        self.items = {}

    def put_item(self, Item):
        pk = Item['userId']
        sk = Item['orderId']
        if pk not in self.items:
            self.items[pk] = {}
        self.items[pk][sk] = Item
        print(f"Item added/updated in '{self.name}': {Item}")

# Simulate a DynamoDB table named 'Orders'
table = MockDynamoDBTable('Orders') # Assume PK: userId, SK: orderId

def add_order_item():
    table.put_item(
        Item={
            'userId': 'user123',
            'orderId': 'order456',
            'itemCount': 2,
            'totalAmount': 50.00,
            'orderDate': '2023-10-26'
        }
    )

if __name__ == "__main__":
    add_order_item()

Designing for Access Patterns

The most crucial aspect of DynamoDB design is understanding your access patterns. You should design your primary keys around how your application will query the data, not just how the data looks.

  • What queries will you make? (e.g., 'Get all products by category', 'Get a specific user's latest posts').
  • What data will be returned? (e.g., single item, list of items).
  • Your Partition Key should typically be the attribute you query on most frequently for specific items or groups of items.
  • Your Sort Key allows for flexible queries within that group (e.g., range queries, reverse order).

Key Selection Best Practices

Choosing the right keys is vital for performance:

  • High Cardinality: Keys should have many unique values to prevent 'hot spots' on a single partition.
  • Even Distribution: Values should be accessed roughly equally. Avoid keys where a few values are queried much more often than others.
  • Query Efficiency: Design keys so that most common queries can be satisfied using GetItem (PK only) or Query (PK + optional SK condition).
  • Avoid Scans: Operations that read every item in a table (Scan) are inefficient and costly. Your design should minimize the need for them.

Modeling One-to-Many Relationships

Composite Primary Keys are excellent for modeling one-to-many relationships, which are very common. For example, a user has many posts:

  • Partition Key: USER#<userId> (a common pattern to prefix keys for clarity).
  • Sort Key: POST#<postId>.
  • This design allows you to fetch all posts for a user by querying only on the Partition Key, and even specific posts by adding a Sort Key condition.

This approach keeps related data together, enabling efficient retrieval.

Design Challenge

You are designing a table to store user comments on various articles. Your primary access patterns are:

  1. Get all comments for a specific article.
  2. Get all comments made by a specific user.

Which primary key design would best support getting all comments for a specific article efficiently?

Key Design Recap

Great job! In this lesson, you learned the foundational principles of designing DynamoDB tables:

  • The importance of Partition Keys for data distribution.
  • The utility of Sort Keys for ordering and range queries.
  • How Primary Keys (simple or composite) uniquely identify items.
  • The critical role of access patterns in driving your design choices.
  • Best practices for selecting keys to ensure performance and cost efficiency.

Mastering these concepts is key to building scalable and performant serverless applications with DynamoDB!

الأسئلة الشائعة

هل درس «تصميم جداول DynamoDB» مجاني؟

نعم — نص درس «تصميم جداول DynamoDB» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Serverless Backend with AWS Lambda & API Gateway، انتقل إلى CoddyKit PRO. تتضمن دورة Serverless Backend with AWS Lambda & API Gateway 4 دروس في المجموع.

ماذا ستتعلم في «تصميم جداول DynamoDB»؟

تعلّم أفضل الممارسات لتصميم مخططات جداول DynamoDB الفعّالة، مع التركيز على مفاتيح التقسيم ومفاتيح الترتيب لتحقيق أفضل أداء تتمرن على Serverless Backend with AWS Lambda & API Gateway مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Serverless Backend with AWS Lambda & API Gateway؟

لا تُشترط خبرة سابقة. Serverless Backend with AWS Lambda & API Gateway على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «تصميم جداول DynamoDB»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Serverless Backend with AWS Lambda & API Gateway هذا؟

نعم. كل درس في Serverless Backend with AWS Lambda & API Gateway يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. مقدمة إلى DynamoDB
  2. تصميم جداول DynamoDB
  3. تكامل Lambda وDynamoDB
  4. الاستعلام باستخدام الفهارس الثانوية: GSIs وLSIs
← العودة إلى Serverless Backend with AWS Lambda & API Gateway