> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-8c05c8a2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# الدالة explain()

> استعرض خطط تنفيذ DataStore باستخدام الدالة explain()

تعرض الدالة `explain()` خطة تنفيذ لاستعلام DataStore، مما يساعدك على فهم العمليات التي ستُنفَّذ وعبارات SQL التي سيتم توليدها.

<div id="basic">
  ## الاستخدام الأساسي
</div>

```python theme={null}
from pathlib import Path
Path("sales.csv").write_text("""\
region,product,category,amount,quantity,price,date,order_id
East,Widget,Electronics,5200,10,120,2024-01-15,1001
West,Gadget,Electronics,800,5,160,2024-02-20,1002
East,Gizmo,Home,6500,3,100,2024-03-10,1003
North,Widget,Electronics,4500,6,150,2024-06-18,1004
West,Gadget,Electronics,2000,8,250,2024-09-14,1005
""")

from chdb import datastore as pd

ds = pd.read_csv("sales.csv")

query = (ds
    .filter(ds['amount'] > 1000)
    .groupby('region')
    .agg({'amount': ['sum', 'mean']})
    .sort('sum', ascending=False)
)

# View execution plan
query.explain()
```

<div id="syntax">
  ## الصيغة
</div>

```python theme={null}
explain(verbose=False) -> None
```

**المعلمات:**

| المعلمة   | النوع | الافتراضي | الوصف                   |
| --------- | ----- | --------- | ----------------------- |
| `verbose` | bool  | `False`   | عرض بيانات وصفية إضافية |

<div id="output-format">
  ## صيغة الإخراج
</div>

<div id="standard">
  ### الإخراج القياسي
</div>

```text theme={null}
================================================================================
Execution Plan (in execution order)
================================================================================

 [1] 📊 Data Source: file('sales.csv', 'csv')

Operations:
────────────────────────────────────────────────────────────────────────────────
    ️  Segment 1 [chDB] (from source): Operations 2-5
    ️  Note: SQL operations after Pandas ops use Python() table function

 [2] 🚀 [chDB] WHERE: "amount" > 1000
 [3] 🚀 [chDB] GROUP BY: region
 [4] 🚀 [chDB] AGGREGATE: sum(amount), avg(amount)
 [5] 🚀 [chDB] ORDER BY: sum DESC

────────────────────────────────────────────────────────────────────────────────
Final State: 📊 Pending (lazy, not yet executed)
             └─> Will execute when print(), .to_df(), .execute() is called

────────────────────────────────────────────────────────────────────────────────
Generated SQL Query:
────────────────────────────────────────────────────────────────────────────────

SELECT region, SUM(amount) AS sum, AVG(amount) AS mean
FROM file('sales.csv', 'csv')
WHERE "amount" > 1000
GROUP BY region
ORDER BY sum DESC

================================================================================
```

<div id="icons">
  ### دليل الأيقونات
</div>

| الأيقونة | المعنى            |
| -------- | ----------------- |
| 📊       | مصدر بيانات       |
| 🚀       | عملية chDB ‏(SQL) |
| 🐼       | عملية pandas      |

<div id="verbose">
  ### الإخراج التفصيلي
</div>

```python theme={null}
query.explain(verbose=True)
```

يعرض الوضع التفصيلي تفاصيل إضافية لكل عملية، بما في ذلك استعلام SQL الكامل مع آليات داخلية لتتبّع ترتيب الصفوف.

***

<div id="phases">
  ## مراحل التنفيذ الثلاث
</div>

تعرض مخرجات EXPLAIN العمليات عبر ثلاث مراحل:

<div id="phase-1">
  ### المرحلة 1: بناء استعلام SQL (التنفيذ المؤجل)
</div>

العمليات التي تُترجم إلى SQL:

```text theme={null}
  1. Source: file('sales.csv', 'CSVWithNames')
  2. Filter: amount > 1000      
  3. GroupBy: region
  4. Aggregate: sum(amount)
```

<div id="phase-2">
  ### المرحلة 2: نقطة التنفيذ
</div>

عند تفعيل المُشغِّل:

```text theme={null}
  5. Execute SQL -> DataFrame
     Trigger: to_df() called
```

<div id="phase-3">
  ### المرحلة 3: العمليات على DataFrame
