الـ Indexes من جُوّه: B-tree و GIN و BRIN

جارٍ التحميل…

01 / ملخص الدرس

الـ Indexes من جُوّه: B-tree و GIN و BRIN

إيه الـ index وليه الـ Seq Scan بطيء، و EXPLAIN ANALYZE لأول مرة. الـ B-tree: = و < و ORDER BY، والـ composite index وقاعدة الـ leftmost prefix. الـ GIN: للـ arrays والـ jsonb والبحث جُوّه الكلام بـ pg_trgm. الـ BRIN: index بالكيلوبايت لجداول الوقت الضخمة. وتمن كل index: مساحة وبطء في الكتابة.

02 / شرح الدرس مكتوبًا

نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.

أهلًا بيك. seed dot sql بيعمل جدول orders فيه مِيتين ألف صف. لو سألت على orders مستخدم واحد، من غير index، Postgres لازم يقرا المِيتين ألف صف كلهم ويشوف كل واحد. ده اسمه Seq Scan. الـ index زي فهرس الكتاب: قايمة مترتبة بتقولك القيمة دي في أنهي صفحة. و EXPLAIN ANALYZE بيشغّل الـ query ويقولك عمل إيه بالزبط، وقفلنا الـ timing علشان الناتج يبقى تابت. مرة من غير index، وبعدين نعمل B-tree على user_id، ومرة تانية. نشغّل.

queries.sql
-- من غير index: Postgres لازم يقرا الجدول كله
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders WHERE user_id = 42;

CREATE INDEX orders_user_id ON orders (user_id);

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders WHERE user_id = 42;

-- index على أكتر من عمود: الترتيب مهم
CREATE INDEX orders_user_created ON orders (user_id, created_at DESC);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, created_at FROM orders WHERE user_id = 42 ORDER BY created_at DESC LIMIT 3;

-- نفس الـ index ما ينفعش لو السؤال من غير user_id
EXPLAIN (COSTS OFF) SELECT * FROM orders WHERE created_at > '2026-05-01' LIMIT 3;

المخرجات

$ psql -q -f seed.sql -f queries.sql
                 QUERY PLAN                  
---------------------------------------------
 Seq Scan on orders (actual rows=40 loops=1)
   Filter: (user_id = 42)
   Rows Removed by Filter: 199960
(3 rows)

                             QUERY PLAN                             
--------------------------------------------------------------------
 Bitmap Heap Scan on orders (actual rows=40 loops=1)
   Recheck Cond: (user_id = 42)
   Heap Blocks: exact=40
   ->  Bitmap Index Scan on orders_user_id (actual rows=40 loops=1)
         Index Cond: (user_id = 42)
(5 rows)

                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Limit (actual rows=3 loops=1)
   ->  Index Scan using orders_user_created on orders (actual rows=3 loops=1)
         Index Cond: (user_id = 42)
(3 rows)

                                    QUERY PLAN                                     
