快速入門:執行你的第一個 DAX 查詢

在這個快速入門中,你會登入 Power BI,對語意模型執行 DAX 查詢,並將 Arrow 格式的回應反序列化成本地資料結構。

先決條件

  • 一個至少有一個語意模型的 Power BI 工作空間。
  • 在語意模型上建立讀取權限。
  • Microsoft Entra 應用程式註冊(或使用互動式認證進行測試)。
  • Python 3.10 或更新版本。

  • 安裝依賴項

    pip install msal pyarrow pandas
    

1 - 認證

取得具有 https://analysis.windows.net/powerbi/api/.default 權限的持有者令牌。

from msal import PublicClientApplication

client_id = "YOUR_APP_CLIENT_ID"
authority = "https://login.microsoftonline.com/YOUR_TENANT_ID"
scopes = ["https://analysis.windows.net/powerbi/api/.default"]

app = PublicClientApplication(client_id, authority=authority)
result = app.acquire_token_interactive(scopes=scopes)

access_token = result["access_token"]

2 - 執行 DAX 查詢

用簡單的 EVALUATE 語句向執行查詢箭頭端點發送 POST 請求。

import io
import pyarrow as pa
import requests

group_id = "YOUR_WORKSPACE_ID"
dataset_id = "YOUR_DATASET_ID"

url = (f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}"
       f"/datasets/{dataset_id}/executeDaxQueries")

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json",
}

body = {"query": "EVALUATE TOPN(5, 'DimProduct')"}

response = requests.post(url, headers=headers, json=body)
response.raise_for_status()

reader = pa.ipc.open_stream(io.BytesIO(response.content))
table = reader.read_all()
df = table.to_pandas()

print(df)

3 - 檢查結果

# Print the Arrow schema (column names and types)
print(table.schema)

# Show the first few rows as a pandas DataFrame
print(df.head())

# Access a specific column
print(table.column("ProductName").to_pylist()[:5])

清理資源

如果你只是為了測試而創建了Microsoft Entra應用程式註冊,請進入Azure入口網站並刪除它。 存取權憑證會自動過期,不需要手動撤銷。