</div>

العمليات بعد التنفيذ:

```text theme={null}
  6. [pandas] pivot_table(...)
  7. [pandas] apply(custom_func)
```

***

<div id="understanding">
  ## فهم خطة التنفيذ
</div>

<div id="source">
  ### معلومات المصدر
</div>

```text theme={null}
Source: file('sales.csv', 'CSVWithNames')
```

* `file()` - دالة الجدول file() في ClickHouse
* `'CSVWithNames'` - تنسيق ملف يتضمن صف عناوين

أنواع المصادر الأخرى:

```text theme={null}
Source: s3('bucket/data.parquet', ...)
Source: mysql('host', 'db', 'table', ...)
Source: __dataframe__  (pandas DataFrame input)
```

<div id="filter">
  ### عمليات التصفية
</div>

```text theme={null}
Filter: amount > 1000 AND status = 'active'
```

يوضح بند WHERE الذي سيُطبَّق.

<div id="groupby">
  ### GroupBy والتجميع
</div>

```text theme={null}
GroupBy: region, category
Aggregate: sum(amount), avg(amount), count(id)
```

يعرض الأعمدة المستخدمة في GROUP BY ودوال التجميع.

<div id="sort">
  ### عمليات الترتيب
</div>

```text theme={null}
Sort: sum DESC, region ASC
```

يعرض عبارة ORDER BY.

<div id="limit">
  ### عمليات LIMIT
</div>

```text theme={null}
Limit: 10
Offset: 100
```

يعرض LIMIT وOFFSET.

***

<div id="engine">
  ## معلومات المحرّك
</div>

عند استخدام الوضع المفصّل، يمكنك رؤية المحرّك الذي سيُستخدم:

```text theme={null}
Filter: amount > 1000
  - Engine: chdb
  - Pushdown: Yes

Apply: custom_function
  - Engine: pandas
  - Pushdown: No
```

<div id="pushdown">
  ### Pushdown
</div>

* **نعم**: ستُنفَّذ العملية في مصدر البيانات (SQL)
* **لا**: تتطلب العملية تنفيذها باستخدام pandas

***

<div id="examples">
  ## أمثلة
</div>

<div id="example-simple">
  ### استعلام بسيط
</div>

```python theme={null}
from pathlib import Path
Path("data.csv").write_text("""\
name,age,city,salary,department
Alice,25,NYC,55000,Engineering
Bob,30,LA,65000,Product
Charlie,35,NYC,80000,Engineering
Diana,28,SF,70000,Design
Eve,42,NYC,95000,Product
""")

ds = pd.read_csv("data.csv")
ds.filter(ds['age'] > 25).explain()
```

```text theme={null}
================================================================================
Execution Plan (in execution order)
================================================================================

 [1] 📊 Data Source: file('data.csv', 'csv')

Operations:
────────────────────────────────────────────────────────────────────────────────
    ️  Segment 1 [chDB] (from source): Operations 2-2

 [2] 🚀 [chDB] WHERE: "age" > 25

────────────────────────────────────────────────────────────────────────────────
Generated SQL Query:
────────────────────────────────────────────────────────────────────────────────

SELECT * FROM file('data.csv', 'csv') WHERE "age" > 25

================================================================================
```

<div id="example-complex">
  ### التجميع المعقّد
</div>

```python theme={null}
query = (ds
    .filter(ds['date'] >= '2024-01-01')
    .filter(ds['amount'] > 100)
    .select('region', 'category', 'amount')
    .groupby('region', 'category')
    .agg({
        'amount': ['sum', 'mean', 'count']
    })
    .sort('sum', ascending=False)
    .limit(20)
)
query.explain()
```

