Criar um aplicativo para executar consultas básicas
Artigo 12/18/2024
3 colaboradores
Comentários
Neste artigo
Aplica-se a: ✅Microsoft Fabric ✅Azure Data Explorer
Neste artigo, você aprenderá a:
Pré-requisitos
Configure seu ambiente de desenvolvimento para usar a biblioteca de cliente Kusto.
Executar uma consulta básica e processar os resultados
Em seu IDE ou editor de texto preferido, crie um projeto ou arquivo chamado de consulta básica usando a convenção apropriada para seu idioma preferido. Em seguida, adicione o seguinte código:
Crie um aplicativo cliente que se conecte ao cluster de ajuda .
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();
Observação
Para aplicativos Node.js, use InteractiveBrowserCredentialNodeOptions
em vez de InteractiveBrowserCredentialInBrowserOptions
.
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)) {
}
}
}
}
Defina o banco de dados e a consulta a serem executados. A consulta retorna a data, o estado e o dano total relacionado ao tornado em que o dano total excedeu 100 milhões de dólares.
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";
Execute a consulta e imprima o resultado.
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"));
}
O código completo deve ter esta aparência:
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();
Observação
Para aplicativos Node.js, use InteractiveBrowserCredentialNodeOptions
em vez de InteractiveBrowserCredentialInBrowserOptions
.
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"));
}
}
}
}
}
Executar seu aplicativo
Em um shell de comando, use o seguinte comando para executar seu aplicativo:
# Change directory to the folder that contains the basic queries project
dotnet run .
Num ambiente Node.js:
node basic-query.js
Em um ambiente de navegador, use o comando apropriado para executar seu aplicativo. Por exemplo, para Vite-React:
npm run dev
Observação
Em um ambiente de navegador, abra o console de ferramentas de desenvolvedor para ver a saída.
mvn install exec:java -Dexec.mainClass="<groupId>.BasicQuery"
Deverá ver um resultado semelhante ao seguinte:
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 $
Usar as posições ordinais para aceder aos valores das colunas
Quando a ordem das colunas em um resultado de consulta é conhecida, é mais eficiente acessar os valores das colunas por sua posição ordinal no conjunto de resultados do que pelo nome da coluna. Opcionalmente, em tempo de execução, você pode usar um método de biblioteca para determinar um ordinal de coluna a partir de seu nome de coluna.
Observação
Você pode controlar a presença e a ordem das colunas em um resultado de consulta usando os operadores project
ou project-away
.
Por exemplo, você pode modificar o código anterior para acessar os valores das colunas StartTime
, State
e DailyDamage
por suas posições ordinais no conjunto de resultados:
Em C#, você só pode acessar os valores das colunas por suas posições ordinais no conjunto de resultados. Não é possível usar os nomes das colunas; portanto, o código permanece o mesmo.
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));
}
Personalizar o comportamento da consulta com as propriedades de solicitação do cliente
Você pode personalizar o comportamento de uma consulta definindo as propriedades de solicitação do cliente. Para mais informações sobre as opções disponíveis, consulte as propriedades do pedido do cliente .
Por exemplo, você pode substituir a chamada kusto_client.execute_query
no código anterior para passar uma ID de solicitação personalizada e definir o tempo limite de consulta para 1 minuto. Para usar as propriedades de solicitação do cliente, você deve importar a classe 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);
Os parâmetros de consulta são importantes para manter a segurança e a proteção dos seus dados. Protege-o de potenciais agentes maliciosos que possam tentar obter acesso não autorizado ou corromper os seus dados. Para obter mais informações sobre consultas parametrizadas, consulte instrução de declaração de parâmetros de consulta .
Por exemplo, pode modificar o código anterior para passar o valor de EventType e o valor mínimo de DailyDamage como parâmetros para a consulta. Para usar parâmetros:
Declarar os parâmetros no texto da consulta
Substitua os valores de propriedade no texto da consulta pelos nomes dos parâmetros
Defina os valores de parâmetro nas propriedades de solicitação do cliente passadas para o método 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));
}
O código completo usando posições ordinais para acessar valores e parâmetros de coluna deve ter esta aparência:
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));
}
}
}
}
}
Deverá ver um resultado semelhante ao seguinte:
Daily flash flood damages over 200,000,000$:
2007-08-21 00:00:00+00:00 - OHIO , 253320000 $
Próximo passo