관리 명령을 실행하는 앱 만들기
이 문서의 내용
적용 대상: ✅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
데이터베이스 수준 보존 정책 표시
관리 명령을 사용하여 데이터베이스의 보존 정책 표시할 수 있습니다.
예를 들어, 다음 코드를 사용하여 앱을 수정하여 데이터베이스의 보존 정책을 표시할 수 있습니다. 결과는 결과에서 두 열을 멀리 프로젝팅하도록 큐레이팅됩니다.
// 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"
}
다음 단계