```text theme={null}
================================================================================
Execution Plan (in execution order)
================================================================================

 [1] 📊 Data Source: file('sales.csv', 'csv')

Operations:
────────────────────────────────────────────────────────────────────────────────
    ️  Segment 1 [chDB] (from source): Operations 2-8

 [2] 🚀 [chDB] WHERE: "date" >= '2024-01-01'
 [3] 🚀 [chDB] WHERE: "amount" > 100
 [4] 🚀 [chDB] SELECT: region, category, amount
 [5] 🚀 [chDB] GROUP BY: region, category
 [6] 🚀 [chDB] AGGREGATE: sum(amount), avg(amount), count(amount)
 [7] 🚀 [chDB] ORDER BY: sum DESC
 [8] 🚀 [chDB] LIMIT: 20

────────────────────────────────────────────────────────────────────────────────
Generated SQL Query:
────────────────────────────────────────────────────────────────────────────────

SELECT region, category, 
       SUM(amount) AS sum, 
       AVG(amount) AS mean, 
       COUNT(amount) AS count
FROM file('sales.csv', 'csv')
WHERE "date" >= '2024-01-01' AND "amount" > 100
GROUP BY region, category
ORDER BY sum DESC
LIMIT 20

================================================================================
```

<div id="example-mixed">
  ### SQL وpandas معًا
</div>

عندما يتعذر تنفيذ جميع العمليات بالكامل داخل SQL، تُظهر الخطة عدة مقاطع:

```python theme={null}
query = (ds
    .filter(ds['age'] > 25)           # SQL
    .groupby('city')                   # SQL
    .agg({'salary': 'mean'})           # SQL
    .apply(lambda x: x * 1.1)          # pandas (triggers segment split)
    .filter(ds['mean'] > 50000)        # SQL (new segment)
)
query.explain()
```

```text theme={null}
================================================================================
Execution Plan (in execution order)
================================================================================

 [1] 📊 Data Source: file('data.csv', 'csv')

Operations:
────────────────────────────────────────────────────────────────────────────────
    ️  Segment 1 [chDB] (from source): Operations 2-4
    ️  Segment 2 [Pandas] (on DataFrame): Operation 5
    ️  Segment 3 [chDB] (on DataFrame): Operation 6
    ️  Note: SQL operations after Pandas ops use Python() table function

 [2] 🚀 [chDB] WHERE: "age" > 25
 [3] 🚀 [chDB] GROUP BY: city
 [4] 🚀 [chDB] AGGREGATE: avg(salary)
 [5] 🐼 [Pandas] APPLY: lambda
 [6] 🚀 [chDB] WHERE: "mean" > 50000

================================================================================
```

***

<div id="debugging">
  ## استكشاف الأخطاء وإصلاحها باستخدام explain()
</div>

<div id="debug-filter">
  ### تحقّق من منطق التصفية
</div>

```python theme={null}
# Verify your filter is correct
query = ds.filter((ds['age'] > 25) & (ds['city'] == 'NYC'))
query.explain()
# Output shows: Filter: age > 25 AND city = 'NYC'
```

<div id="debug-select">
  ### تحقّق من تحديد العمود
</div>

```python theme={null}
# Check column pruning
query = ds.select('name', 'age').filter(ds['age'] > 25)
query.explain()
# Output shows: SELECT name, age FROM ... WHERE age > 25
```

<div id="debug-agg">
  ### فهم التجميع
</div>

```python theme={null}
# Check aggregation functions
query = ds.groupby('dept').agg({'salary': ['sum', 'mean', 'std']})
query.explain()
# Output shows: SELECT dept, SUM(salary), AVG(salary), stddevPop(salary)
```

***

<div id="best-practices">
  ## أفضل الممارسات
</div>

<div id="best-practice-1">
  ### 1. تحقّق قبل تنفيذ الاستعلامات الكبيرة
</div>

```python theme={null}
# Always explain first for large data
query = ds.complex_pipeline()
query.explain()  # Check plan

# If plan looks correct
result = query.to_df()  # Execute
```

<div id="best-practice-2">
  ### 2. استخدم تفصيلي لاستكشاف الأخطاء وإصلاحها
</div>

```python theme={null}
# When something seems wrong
query.explain(verbose=True)
# Shows engine selection and pushdown info
```

<div id="best-practice-3">
  ### 3. قارن مع `to_sql()`
</div>

```python theme={null}
# explain() shows the plan
query.explain()

# to_sql() shows just the SQL
print(query.to_sql())

# Both useful for different purposes
```

<div id="best-practice-4">
  ### 4. التحقّق من حالة Pushdown
</div>

```python theme={null}
# Verbose mode shows if operations are pushed down
query.explain(verbose=True)

# If Pushdown: No, operation runs in pandas
# Consider restructuring query for better performance
```