-----------------------------------------------------------------------------------
 Limit
   ->  Seq Scan on orders
         Filter: (created_at > '2026-05-01 00:00:00+00'::timestamp with time zon
…

من غير index: Seq Scan، و Rows Removed by Filter: مِيّة تسعة وتسعين ألف وتسعمية وستين تقريبًا، يعني قرا كل حاجة علشان يلاقي أربعين. بعد الـ index: Bitmap Index Scan، راح على الأربعين على طول. والـ composite على user_id و created_at: Index Scan، ومفيش Sort، و LIMIT وقف بعد تلاتة، لأن الـ index أصلًا مترتب بالوقت جُوّه كل مستخدم. بس لما سألنا بالـ created_at لوحده: Seq Scan تاني، لأن الـ index مترتب بـ user_id الأول. الـ B-tree ممتاز للمساواة والمدى والترتيب. بس فيه أسئلة ما يعرفهاش. إنك تدوّر على كلمة في نص الاسم بـ ILIKE و two percent signs: الـ B-tree بيعرف يدوّر من أول الكلمة بس. و array فيها tag معين. للحاجات دي فيه GIN: index بيفك كل قيمة لأجزاء. pg_trgm بيقسّم الكلام لتلات حروف تلات حروف، فيعرف يدوّر جُوّه أي كلمة. و GIN على الـ tags.

نشغّل.

queries.sql
-- GIN: index لحاجات جُوّاها حاجات (arrays، jsonb، كلام)
CREATE EXTENSION IF NOT EXISTS pg_trgm;
DROP TABLE IF EXISTS customers;
CREATE TABLE customers (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text, tags text[]);
INSERT INTO customers (name, tags)
SELECT 'customer_' || i || CASE WHEN i % 1000 = 0 THEN '_mona' ELSE '' END,
       CASE WHEN i % 7 = 0 THEN ARRAY['vip'] ELSE ARRAY['regular'] END
FROM generate_series(1, 100000) AS i;

CREATE INDEX customers_name_btree ON customers (name);
CREATE INDEX customers_name_trgm ON customers USING gin (name gin_trgm_ops);
CREATE INDEX customers_tags ON customers USING gin (tags);
ANALYZE customers;

-- B-tree ما بيساعدش في '%…%'، الـ trigram GIN بيساعد
EXPLAIN (COSTS OFF) SELECT count(*) FROM customers WHERE name ILIKE '%mona%';
SELECT count(*) FROM customers WHERE name ILIKE '%mona%';

EXPLAIN (COSTS OFF) SELECT count(*) FROM customers WHERE tags @> ARRAY['vip'];

المخرجات

$ psql -q -f seed.sql -f queries.sql
                      QUERY PLAN                      
------------------------------------------------------
 Aggregate
   ->  Bitmap Heap Scan on customers
         Recheck Cond: (name ~~* '%mona%'::text)
         ->  Bitmap Index Scan on customers_name_trgm
               Index Cond: (name ~~* '%mona%'::text)
(5 rows)

 count 
-------
   100
(1 row)

                     QUERY PLAN                      
-----------------------------------------------------
 Aggregate
   ->  Bitmap Heap Scan on customers
         Recheck Cond: (tags @> '{vip}'::text[])
         ->  Bitmap Index Scan on customers_tags
               Index Cond: (tags @> '{vip}'::text[])
(5 rows)

ILIKE percent mona percent: Bitmap Index Scan على الـ trigram index، مش الـ B-tree، ولقى مِيّة. و tags الـ contains operator vip: الـ GIN بتاع الـ tags. من غير pg_trgm، أي search box في الموقع بـ LIKE كان هيعمل Seq Scan على الجدول كله في كل حرف المستخدم بيكتبه. BRIN. جدول بيكبر بالوقت: orders و logs و events. الصفوف بتتكتب بالترتيب، فالـ created_at مترتب طبيعي على الـ disk. الـ BRIN بيخزن أقل وأكبر قيمة لكل مجموعة صفحات بس، فحجمه صغير جدًّا. هنعمل B-tree و BRIN على نفس العمود ونقارن الحجم، وبعدين نسأل على يوم واحد بالـ BRIN. نشغّل.

queries.sql
-- BRIN: لجداول ضخمة البيانات فيها مترتبة طبيعي (زي الوقت)
CREATE INDEX orders_created_btree ON orders (created_at);
CREATE INDEX orders_created_brin ON orders USING brin (created_at);

SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes WHERE relname = 'orders' ORDER BY pg_relation_size(indexrelid) DESC;

DROP INDEX orders_created_btree;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM orders WHERE created_at BETWEEN '2026-03-01' AND '2026-03-02';

المخرجات

$ psql -q -f seed.sql -f queries.sql
        index         |  size   
----------------------+---------
 orders_pkey          | 4408 kB
 orders_created_btree | 4408 kB
 orders_created_brin  | 24 kB
(3 rows)

                                                                              QUERY PLAN                                                                               
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate (actual rows=1 loops=1)
   ->  Bitmap Heap Scan on orders (actual rows=1441 loops=1)
         Recheck Cond: ((created_at >= '2026-03-01 00:00:00+00'::timestamp with time zone) AND (created_at <= '2026-03-02 00:00:00+00'::timestamp with time zone))
         Rows Removed by Index Recheck: 13919
         Heap Blocks: lossy=128
         ->  Bitmap Index Scan on orders_created_brin (actual rows=1280 loops=1)
               Index Cond: ((created_at >= '2026-03-01 00:00:00+00'::timestamp with time zone) AND (created_at <= '2026-03-02 00:00:00+00'::timestamp with time zone))
(7 rows)

الـ B-tree على created_at حوالي أربعة ميجا ونص، والـ BRIN أربعة وعشرين كيلو! وسؤال اليوم الواحد: Bitmap Index Scan على الـ BRIN، والـ Rows Removed by Index Recheck بيقول إنه قرا شوية صفوف زيادة وفلترها، وده التمن. BRIN ممتاز للجداول الضخمة المترتبة طبيعي، ووحش لو البيانات متلخبطة. وخد بالك من التمن. كل index بيتعدّل مع كل INSERT و UPDATE. خمس indexes على جدول يعني كل كتابة بتكتب ست مرات. والعمل على الإنتاج: CREATE INDEX العادي بيقفل الكتابة على الجدول لحد ما يخلص، فالموقع يقف. استخدم CREATE INDEX CONCURRENTLY، أبطأ بس من غير قفل. وده هنرجعله في درس الـ migrations. التحدي: أقل indexes لأسرع queries. تلات queries بتتشغّل آلاف المرات: آخر الـ pending. orders مستخدم بحالة معينة. ومجموع يوم واحد. اعمل أقل indexes تخلي التلاتة من غير Seq Scan ولا Sort، وفكّر في الترتيب جُوّه كل composite index. الشروط في الكومنت.

تمرين

اعمل indexes: (status, created_at DESC) و (user_id, status) و BRIN على created_at، و ANALYZE، واتأكد إن الـ EXPLAINs التلاتة من غير Seq Scan ولا Sort.

الحل. status و created_at تنازلي: بيجيب الـ pending مترتبة. user_id و status: user_id الأول لأنه أكتر عمود بيفرّق، يعني فيه قيم كتير مختلفة. و BRIN للوقت. و ANALYZE علشان Postgres يعرف الإحصائيات الجديدة. نشغّل.

queries.sql
CREATE INDEX orders_status_created ON orders (status, created_at DESC);
CREATE INDEX orders_user_status ON orders (user_id, status);
CREATE INDEX orders_created_brin ON orders USING brin (created_at);
ANALYZE orders;

EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE status = 'pending' ORDER BY created_at DESC LIMIT 20;
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE user_id = 7 AND status = 'paid';
EXPLAIN (COSTS OFF) SELECT sum(total_cents) FROM orders WHERE created_at >= '2026-04-01' AND created_at < '2026-04-02';


SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes WHERE relname = 'orders' ORDER BY pg_relation_size(indexrelid) DESC;

المخرجات

$ psql -q -f seed.sql -f queries.sql
                       QUERY PLAN                       
--------------------------------------------------------
 Limit
   ->  Index Scan using orders_status_created on orders
         Index Cond: (status = 'pending'::text)
(3 rows)

                           QUERY PLAN                            
-----------------------------------------------------------------
 Bitmap Heap Scan on orders
   Recheck Cond: ((user_id = 7) AND (status = 'paid'::text))
   ->  Bitmap Index Scan on orders_user_status
         Index Cond: ((user_id = 7) AND (status = 'paid'::text))
(4 rows)

                                                                              QUERY PLAN                                                                              
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate
   ->  Bitmap Heap Scan on orders
         Recheck Cond: ((created_at >= '2026-04-01 00:00:00+00'::timestamp with time zone) AND (created_at < '2026-04-02 00:00:00+00'::timestamp with time zone))
         ->  Bitmap Index Scan on orders_cre
…

التلاتة بـ indexes، والأولى من غير Sort، والـ BRIN أصغرهم بكتير. الدرس الجاي: الـ partial indexes والـ covering indexes، يعني indexes أصغر وأشطر.

03 / دروس المسار (122)
  1. 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
  2. 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
  3. 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
  4. 04القيم والمتغيرات والأنواع: const و let و typeof
  5. 05القرارات والتكرار: if و === والـ truthy والـ loops
  6. 06الـ functions: parameters و return والـ arrow functions والـ scope
  7. 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
  8. 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
  9. 09الـ callbacks والـ closures وأول لمسة async: setTimeout
  10. 10الـ classes والـ errors: throw و try/catch و stack trace
  11. 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
  12. 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
  13. 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
  14. 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
  15. 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
  16. 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
  17. 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
  18. 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
  19. 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
  20. 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
  21. 21الـ Node test runner والـ debugging: tests من غير مكتبات
  22. 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
  23. 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
  24. 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
  25. 25الـ Middleware ودورة حياة الـ request جُوّه Express
  26. 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
  27. 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
  28. 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
  29. 29رفع الملفات وحدود الحجم: multer من غير ثغرات
  30. 30الـ Realtime: Server-Sent Events و WebSockets
  31. 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
  32. 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
  33. 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
  34. 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
  35. 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
  36. 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
  37. 37الـ Indexes من جُوّه: B-tree و GIN و BRINانت هنا
  38. 38Partial و Covering indexes: indexes أصغر وأسرع
  39. 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
  40. 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
  41. 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
  42. 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
  43. 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
  44. 44الـ Locks والـ Deadlocks: مين مستني مين
  45. 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
  46. 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
  47. 47Migrations من غير downtime: expand و backfill و contract
  48. 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
  49. 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
  50. 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
  51. 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
  52. 52Cache-aside والـ TTL: Redis قدام الـ database
  53. 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
  54. 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
  55. 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
  56. 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
  57. 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
  58. 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
  59. 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
  60. 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
  61. 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
  62. 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
  63. 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
  64. 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
  65. 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
  66. 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
  67. 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
  68. 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
  69. 69الـ MFA والـ recovery: التاني factor اللي بجد
  70. 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
  71. 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
  72. 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
  73. 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
  74. 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
  75. 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
  76. 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
  77. 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
  78. 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
  79. 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
  80. 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
  81. 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
  82. 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
  83. 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
  84. 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
  85. 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
  86. 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
  87. 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
  88. 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
  89. 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
  90. 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
  91. 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
  92. 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
  93. 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
  94. 94Docker Volumes: الـ data بتتحفَظ فين
  95. 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
  96. 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
  97. 97Reverse Proxy و TLS: اللي واقف قدام الـ app
  98. 98Multi-arch Images والـ Native Modules: اشتغلت عندي
  99. 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
  100. 100Kubernetes من الأول: Pods و Deployments و Services و Probes
  101. 101Modular Monolith و DDD: حدود واضحة من غير network
  102. 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
  103. 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
  104. 104CQRS و Event Sourcing: الـ events هي الحقيقة
  105. 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
  106. 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
  107. 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
  108. 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
  109. 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
  110. 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
  111. 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
  112. 112ORM ولا SQL: query builders و repositories و migrations و transactions
  113. 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
  114. 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
  115. 115Contract Testing و Property-Based Testing بـ fast-check
  116. 116الـ Payments: idempotency و webhooks و refunds و reconciliation
  117. 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
  118. 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
  119. 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
  120. 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
  121. 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
  122. 122Incident Runbooks: من الـ alert للـ postmortem