Creare un'app per eseguire query di base
Articolo 12/19/2024
3 contributori
Commenti e suggerimenti
In questo articolo
Si applica a: ✅Microsoft Fabric ✅Esplora dati di Azure
Questo articolo illustra come:
Prerequisiti
Configurare l'ambiente di sviluppo per usare la libreria client Kusto.
Eseguire una query di base ed elaborare i risultati
Nell'IDE o nell'editor di testo preferito creare un progetto o un file denominato query di base usando la convenzione appropriata per il linguaggio preferito. Aggiungere quindi il codice seguente:
Crea un'app client che si collega al cluster di aiuto .
C#
Python
#TypeScript#
Java
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();
Nota
Per le app Node.js, usare InteractiveBrowserCredentialNodeOptions
anziché 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)) {
}
}
}
}
Definire il database e la query da eseguire. L'interrogazione restituisce la data, lo stato e il danno totale correlato al tornado quando il danno totale ha superato i 100 milioni di dollari.
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";
Esegui la query e stampa il risultato.
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"));
}
Il codice completo dovrebbe essere simile al seguente:
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();
Nota
Per le app Node.js, usare InteractiveBrowserCredentialNodeOptions
anziché 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"));
}
}
}
}
}
Esegui la tua app
In una shell di comando, utilizzare il comando seguente per eseguire la tua app:
C#
Python
TypeScript
Java
# Change directory to the folder that contains the basic queries project
dotnet run .
In un ambiente Node.js:
node basic-query.js
In un ambiente browser usare il comando appropriato per eseguire l'app. Ad esempio, per Vite-React:
npm run dev
Nota
In un ambiente browser aprire la console degli strumenti di sviluppo per visualizzare l'output.
mvn install exec:java -Dexec.mainClass="<groupId>.BasicQuery"
Verrà visualizzato un risultato simile al seguente:
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 $
Usare le posizioni ordinali per accedere ai valori delle colonne
Quando l'ordine delle colonne in un risultato della query è noto, è più efficiente accedere ai valori delle colonne in base alla posizione ordinale nel set di risultati rispetto al nome della colonna. Facoltativamente, in fase di esecuzione è possibile usare un metodo di libreria per determinare un ordinale di colonna dal nome della colonna.
Nota
È possibile controllare la presenza e l'ordine delle colonne in un risultato della query usando gli operatori project
o project-away
.
Ad esempio, è possibile modificare il codice precedente per accedere ai valori delle colonne StartTime
, State
e DailyDamage
in base alle rispettive posizioni ordinali nel set di risultati:
In C# è possibile accedere solo ai valori delle colonne in base alle rispettive posizioni ordinali nel set di risultati. Non è possibile usare i nomi delle colonne; pertanto, il codice rimane invariato.
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));
}
Personalizzare il comportamento delle interrogazioni con le proprietà della richiesta del client
È possibile personalizzare il comportamento di una query impostando le proprietà della richiesta client. Per ulteriori informazioni sulle opzioni disponibili, vedere le proprietà delle richieste del client .
Ad esempio, è possibile sostituire la chiamata kusto_client.execute_query
nel codice precedente per passare un ID richiesta personalizzato e impostare il timeout della query su 1 minuto. Per usare le proprietà della richiesta client, è necessario importare la 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);
I parametri di query sono importanti per mantenere la sicurezza e la protezione dei dati. Protegge da potenziali attori malintenzionati che potrebbero tentare di ottenere l'accesso non autorizzato o danneggiare i dati. Per altre informazioni sulle query con parametri, vedere istruzione di dichiarazione dei parametri di query .
Ad esempio, è possibile modificare il codice precedente per passare il valore EventType e il valore minimo DailyDamage come parametri alla query. Per usare i parametri:
Dichiarare i parametri nel testo della query
Sostituire i valori delle proprietà nel testo della query con i nomi dei parametri
Imposta i valori dei parametri nelle proprietà della richiesta client passate al metodo 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));
}
Il codice completo che usa le posizioni ordinali per accedere ai valori di colonna e ai parametri dovrebbe essere simile al seguente:
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));
}
}
}
}
}
Verrà visualizzato un risultato simile al seguente:
Daily flash flood damages over 200,000,000$:
2007-08-21 00:00:00+00:00 - OHIO , 253320000 $
Passaggio successivo