管理コマンドを実行するアプリを作成する
[アーティクル] 01/23/2025
3 人の共同作成者
フィードバック
この記事の内容
適用対象: ✅Microsoft Fabric ✅Azure Data Explorer
この記事では、次の方法について説明します。
前提 条件
Kusto クライアント ライブラリを使用するように開発環境 を設定します。
管理コマンドを実行して結果を処理する
任意の IDE またはテキスト エディターで、管理コマンドという名前のプロジェクトまたはファイルを作成 、好みの言語に適した規則を使用します。 次に、次のコードを追加します。
クラスターに接続するクライアント アプリを作成します。 <your_cluster_uri>
プレースホルダーをクラスター名に置き換えます。
手記
管理コマンドの場合は、CreateCslAdminProvider
クライアント ファクトリ メソッドを使用します。
using Kusto.Data;
using Kusto.Data.Net.Client;
namespace ManagementCommands {
class ManagementCommands {
static void Main(string[] args) {
var clusterUri = "<your_cluster_uri>";
var kcsb = new KustoConnectionStringBuilder(clusterUri)
.WithAadUserPromptAuthentication();
using (var kustoClient = KustoClientFactory.CreateCslAdminProvider(kcsb)) {
}
}
}
}
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder
def main():
cluster_uri = "<your_cluster_uri>"
kcsb = KustoConnectionStringBuilder.with_interactive_login(cluster_uri)
with KustoClient(kcsb) as kusto_client:
if __name__ == "__main__":
main()
import { Client as KustoClient, KustoConnectionStringBuilder } from "azure-kusto-data/";
import { InteractiveBrowserCredentialInBrowserOptions } from "@azure/identity";
async function main() {
const clusterUri = "<your_cluster_uri>";
const authOptions = {
clientId: "00001111-aaaa-2222-bbbb-3333cccc4444",
redirectUri: "http://localhost:5173",
} as InteractiveBrowserCredentialInBrowserOptions;
const kcsb = KustoConnectionStringBuilder.withUserPrompt(clusterUri, authOptions);
const kustoClient = new KustoClient(kcsb);
}
main();
手記
Node.js アプリの場合は、InteractiveBrowserCredentialInBrowserOptions
の代わりに InteractiveBrowserCredentialNodeOptions
を使用します。
import com.microsoft.azure.kusto.data.Client;
import com.microsoft.azure.kusto.data.ClientFactory;
import com.microsoft.azure.kusto.data.KustoOperationResult;
import com.microsoft.azure.kusto.data.KustoResultSetTable;
import com.microsoft.azure.kusto.data.KustoResultColumn;
import com.microsoft.azure.kusto.data.auth.ConnectionStringBuilder;
public class ManagementCommands {
public static void main(String[] args) throws Exception {
try {
String clusterUri = "<your_cluster_uri>";
ConnectionStringBuilder kcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri);
try (Client kustoClient = ClientFactory.createClient(kcsb)) {
}
}
}
}
実行されているコマンドとその結果テーブルを出力する関数を定義します。 この関数は、結果テーブル内の列名をアンパックし、各名前と値のペアを新しい行に出力します。
static void PrintResultsAsValueList(string command, IDataReader response) {
while (response.Read()) {
Console.WriteLine("\n{0}\n", new String('-', 20));
Console.WriteLine("Command: {0}", command);
Console.WriteLine("Result:");
for (int i = 0; i < response.FieldCount; i++) {
Console.WriteLine("\t{0} - {1}", response.GetName(i), response.IsDBNull(i) ? "None" : response.GetString(i));
}
}
}
def print_result_as_value_list(command, response):
# create a list of columns
cols = (col.column_name for col in response.primary_results[0].columns)
print("\n" + "-" * 20 + "\n")
print("Command: " + command)
# print the values for each row
for row in response.primary_results[0]:
print("Result:")
for col in cols:
print("\t", col, "-", row[col])
function printResultsAsValueList(command: string, response: KustoResponseDataSet) {
// create a list of columns
const cols = response.primaryResults[0].columns;
console.log("\n" + "-".repeat(20) + "\n")
console.log("Command: " + command)
// print the values for each row
for (const row of response.primaryResults[0].rows()) {
console.log("Result:")
for (col of cols)
console.log("\t", col.name, "-", row.getValueAt(col.ordinal) ? row.getValueAt(col.ordinal).toString() : "None")
}
}
public static void printResultsAsValueList(String command, KustoResultSetTable results) {
while (results.next()) {
System.out.println("\n" + "-".repeat(20) + "\n");
System.out.println("Command: " + command);
System.out.println("Result:");
KustoResultColumn[] columns = results.getColumns();
for (int i = 0; i < columns.length; i++) {
System.out.println("\t" + columns[i].getColumnName() + " - " + (results.getObject(i) == null ? "None" : results.getString(i)));
}
}
}
実行するコマンドを定義します。 コマンド は と呼ばれるテーブル MyStormEvents を作成し、列名と型のリストとしてテーブルスキーマを定義します。 <your_database>
プレースホルダーをデータベース名に置き換えます。
string database = "<your_database>";
string table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
string command = @$".create table {table}
(StartTime:datetime,
EndTime:datetime,
State:string,
DamageProperty:int,
DamageCrops:int,
Source:string,
StormSummary:dynamic)";
database = "<your_database>"
table = "MyStormEvents"
# Create a table named MyStormEvents
# The brackets contain a list of column Name:Type pairs that defines the table schema
command = ".create table " + table + " " \
"(StartTime:datetime," \
" EndTime:datetime," \
" State:string," \
" DamageProperty:int," \
" DamageCrops:int," \
" Source:string," \
" StormSummary:dynamic)"
const database = "<your_database>";
const table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
const command = `.create table ${table}
(StartTime:datetime,
EndTime:datetime,
State:string,
DamageProperty:int,
Source:string,
StormSummary:dynamic)`;
String database = "<your_database>";
String table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
String command = ".create table " + table + " " +
"(StartTime:datetime," +
" EndTime:datetime," +
" State:string," +
" DamageProperty:int," +
" DamageCrops:int," +
" Source:string," +
" StormSummary:dynamic)";
コマンドを実行し、前に定義した関数を使用して結果を出力します。
手記
ExecuteControlCommand
メソッドを使用してコマンドを実行します。
using (var response = kustoClient.ExecuteControlCommand(database, command, null)) {
PrintResultsAsValueList(command, response);
}
手記
execute_mgmt
メソッドを使用してコマンドを実行します。
response = kusto_client.execute_mgmt(database, command)
print_result_as_value_list(command, response)
手記
executeMgmt
メソッドを使用してコマンドを実行します。
const response = await kustoClient.executeMgmt(database, command);
printResultsAsValueList(command, response)
KustoOperationResult response = kusto_client.execute(database, command);
printResultsAsValueList(command, response.getPrimaryResults());
完全なコードは次のようになります。
using Kusto.Data;
using Kusto.Data.Net.Client;
namespace ManagementCommands {
class ManagementCommands {
static void Main(string[] args) {
string clusterUri = "https://<your_cluster_uri>";
var kcsb = new KustoConnectionStringBuilder(clusterUri)
.WithAadUserPromptAuthentication();
using (var kustoClient = KustoClientFactory.CreateCslAdminProvider(kcsb)) {
string database = "<your_database>";
string table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
string command = @$".create table {table}
(StartTime:datetime,
EndTime:datetime,
State:string,
DamageProperty:int,
DamageCrops:int,
Source:string,
StormSummary:dynamic)";
using (var response = kustoClient.ExecuteControlCommand(database, command, null)) {
PrintResultsAsValueList(command, response);
}
}
}
static void PrintResultsAsValueList(string command, IDataReader response) {
while (response.Read()) {
Console.WriteLine("\n{0}\n", new String('-', 20));
Console.WriteLine("Command: {0}", command);
Console.WriteLine("Result:");
for (int i = 0; i < response.FieldCount; i++) {
Console.WriteLine("\t{0} - {1}", response.GetName(i), response.IsDBNull(i) ? "None" : response.GetString(i));
}
}
}
}
}
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder
def main():
cluster_uri = "https://<your_cluster_uri>"
kcsb = KustoConnectionStringBuilder.with_interactive_login(cluster_uri)
with KustoClient(kcsb) as kusto_client:
database = "<your_database>"
table = "MyStormEvents"
# Create a table named MyStormEvents
# The brackets contain a list of column Name:Type pairs that defines the table schema
command = ".create table " + table + " " \
"(StartTime:datetime," \
" EndTime:datetime," \
" State:string," \
" DamageProperty:int," \
" DamageCrops:int," \
" Source:string," \
" StormSummary:dynamic)"
response = kusto_client.execute_mgmt(database, command)
print_result_as_value_list(command, response)
def print_result_as_value_list(command, response):
# create a list of columns
cols = (col.column_name for col in response.primary_results[0].columns)
print("\n" + "-" * 20 + "\n")
print("Command: " + command)
# print the values for each row
for row in response.primary_results[0]:
print("Result:")
for col in cols:
print("\t", col, "-", row[col])
if __name__ == "__main__":
main()
import { Client as KustoClient, KustoConnectionStringBuilder, KustoResponseDataSet } from "azure-kusto-data/";
import { InteractiveBrowserCredentialInBrowserOptions } from "@azure/identity";
async function main() {
const clusterUri = "<your_cluster_uri>";
const authOptions = {
clientId: "00001111-aaaa-2222-bbbb-3333cccc4444",
redirectUri: "http://localhost:5173",
} as InteractiveBrowserCredentialInBrowserOptions;
const kcsb = KustoConnectionStringBuilder.withUserPrompt(clusterUri, authOptions);
const kustoClient = new KustoClient(kcsb);
const database = "<your_database>";
const table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
const command = `.create table ${table}
(StartTime:datetime,
EndTime:datetime,
State:string,
DamageProperty:int,
Source:string,
StormSummary:dynamic)`;
const response = await kustoClient.executeMgmt(database, command);
printResultsAsValueList(command, response)
}
function printResultsAsValueList(command: string, response: KustoResponseDataSet) {
// create a list of columns
const cols = response.primaryResults[0].columns;
console.log("\n" + "-".repeat(20) + "\n")
console.log("Command: " + command)
// print the values for each row
for (const row of response.primaryResults[0].rows()) {
console.log("Result:")
for (const col of cols) {
console.log("\t", col.name, "-", row.getValueAt(col.ordinal) ? row.getValueAt(col.ordinal).toString() : "None")
}
}
}
main();
手記
Node.js アプリの場合は、InteractiveBrowserCredentialInBrowserOptions
の代わりに InteractiveBrowserCredentialNodeOptions
を使用します。
import com.microsoft.azure.kusto.data.Client;
import com.microsoft.azure.kusto.data.ClientFactory;
import com.microsoft.azure.kusto.data.KustoOperationResult;
import com.microsoft.azure.kusto.data.KustoResultSetTable;
import com.microsoft.azure.kusto.data.KustoResultColumn;
import com.microsoft.azure.kusto.data.auth.ConnectionStringBuilder;
public class ManagementCommands {
public static void main(String[] args) throws Exception {
try {
String clusterUri = "https://<your_cluster_uri>";
ConnectionStringBuilder kcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri);
try (Client kustoClient = ClientFactory.createClient(kcsb)) {
String database = "<your_database>";
String table = "MyStormEvents";
// Create a table named MyStormEvents
// The brackets contain a list of column Name:Type pairs that defines the table schema
String command = ".create table " + table + " " +
"(StartTime:datetime," +
" EndTime:datetime," +
" State:string," +
" DamageProperty:int," +
" DamageCrops:int," +
" Source:string," +
" StormSummary:dynamic)";
KustoOperationResult response = kustoClient.execute(database, command);
printResultsAsValueList(command, response.getPrimaryResults());
}
}
}
public static void printResultsAsValueList(String command, KustoResultSetTable results) {
while (results.next()) {
System.out.println("\n" + "-".repeat(20) + "\n");
System.out.println("Command: " + command);
System.out.println("Result:");
KustoResultColumn[] columns = results.getColumns();
for (int i = 0; i < columns.length; i++) {
System.out.println("\t" + columns[i].getColumnName() + " - " + (results.getObject(i) == null ? "None" : results.getString(i)));
}
}
}
}
アプリを実行する
コマンド シェルで、次のコマンドを使用してアプリを実行します。
# Change directory to the folder that contains the management commands project
dotnet run .
python management_commands.py
Node.js 環境の場合:
node management-commands.js
ブラウザー環境で、適切なコマンドを使用してアプリを実行します。 たとえば、Vite-React の場合:
npm run dev
mvn install exec:java -Dexec.mainClass="<groupId>.ManagementCommands"
次のような結果が表示されます。
--------------------
Command: .create table MyStormEvents
(StartTime:datetime,
EndTime:datetime,
State:string,
DamageProperty:int,
Source:string,
StormSummary:dynamic)
Result:
TableName - MyStormEvents
Schema - {"Name":"MyStormEvents","OrderedColumns":[{"Name":"StartTime","Type":"System.DateTime","CslType":"datetime"},{"Name":"EndTime","Type":"System.DateTime","CslType":"datetime"},{"Name":"State","Type":"System.String","CslType":"string"},{"Name":"DamageProperty","Type":"System.Int32","CslType":"int"},{"Name":"Source","Type":"System.String","CslType":"string"},{"Name":"StormSummary","Type":"System.Object","CslType":"dynamic"}]}
DatabaseName - MyDatabaseName
Folder - None
DocString - None
テーブル レベルのインジェスト バッチ処理ポリシーを変更する
対応するテーブル ポリシーを変更することで、テーブルのインジェスト バッチ処理の動作をカスタマイズできます。 詳細については、「IngestionBatching ポリシー 」を参照してください。
手記
PolicyObject のすべてのパラメーターを指定しない場合、指定されていないパラメーターは既定値に設定されます。 たとえば、"MaximumBatchingTimeSpan" のみを指定すると、"MaximumNumberOfItems" と "MaximumRawDataSizeMB" が既定値に設定されます。
たとえば、次のコマンドを使用して、MyStormEvents
テーブルの ingestionBatching
ポリシーを変更することで、アプリを変更して、インジェスト バッチ処理ポリシー タイムアウト値を 30 秒に変更できます。
// Reduce the default batching timeout to 30 seconds
command = @$".alter-merge table {table} policy ingestionbatching '{{ ""MaximumBatchingTimeSpan"":""00:00:30"" }}'";
using (var response = kustoClient.ExecuteControlCommand(database, command, null))
{
PrintResultsAsValueList(command, response);
}
# Reduce the default batching timeout to 30 seconds
command = ".alter-merge table " + table + " policy ingestionbatching '{ \"MaximumBatchingTimeSpan\":\"00:00:30\" }'"
response = kusto_client.execute_mgmt(database, command)
print_result_as_value_list(command, response)
// Reduce the default batching timeout to 30 seconds
command = ".alter-merge table " + table + " policy ingestionbatching '{ \"MaximumBatchingTimeSpan\":\"00:00:30\" }'"
response = await kustoClient.executeMgmt(database, command)
printResultsAsValueList(command, response)
// Reduce the default batching timeout to 30 seconds
command = ".alter-merge table " + table + " policy ingestionbatching '{ \"MaximumBatchingTimeSpan\":\"00:00:30\" }'";
response = kusto_client.execute(database, command);
printResultsAsValueList(command, response.getPrimaryResults());
アプリにコードを追加して実行すると、次のような結果が表示されます。
--------------------
Command: .alter-merge table MyStormEvents policy ingestionbatching '{ "MaximumBatchingTimeSpan":"00:00:30" }'
Result:
PolicyName - IngestionBatchingPolicy
EntityName - [YourDatabase].[MyStormEvents]
Policy - {
"MaximumBatchingTimeSpan": "00:00:30",
"MaximumNumberOfItems": 500,
"MaximumRawDataSizeMB": 1024
}
ChildEntities - None
EntityType - Table
データベース レベルの保持ポリシーを表示する
管理コマンドを使用して、データベースの 保持ポリシー を表示できます。
たとえば、次のコードを使用して、アプリを変更してデータベースの保持ポリシー を表示することができます。 結果は、2 つの列を除外するようにキュレートされます。
// Show the database retention policy (drop some columns from the result)
command = @$".show database {database} policy retention | project-away ChildEntities, EntityType";
using (var response = kustoClient.ExecuteControlCommand(database, command, null)) {
PrintResultsAsValueList(command, response);
}
# Show the database retention policy (drop some columns from the result)
command = ".show database " + database + " policy retention | project-away ChildEntities, EntityType"
response = kusto_client.execute_mgmt(database, command)
print_result_as_value_list(command, response)
// Show the database retention policy (drop some columns from the result)
command = ".show database " + database + " policy retention | project-away ChildEntities, EntityType"
response = await kustoClient.executeMgmt(database, command)
printResultsAsValueList(command, response)
// Show the database retention policy (drop some columns from the result)
command = ".show database " + database + " policy retention | project-away ChildEntities, EntityType";
response = kusto_client.execute(database, command);
printResultsAsValueList(command, response.getPrimaryResults());
アプリにコードを追加して実行すると、次のような結果が表示されます。
--------------------
Command: .show database YourDatabase policy retention | project-away ChildEntities, EntityType
Result:
PolicyName - RetentionPolicy
EntityName - [YourDatabase]
Policy - {
"SoftDeletePeriod": "365.00:00:00",
"Recoverability": "Enabled"
}
次の手順