기본 쿼리를 실행하는 앱 만들기
이 문서의 내용
적용 대상: ✅Microsoft Fabric ✅Azure Data Explorer
이 문서에서는 다음 방법을 알아봅니다.
필수 구성 요소
Kusto 클라이언트 라이브러리를 사용하도록 개발 환경 설정합니다.
기본 쿼리 실행 및 결과 처리
기본 설정 IDE 또는 텍스트 편집기에서, 선호하는 언어에 적합한 규칙을 사용하여 프로젝트 또는 파일을 만들고 해당 프로젝트나 파일의 이름을 "기본 쿼리 "로 지정합니다. 그런 다음, 다음 코드를 추가합니다.
도움말 클러스터 연결하는 클라이언트 앱을 만듭니다.
using Kusto.Data;
using Kusto.Data.Net.Client;
namespace BasicQuery {
class BasicQuery {
static void Main(string[] args) {
var clusterUri = "https://help.kusto.windows.net/";
var kcsb = new KustoConnectionStringBuilder(clusterUri)
.WithAadUserPromptAuthentication();
using (var kustoClient = KustoClientFactory.CreateCslQueryProvider(kcsb)) {
}
}
}
}
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder
def main():
cluster_uri = "https://help.kusto.windows.net"
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 = "https://help.kusto.windows.net";
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.auth.ConnectionStringBuilder;
public class BasicQuery {
public static void main(String[] args) throws Exception {
try {
String clusterUri = "https://help.kusto.windows.net/";
ConnectionStringBuilder kcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri);
try (Client kustoClient = ClientFactory.createClient(kcsb)) {
}
}
}
}
실행할 데이터베이스 및 쿼리를 정의합니다. 이 쿼리는 총 피해가 1억 달러를 초과한 날짜, 상태 및 총 토네이도 관련 피해를 반환합니다.
var database = "Samples";
var query = @"StormEvents
| where EventType == 'Tornado'
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > 100000000
| order by DailyDamage desc";
database = "Samples"
query = "StormEvents" \
"| where EventType == 'Tornado'" \
"| extend TotalDamage = DamageProperty + DamageCrops" \
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)" \
"| where DailyDamage > 100000000" \
"| order by DailyDamage desc"
const database = "Samples";
const query = `StormEvents
| where EventType == 'Tornado'
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > 100000000
| order by DailyDamage desc`;
String database = "Samples";
String query = "StormEvents\n" +
"| where EventType == 'Tornado'\n" +
"| extend TotalDamage = DamageProperty + DamageCrops\n" +
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)\n" +
"| where DailyDamage > 100000000\n" +
"| order by DailyDamage desc";
쿼리를 실행하고 결과를 출력합니다.
using (var response = kustoClient.ExecuteQuery(database, query, null)) {
int columnNoStartTime = response.GetOrdinal("StartTime");
int columnNoState = response.GetOrdinal("State");
int columnNoDailyDamage = response.GetOrdinal("DailyDamage");
Console.WriteLine("Daily tornado damages over 100,000,000$:");
while (response.Read()) {
Console.WriteLine("{0} - {1}, {2}",
response.GetDateTime(columnNoStartTime),
response.GetString(columnNoState),
response.GetInt64(columnNoDailyDamage));
}
}
response = kusto_client.execute(database, query)
print("Daily tornado damages over 100,000,000$:")
for row in response.primary_results[0]:
print(row["StartTime"], "-", row["State"], ",", row["DailyDamage"], "$")
const response = await kustoClient.execute(database, query);
console.log("Daily tornado damages over 100,000,000$:");
for (row of response.primaryResults[0].rows()) {
console.log(row["StartTime"].toString(), "-", row["State"].toString(), ",", row["DailyDamage"].toString(), "$");
}
KustoOperationResult response = kusto_client.execute(database, query);
KustoResultSetTable primaryResults = response.getPrimaryResults();
System.out.println("Daily tornado damages over 100,000,000$:");
while (primaryResults.next()) {
System.out.println(primaryResults.getString("StartTime") + " - " + primaryResults.getString("State") + " , " + primaryResults.getString("DailyDamage"));
}
전체 코드는 다음과 같습니다.
using Kusto.Data;
using Kusto.Data.Net.Client;
namespace BasicQuery {
class BasicQuery {
static void Main(string[] args) {
string clusterUri = "https://help.kusto.windows.net/";
var kcsb = new KustoConnectionStringBuilder(clusterUri)
.WithAadUserPromptAuthentication();
using (var kustoClient = KustoClientFactory.CreateCslQueryProvider(kcsb)) {
string database = "Samples";
string query = @"StormEvents
| where EventType == 'Tornado'
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > 100000000
| order by DailyDamage desc";
using (var response = kustoClient.ExecuteQuery(database, query, null)) {
int columnNoStartTime = response.GetOrdinal("StartTime");
int columnNoState = response.GetOrdinal("State");
int columnNoDailyDamage = response.GetOrdinal("DailyDamage");
Console.WriteLine("Daily tornado damages over 100,000,000$:");
while (response.Read()) {
Console.WriteLine("{0} - {1}, {2}",
response.GetDateTime(columnNoStartTime),
response.GetString(columnNoState),
response.GetInt64(columnNoDailyDamage));
}
}
}
}
}
}
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder
def main():
cluster_uri = "https://help.kusto.windows.net"
kcsb = KustoConnectionStringBuilder.with_interactive_login(cluster_uri)
with KustoClient(kcsb) as kusto_client:
database = "Samples"
query = "StormEvents" \
"| where EventType == 'Tornado'" \
"| extend TotalDamage = DamageProperty + DamageCrops" \
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)" \
"| where DailyDamage > 100000000" \
"| order by DailyDamage desc"
response = kusto_client.execute(database, query)
print("Daily tornado damages over 100,000,000$:")
for row in response.primary_results[0]:
print(row["StartTime"], "-", row["State"], ",", row["DailyDamage"], "$")
if __name__ == "__main__":
main()
import { Client as KustoClient, KustoConnectionStringBuilder } from "azure-kusto-data";
import { InteractiveBrowserCredentialInBrowserOptions } from "@azure/identity";
async function main() {
const clusterUri = "https://help.kusto.windows.net";
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 = "Samples";
const query = `StormEvents
| where EventType == 'Tornado'
| extend TotalDamage = DamageProperty + DamageCrops
| where DailyDamage > 100000000
| order by DailyDamage desc`;
const response = await kustoClient.execute(database, query);
console.log("Daily tornado damages over 100,000,000$:");
for (row of response.primaryResults[0].rows()) {
console.log(row["StartTime"].toString(), "-", row["State"].toString(), ",", row["DailyDamage"].toString(), "$");
}
}
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.auth.ConnectionStringBuilder;
public class BasicQuery {
public static void main(String[] args) throws Exception {
try {
String clusterUri = "https://help.kusto.windows.net/";
ConnectionStringBuilder kcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri);
try (Client kustoClient = ClientFactory.createClient(kcsb)) {
String database = "Samples";
String query = "StormEvents\n" +
"| where EventType == 'Tornado'\n" +
"| extend TotalDamage = DamageProperty + DamageCrops\n" +
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)\n" +
"| where DailyDamage > 100000000\n" +
"| order by DailyDamage desc";
KustoOperationResult response = kustoClient.execute(database, query);
KustoResultSetTable primaryResults = response.getPrimaryResults();
System.out.println("Daily tornado damages over 100,000,000$:");
while (primaryResults.next()) {
System.out.println(primaryResults.getString("StartTime") + " - " + primaryResults.getString("State") + " , " + primaryResults.getString("DailyDamage"));
}
}
}
}
}
앱 실행
명령 셸에서 다음 명령을 사용하여 앱을 실행합니다.
# Change directory to the folder that contains the basic queries project
dotnet run .
Node.js 환경에서:
node basic-query.js
브라우저 환경에서 적절한 명령을 사용하여 앱을 실행합니다. 예를 들어 Vite-React의 경우:
npm run dev
mvn install exec:java -Dexec.mainClass="<groupId>.BasicQuery"
다음과 유사한 결과가 표시됩니다.
Daily damages tornado with damages over 100,000,000$:
2007-02-02 00:00:00+00:00 - FLORIDA , 270004000 $
2007-03-01 00:00:00+00:00 - ALABAMA , 266853000 $
2007-05-04 00:00:00+00:00 - KANSAS , 251625000 $
2007-03-01 00:00:00+00:00 - GEORGIA , 143688000 $
서수 위치를 사용하여 열 값에 액세스
쿼리 결과의 열 순서를 알 수 있는 경우 열 이름보다 결과 집합의 서수 위치로 열 값에 액세스하는 것이 더 효율적입니다. 필요에 따라 실행 중에 라이브러리 메서드를 사용하여 열 이름으로부터 열 서수를 확인할 수 있습니다.
예를 들어 이전 코드를 수정하여 결과 집합의 서수 위치별로 StartTime
, State
및 DailyDamage
열의 값에 액세스할 수 있습니다.
C#에서는 결과 집합의 서수 위치로만 열 값에 액세스할 수 있습니다. 열 이름은 사용할 수 없습니다. 따라서 코드는 동일하게 유지됩니다.
int columnNoStartTime = response.GetOrdinal("StartTime");
int columnNoState = response.GetOrdinal("State");
int columnNoDailyDamage = response.GetOrdinal("DailyDamage");
Console.WriteLine("Daily tornado damages over 100,000,000$:");
while (response.Read()) {
Console.WriteLine("{0} - {1}, {2}",
response.GetDateTime(columnNoStartTime),
response.GetString(columnNoState),
response.GetInt64(columnNoDailyDamage));
}
state_col = 0
start_time_col = next(col.ordinal for col in response.primary_results[0].columns if col.column_name == "StartTime")
damage_col = 2
print("Daily damages over 100,000,000$:")
for row in response.primary_results[0]:
print(row[start_time_col], "-", row[state_col], ",", row[damage_col], "$")
const columnNoState = 0;
const columnNoStartTime = response.primaryResults[0].columns.find(c => c.name == "StartTime").ordinal;
const columnNoDailyDamage = 2;
console.log("Daily tornado damages over 100,000,000$:");
for (row of response.primaryResults[0].rows()) {
console.log(row.getValueAt(columnNoStartTime).toString(), "-", row.getValueAt(columnNoState).toString(), ",", row.getValueAt(columnNoDailyDamage).toString(), "$");
}
Integer columnNoState = 0;
Integer columnNoStartTime = primaryResults.findColumn("StartTime");
Integer columnNoDailyDamage = 2;
while (primaryResults.next()) {
System.out.println(primaryResults.getString(columnNoStartTime) + " - " + primaryResults.getString(columnNoState) + " , " + primaryResults.getString(columnNoDailyDamage));
}
클라이언트 요청 속성을 사용하여 쿼리 동작 사용자 지정
클라이언트 요청 속성을 설정하여 쿼리 동작을 사용자 지정할 수 있습니다. 사용 가능한 옵션에 대한 자세한 내용은 클라이언트 요청 속성참조하세요.
예를 들어 이전 코드의 kusto_client.execute_query
호출을 바꿔 사용자 지정 요청 ID를 전달하고 쿼리 시간 제한을 1분으로 설정할 수 있습니다. 클라이언트 요청 속성을 사용하려면 ClientRequestProperties
클래스를 가져와야 합니다.
using Kusto.Data.Common;
var crp = new ClientRequestProperties();
// Set a custom client request identifier
crp.ClientRequestId = "QueryDemo" + Guid.NewGuid().ToString();
// Set the query timeout to 1 minute
crp.SetOption(ClientRequestProperties.OptionServerTimeout, "1m");
using (var response = kustoClient.ExecuteQuery(database, query, crp)) {
}
from azure.kusto.data import ClientRequestProperties
from datetime import datetime
import uuid;
crp = ClientRequestProperties()
# Set a custom client request identifier
crp.client_request_id = "QueryDemo" + str(uuid.uuid4())
# Set the query timeout to 1 minute
crp.set_option(crp.request_timeout_option_name, datetime.timedelta(minutes=1))
response = kusto_client.execute_query(database, query, crp)
import { ClientRequestProperties } from "azure-kusto-data";
import { v4 as uuidv4 } from "uuid";
const crp = new ClientRequestProperties();
// Set a custom client request identifier
crp.clientRequestId = "QueryDemo" + uuidv4();
// Set the query timeout to 1 minute
crp.setServerTimeout(1000 * 60);
const response = await kustoClient.execute(database, query, crp);
import com.microsoft.azure.kusto.data.ClientRequestProperties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
ClientRequestProperties crp = new ClientRequestProperties();
// Set a custom client request identifier
crp.setClientRequestId("QueryDemo" + UUID.randomUUID());
// Set the query timeout to 1 minute
crp.setTimeoutInMilliSec(TimeUnit.MINUTES.toMillis(60));
KustoOperationResult response = kusto_client.execute(database, query, crp);
쿼리 매개 변수는 데이터의 보안 및 보호를 유지하는 데 중요합니다. 데이터에 무단으로 액세스하거나 손상하려고 시도할 수 있는 잠재적인 악의적 행위자로부터 보호합니다. 매개 변수가 있는 쿼리에 대한 자세한 내용은Query 매개 변수 선언 문을 참조하세요.
예를 들어 이전 코드를 수정하여 EventType 값과 DailyDamage 최소값을 매개변수로 쿼리에 전달할 수 있습니다. 매개 변수를 사용하려면 다음을 수행합니다.
쿼리 텍스트에서 매개 변수 선언
쿼리 텍스트의 속성 값을 매개 변수 이름으로 대체
execute 메서드에 전달된 클라이언트 요청 속성의 매개 변수 값 설정
string query = @"declare query_parameters(event_type:string, daily_damage:int);
StormEvents
| where EventType == event_type
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > daily_damage
| order by DailyDamage desc";
var crp = new ClientRequestProperties();
crp.SetParameter("event_type", "Flash Flood");
crp.SetParameter("daily_damage", 200000000.ToString());
using (var response = kustoClient.ExecuteQuery(database, query, crp)) {
int columnNoStartTime = response.GetOrdinal("StartTime");
int columnNoState = response.GetOrdinal("State");
int columnNoDailyDamage = response.GetOrdinal("DailyDamage");
Console.WriteLine("Daily flash flood damages over 200,000,000$:");
while (response.Read()) {
Console.WriteLine("{0} - {1}, {2}",
response.GetDateTime(columnNoStartTime),
response.GetString(columnNoState),
response.GetInt64(columnNoDailyDamage));
}
}
query = "declare query_parameters(event_type:string, daily_damage:int);"\
"StormEvents" \
"| where EventType == event_type" \
"| extend TotalDamages = DamageProperty + DamageCrops" \
"| summarize DailyDamage=sum(TotalDamages) by State, bin(StartTime, 1d)" \
"| where DailyDamage > daily_damage" \
"| order by DailyDamage desc"
crp = ClientRequestProperties()
crp.set_parameter("event_type", "Flash Flood")
crp.set_parameter("daily_damage", str(200000000))
response = kusto_client.execute_query(=database, query, crp)
print("Daily flash flood damages over 200,000,000$:")
for row in response.primary_results[0]:
print(row["StartTime"], "-", row["State"], ",", row["DailyDamage"], "$")
const query = `declare query_parameters(event_type:string, daily_damage:int);
StormEvents
| where EventType == event_type
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > daily_damage
| order by DailyDamage desc`;
const crp = new ClientRequestProperties();
crp.setParameter("event_type", "Flash Flood");
crp.setParameter("daily_damage", 200000000);
const response = await kustoClient.execute(database, query, crp);
console.log("Daily flash flood damages over 200,000,000$:");
for (row of response.primaryResults[0].rows()) {
console.log(row.getValueAt(columnNoStartTime).toString(), "-", row.getValueAt(columnNoState).toString(), ",", row.getValueAt(columnNoDailyDamage).toString(), "$");
}
String query = "declare query_parameters(event_type:string, daily_damage:int);\n" +
"StormEvents\n" +
"| where EventType == event_type\n" +
"| extend TotalDamage = DamageProperty + DamageCrops\n" +
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)\n" +
"| where DailyDamage > daily_damage\n" +
"| order by DailyDamage desc";
ClientRequestProperties crp = new ClientRequestProperties();
crp.setParameter("event_type", "Flash Flood");
crp.setParameter("daily_damage", 200000000);
KustoOperationResult response = kusto_client.execute(database, query, crp);
KustoResultSetTable primary_results = response.getPrimaryResults();
System.out.println("Daily flash flood damages over 200,000,000$:");
while (primary_results.next()) {
System.out.println("DEBUG: " + primary_results.getString(columnNoStartTime) + " - " + primary_results.getString(columnNoState) + " , " + primary_results.getString(columnNoDailyDamage));
}
서수 위치를 사용하여 열 값 및 매개 변수에 액세스하는 전체 코드는 다음과 같습니다.
using Kusto.Data;
using Kusto.Data.Common;
using Kusto.Data.Net.Client;
namespace BasicQuery {
class BasicQuery {
static void Main(string[] args) {
string clusterUri = "https://help.kusto.windows.net/";
var kcsb = new KustoConnectionStringBuilder(clusterUri)
.WithAadUserPromptAuthentication();
using (var kustoClient = KustoClientFactory.CreateCslQueryProvider(kcsb)) {
string database = "Samples";
string query = @"declare query_parameters(event_type:string, daily_damage:int);
StormEvents
| where EventType == event_type
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > daily_damage
| order by DailyDamage desc";
var crp = new ClientRequestProperties();
crp.ClientRequestId = "QueryDemo" + Guid.NewGuid().ToString();
crp.SetOption(ClientRequestProperties.OptionServerTimeout, "1m");
crp.SetParameter("event_type", "Flash Flood");
crp.SetParameter("daily_damage", 200000000.ToString());
using (var response = kustoClient.ExecuteQuery(database, query, crp)) {
int columnNoStartTime = response.GetOrdinal("StartTime");
int columnNoState = response.GetOrdinal("State");
int columnNoDailyDamage = response.GetOrdinal("DailyDamage");
Console.WriteLine("Daily flash flood damages over 200,000,000$:");
while (response.Read()) {
Console.WriteLine("{0} - {1}, {2}",
response.GetDateTime(columnNoStartTime),
response.GetString(columnNoState),
response.GetInt64(columnNoDailyDamage));
}
}
}
}
}
}
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder, ClientRequestProperties
from datetime import timedelta
import uuid;
def main():
cluster_uri = "https://help.kusto.windows.net"
kcsb = KustoConnectionStringBuilder.with_interactive_login(cluster_uri)
crp = ClientRequestProperties()
crp.client_request_id = "QueryDemo" + str(uuid.uuid4())
crp.set_option(crp.request_timeout_option_name, timedelta(minutes=1))
crp.set_parameter("event_type", "Flash Flood")
crp.set_parameter("daily_damage", str(200000000))
with KustoClient(kcsb) as kusto_client:
database = "Samples"
query = "declare query_parameters(event_type:string, daily_damage:int);"\
"StormEvents" \
"| where EventType == event_type" \
"| extend TotalDamages = DamageProperty + DamageCrops" \
"| summarize DailyDamage=sum(TotalDamages) by State, bin(StartTime, 1d)" \
"| where DailyDamage > daily_damage" \
"| order by DailyDamage desc"
response = kusto_client.execute_query(database, query, crp)
state_col = 0
start_time_col = next(col.ordinal for col in response.primary_results[0].columns if col.column_name == "StartTime")
damage_col = 2
print("Daily flash flood damages over 200,000,000$:")
for row in response.primary_results[0]:
print(row[start_time_col], "-", row[state_col], ",", row[damage_col], "$")
if __name__ == "__main__":
main()
import {
Client as KustoClient,
KustoConnectionStringBuilder,
ClientRequestProperties
} from "azure-kusto-data";
import { v4 as uuidv4 } from "uuid";
async function main() {
const clusterUri = "https://help.kusto.windows.net";
const kcsb = KustoConnectionStringBuilder.withUserPrompt(clusterUri);
const kustoClient = new KustoClient(kcsb);
const database = "Samples";
const query = `declare query_parameters(event_type:string, daily_damage:int);
StormEvents
| where EventType == event_type
| extend TotalDamage = DamageProperty + DamageCrops
| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)
| where DailyDamage > daily_damage
| order by DailyDamage desc`;
const crp = new ClientRequestProperties();
// Set a custom client request identifier
crp.clientRequestId = "QueryDemo" + uuidv4();
// Set the query timeout to 1 minute
crp.setTimeout(1000 * 60);
crp.setParameter("event_type", "Flash Flood");
crp.setParameter("daily_damage", 200000000);
const response = await kustoClient.execute(database, query, crp);
const columnNoState = 0;
const columnNoStartTime = response.primaryResults[0].columns.find(c => c.name == "StartTime").ordinal;
const columnNoDailyDamage = 2;
console.log("Daily flash flood damages over 200,000,000$:");
for (row of response.primaryResults[0].rows()) {
console.log(row.getValueAt(columnNoStartTime).toString(), "-", row.getValueAt(columnNoState).toString(), ",", row.getValueAt(columnNoDailyDamage).toString(), "$");
}
}
main();
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.auth.ConnectionStringBuilder;
import com.microsoft.azure.kusto.data.ClientRequestProperties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class BasicQuery {
public static void main(String[] args) throws Exception {
try {
String clusterUri = "https://help.kusto.windows.net/";
ConnectionStringBuilder kcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri);
try (Client kustoClient = ClientFactory.createClient(kcsb)) {
String database = "Samples";
String query = "declare query_parameters(event_type:string, daily_damage:int);\n" +
"StormEvents\n" +
"| where EventType == event_type\n" +
"| extend TotalDamage = DamageProperty + DamageCrops\n" +
"| summarize DailyDamage=sum(TotalDamage) by State, bin(StartTime, 1d)\n" +
"| where DailyDamage > daily_damage\n" +
"| order by DailyDamage desc";
ClientRequestProperties crp = new ClientRequestProperties();
// Set a custom client request identifier
crp.setClientRequestId("QueryDemo" + UUID.randomUUID());
// Set the query timeout to 1 minute
crp.setTimeoutInMilliSec(TimeUnit.MINUTES.toMillis(60));
crp.setParameter("event_type", "Flash Flood");
crp.setParameter("daily_damage", 200000000);
KustoOperationResult response = kustoClient.execute(database, query, crp);
KustoResultSetTable primaryResults = response.getPrimaryResults();
Integer columnNoState = 0;
Integer columnNoStartTime = primaryResults.findColumn("StartTime");
Integer columnNoDailyDamage = 2;
System.out.println("Daily flash flood damages over 200,000,000$:");
while (primaryResults.next()) {
System.out.println("DEBUG: " + primaryResults.getString(columnNoStartTime) + " - " + primaryResults.getString(columnNoState) + " , " + primaryResults.getString(columnNoDailyDamage));
}
}
}
}
}
다음과 유사한 결과가 표시됩니다.
Daily flash flood damages over 200,000,000$:
2007-08-21 00:00:00+00:00 - OHIO , 253320000 $
다음 단계