### Example: Two-step purge - Start purge Source: https://learn.microsoft.com/en-us/kusto/concepts/data-purge Example of initiating a two-step purge by running the first step of the command. ```kusto // Connect to the Data Management service #connect "https://ingest-[YourClusterName].[Region].kusto.windows.net" .purge table MyTable in database MyDatabase allrecords ``` -------------------------------- ### Complete Kusto App Setup (TypeScript) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-hello-kusto A complete TypeScript example showing how to initialize the Kusto client with user prompt authentication, execute a query, and log the result. ```typescript 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 = "print Welcome='Hello Kusto!'"; const response = await kustoClient.execute(database, query); console.log(response.primaryResults[0][0]["Welcome"].toString()); } main(); ``` -------------------------------- ### Java example for Kusto client setup and initial row count query Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-managed-streaming-ingest This Java code sets up the Kusto client using `DefaultAzureCredential` and queries the initial row count of a table before ingestion. Replace placeholders for cluster URIs and database name. ```java package com.example; import java.io.FileWriter; import com.azure.identity.DefaultAzureCredential; import com.azure.identity.DefaultAzureCredentialBuilder; 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; import com.microsoft.azure.kusto.ingest.IngestClientFactory; import com.microsoft.azure.kusto.ingest.IngestionProperties; import com.microsoft.azure.kusto.ingest.ManagedStreamingIngestClient; import com.microsoft.azure.kusto.ingest.IngestionProperties.DataFormat; import com.microsoft.azure.kusto.ingest.source.FileSourceInfo; public class BatchIngestion { public static void main(String[] args) throws Exception { String clusterUri = ""; String ingestionUri = ""; String databaseName = ""; String table = "MyStormEvents"; ConnectionStringBuilder clusterKcsb = ConnectionStringBuilder.createWithUserPrompt(clusterUri); ConnectionStringBuilder ingestionKcsb = ConnectionStringBuilder.createWithUserPrompt(ingestionUri); try (Client kustoClient = ClientFactory.createClient(clusterKcsb)) { String query = table + " | count"; KustoOperationResult results = kustoClient.execute(databaseName, query); KustoResultSetTable primaryResults = results.getPrimaryResults(); System.out.println("\nNumber of rows in " + table + " BEFORE ingestion:"); printResultsAsValueList(primaryResults); } } public static void printResultsAsValueList(KustoResultSetTable results) { while (results.next()) { 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))); } } } } ``` -------------------------------- ### Get the start of the day with an offset Source: https://learn.microsoft.com/en-us/kusto/query/startofday-function This example demonstrates how to use the startofday() function with a date and an offset. The offset parameter allows you to shift the start of the day by a specified number of days. ```kusto range offset from -1 to 1 step 1 | project dayStart = startofday(datetime(2017-01-01 10:10:17), offset) ``` -------------------------------- ### Convert strings to guid Source: https://learn.microsoft.com/en-us/kusto/query/toguid-function This example demonstrates converting strings within a datatable to guid scalars. It handles valid guid formats and strings that cannot be converted. ```Kusto datatable(str: string) [ "0123456789abcdef0123456789abcdef", "0123456789ab-cdef-0123-456789abcdef", "a string that is not a guid" ] | extend guid = toguid(str) ``` -------------------------------- ### Install Dependencies and Build Project Source: https://learn.microsoft.com/en-us/kusto/api/monaco/monaco-kusto Run this command to install all necessary dependencies and build the project. ```bash npm install ``` -------------------------------- ### Get Start of Week with Offset Source: https://learn.microsoft.com/en-us/kusto/query/startofweek-function Calculates the start of the week for a specific date, demonstrating the effect of different offsets. The default start of the week is Sunday. ```kusto range offset from -1 to 1 step 1 | project weekStart = startofweek(datetime(2017-01-01 10:10:17), offset) ``` -------------------------------- ### Create a new Java project with Maven Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-set-up Use the maven-archetype-quickstart template to generate a new Java project. Ensure to replace placeholder values as needed. ```bash mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId==my-app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false ``` -------------------------------- ### Basic Path Mode Examples Source: https://learn.microsoft.com/en-us/kusto/query/graph-query-language-reference Demonstrates syntax for default (WALK with DIFFERENT EDGES), explicit WALK, TRAIL, and ACYCLIC path modes. ```gql -- Default (WALK with DIFFERENT EDGES) MATCH (n)-[]->(m) RETURN n, m ``` ```gql -- Explicit WALK mode MATCH WALK (n)-[]->(m) RETURN n, m ``` ```gql -- TRAIL mode - no repeating edges MATCH TRAIL (n)-[]->{1,3}(m) RETURN n, m ``` ```gql -- ACYCLIC mode - no repeating nodes MATCH ACYCLIC (n)-[]->{1,3}(m) RETURN n, m ``` -------------------------------- ### Verify Project and Start Watch Mode Source: https://learn.microsoft.com/en-us/kusto/api/monaco/monaco-kusto Execute this command to verify the project is working correctly. If successful, the index.html file will open automatically. ```bash npm run watch ``` -------------------------------- ### Get column names from a datatable Source: https://learn.microsoft.com/en-us/kusto/query/column-names-of-function This example demonstrates how to get the column names from a datatable defined using a let statement. ```APIDOC ## Get column names from a datatable ### Description This example returns the columns of the tabular expression `T`. `T` can be a table in the database or defined with a `let` statement. ### Method ```kusto let T = datatable(A:string, B:int) []; print Columns=column_names_of(T) ``` ### Output ```json [ "A", "B" ] ``` ``` -------------------------------- ### Calculating start of week as Monday Source: https://learn.microsoft.com/en-us/kusto/query/startofweek-function This example shows how to define a helper function to calculate the start of the week as Monday for a specified date. ```APIDOC ## startofweekFromMonday(dateArg) ### Description Calculates the start of the week, considering Monday as the first day of the week, for a given date argument. ### Parameters #### Path Parameters - **dateArg** (datetime) - Required - The date for which to calculate the Monday start of the week. ### Request Example ```kusto let startofweekFromMonday = (dateArg: datetime) { datetime_add('day', 1, startofweek(datetime_add('day', -1, dateArg))) }; let data=datatable(Date: datetime, day: string) [ datetime(2025, 6, 14), "Saturday", datetime(2025, 6, 15), "Sunday", datetime(2025, 6, 16), "Monday", datetime(2025, 6, 17), "Tuesday" ]; data | extend MondayWeek=startofweekFromMonday(Date) ``` ### Response #### Success Response (200) - **MondayWeek** (datetime) - The calculated start of the week, with Monday as the first day. #### Response Example ``` Date | day | MondayWeek --- 2025-06-14 00:00:00.0000000 | Saturday | 2025-06-09 00:00:00.0000000 2025-06-15 00:00:00.0000000 | Sunday | 2025-06-09 00:00:00.0000000 2025-06-16 00:00:00.0000000 | Monday | 2025-06-16 00:00:00.0000000 2025-06-17 00:00:00.0000000 | Tuesday | 2025-06-16 00:00:00.0000000 ``` ``` -------------------------------- ### Install Kusto Golang SDK Source: https://learn.microsoft.com/en-us/kusto/api/golang/kusto-golang-client-library Use this command to install the Kusto Go Client library. Ensure you have Go version 1.13 or later. ```bash go get github.com/Azure/azure-kusto-go/kusto ``` -------------------------------- ### Complete Kusto App Setup (C#) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-hello-kusto A complete C# application demonstrating how to connect to Kusto, execute a query, and print the result. ```csharp using Kusto.Data; using Kusto.Data.Net.Client; namespace HelloKusto { class HelloKusto { 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 = "print Welcome='Hello Kusto!'"; using (var response = kustoClient.ExecuteQuery(database, query, null)) { response.Read(); int columnNo = response.GetOrdinal("Welcome"); Console.WriteLine(response.GetString(columnNo)); } } } } } ``` -------------------------------- ### Row numbering starting from a specific value Source: https://learn.microsoft.com/en-us/kusto/query/row-number-function This example shows how to use row_number() to start the row index from a value other than the default of 1. ```Kusto range a from 1 to 10 step 1 | sort by a desc | extend rn=row_number(7) ``` -------------------------------- ### Example: Update schema of OriginalTable Source: https://learn.microsoft.com/en-us/kusto/management/change-column-type-without-data-loss This example demonstrates the full process of changing a column type from guid to string for 'Col1' in 'OriginalTable' while preserving data. ```Kusto .create table OriginalTable (Col1:guid, Id:int) ``` ```Kusto .ingest inline into table OriginalTable <| b642dec0-1040-4eac-84df-a75cfeba7aa4,1 c224488c-ad42-4e6c-bc55-ae10858af58d,2 99784a64-91ad-4897-ae0e-9d44bed8eda0,3 d8857a93-2728-4bcb-be1d-1a2cd35386a7,4 b1ddcfcc-388c-46a2-91d4-5e70aead098c,5 ``` ```Kusto .create table NewTable (Col1:string, Id:int) ``` ```Kusto .set-or-append NewTable <| OriginalTable | extend Col1=tostring(Col1) ``` ```Kusto .rename tables NewTable = OriginalTable, OriginalTable = NewTable ``` ```Kusto .drop table NewTable ``` -------------------------------- ### Verify .NET SDK Installation Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-set-up Run this command in your command shell to confirm that your installed .NET SDK versions meet the minimum requirements. ```bash dotnet sdk check ``` -------------------------------- ### Filter states that do not start with 'N' Source: https://learn.microsoft.com/en-us/kusto/query/not-hasprefix-operator This example demonstrates filtering the StormEvents table to show states that do not start with the letter 'N', and then further filters for events with a count greater than 2000. ```kusto StormEvents | summarize event_count=count() by State | where State !hasprefix "N" | where event_count > 2000 | project State, event_count ``` -------------------------------- ### Create a client app that connects to the help cluster (Java) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-basic-query Establishes a connection to the Kusto help cluster using Java and user prompt authentication. ```Java 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)) { } } } } ``` -------------------------------- ### Extract a slice using negative start and end indices Source: https://learn.microsoft.com/en-us/kusto/query/array-slice-function This example illustrates extracting a slice using negative start and end indices, both counting from the end of the array. ```kusto print arr=dynamic([1,2,3,4,5]) | extend sliced=array_slice(arr, -3, -2) ``` -------------------------------- ### Extract a subset of capturing groups from a GUID Source: https://learn.microsoft.com/en-us/kusto/query/extract-all-function This example shows how to use the `captureGroups` parameter to select specific capturing groups. Here, it extracts only the first and last characters of each GUID part. ```Kusto print Id="82b8be2d-dfa7-4bd1-8f63-24ad26d31449" | extend guid_bytes = extract_all(@"(\w)(\w+)(\w)", dynamic([1,3]), Id) ``` -------------------------------- ### Full C# Example for Batch Ingestion Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-queued-ingestion A complete C# example demonstrating how to set up and perform batch ingestion from an in-memory stream. Includes necessary usings and main function structure. ```csharp using System.Data; using Azure.Identity; using Kusto.Data; using Kusto.Data.Common; using Kusto.Data.Net.Client; using Kusto.Ingest; namespace BatchIngest; class BatchIngest { static async Task Main() { string singleLine = "2018-01-26 00:00:00.0000000,2018-01-27 14:00:00.0000000,MEXICO,0,0,Unknown,\"{}\""; var stringStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(singleLine)); ... _= await ingestClient.IngestFromStreamAsync(stringStream, ingestProps, new StreamSourceOptions {Size = stringStream.Length}); ... } static void PrintResultsAsValueList(IDataReader response) { ... } } ``` -------------------------------- ### Run .NET Hello Kusto App Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-hello-kusto Command to run a .NET 'Hello Kusto' project from the command line. Ensure you are in the project directory. ```bash # Change directory to the folder that contains the hello world project dotnet run . ``` -------------------------------- ### Extract GUID bytes using extract_all() Source: https://learn.microsoft.com/en-us/kusto/query/extract-all-function This example demonstrates extracting individual byte pairs (two hex-digits) from a GUID string. The regex captures two hexadecimal characters at a time. ```Kusto print Id="82b8be2d-dfa7-4bd1-8f63-24ad26d31449" | extend guid_bytes = extract_all(@"([\da-f]{2})", Id) ``` -------------------------------- ### Kusto Error Details Example Source: https://learn.microsoft.com/en-us/kusto/tools/kusto-explorer-troubleshooting This is an example of the detailed error output you might see when Kusto Explorer fails to start due to a ClickOnce issue. It includes system exceptions and stack traces. ```kusto Following errors were detected during this operation. * System.ArgumentException - Value does not fall within the expected range. - Source: System.Deployment - Stack trace: at System.Deployment.Application.NativeMethods.CorLaunchApplication(UInt32 hostType, String applicationFullName, Int32 manifestPathsCount, String[] manifestPaths, Int32 activationDataCount, String[] activationData, PROCESS_INFORMATION processInformation) at System.Deployment.Application.ComponentStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter) at System.Deployment.Application.SubscriptionStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter) at System.Deployment.Application.ApplicationActivator.Activate(DefinitionAppId appId, AssemblyManifest appManifest, String activationParameter, Boolean useActivationParameter) at System.Deployment.Application.ApplicationActivator.ProcessOrFollowShortcut(String shortcutFile, String& errorPageUrl, TempFile& deployFile) at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl) at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state) ``` -------------------------------- ### Partition Reference with Legacy Strategy Source: https://learn.microsoft.com/en-us/kusto/query/partition-operator This example illustrates how to use the 'as' operator with the legacy partition strategy to name a data partition and reference it within the subquery. It calculates the percentage of a metric relative to the sum of the metric within that partition. ```kql T | partition by Dim ( as Partition | extend MetricPct = Metric * 100.0 / toscalar(Partition | summarize sum(Metric)) ) ``` -------------------------------- ### Filter states not starting with 'I' (case-sensitive) Source: https://learn.microsoft.com/en-us/kusto/query/not-startswith-cs-operator Use the `!startswith_cs` operator to filter records where a column's value does not begin with a specific case-sensitive string. This example filters `StormEvents` data to exclude states starting with 'I'. ```kql StormEvents | summarize event_count=count() by State | where State !startswith_cs "I" | where event_count > 2000 | project State, event_count ``` -------------------------------- ### List All Plugins Source: https://learn.microsoft.com/en-us/kusto/management/show-plugins Use this command to view all plugins configured for the cluster and their current enabled status. Ensure you have the necessary permissions. ```kusto .show plugins ``` -------------------------------- ### Show detailed statistics including processing steps Source: https://learn.microsoft.com/en-us/kusto/management/graph/graph-snapshot-statistics-show This example demonstrates how to view detailed statistics for a snapshot, including a JSON object in the 'Details' column that breaks down the snapshot creation process step-by-step. ```json { "Steps": [ { "Kind": "AddNodes", "StepNumber": 0, "Status": "Completed", "Duration": "00:00:00.9260505", "StartTime": "2025-09-04T12:15:33.1567939Z", "AddedElementsCount": 2, "AddedElementsSizeDelta": 1838, "TotalCpu": "00:00:01.0937500", "MemoryPeak": 1193360 }, { "Kind": "AddEdges", "StepNumber": 1, "Status": "Completed", "Duration": "00:00:00.4027208", "StartTime": "2025-09-04T12:15:34.0846894Z", "AddedElementsCount": 2, "AddedElementsSizeDelta": 2688, "TotalCpu": "00:00:00.3906250", "MemoryPeak": 3789792 }, { "Kind": "AddNodes", "StepNumber": 2, "Status": "Completed", "Duration": "00:00:00.6202220", "StartTime": "2025-09-04T12:15:39.2880152Z", "AddedElementsCount": 2, "AddedElementsSizeDelta": 1547, "TotalCpu": "00:00:00.7343750", "MemoryPeak": 2158192 } ], "Seal": { "Status": "Completed", "StartTime": "2025-09-10T10:30:13.000Z", "Duration": "00:00:12.500", "TotalCpu": "00:00:06.250", "MemoryPeak": 104857600 } } ``` -------------------------------- ### Get column names from a function with parameters Source: https://learn.microsoft.com/en-us/kusto/query/column-names-of-function This example illustrates how to use `column_names_of()` with a function that accepts arguments. ```APIDOC ## Get column names from a function with parameters ### Description If the function has arguments, they can be used when calling `column_names_of()`. ### Method ```kusto let MyFunction1 = (param1:int) { print A="", B=1 }; print Columns=column_names_of(MyFunction1(1)) ``` ### Output ```json [ "A", "B" ] ``` ``` -------------------------------- ### Get a list of all supported timezones Source: https://learn.microsoft.com/en-us/kusto/query/datetime-list-timezones Use this function to retrieve all IANA-supported timezones. No setup or parameters are required. ```kusto print datetime_list_timezones() ``` -------------------------------- ### Extract a slice from an array Source: https://learn.microsoft.com/en-us/kusto/query/array-slice-function This example demonstrates extracting a slice from an array using positive start and end indices. ```kusto print arr=dynamic([1,2,3]) | extend sliced=array_slice(arr, 1, 2) ``` -------------------------------- ### Create C# Client App for Management Commands Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-management-commands Use `KustoClientFactory.CreateCslAdminProvider` to create a client for management commands. Ensure you replace the placeholder with your cluster URI. ```csharp using Kusto.Data; using Kusto.Data.Net.Client; namespace ManagementCommands { class ManagementCommands { static void Main(string[] args) { var clusterUri = ""; var kcsb = new KustoConnectionStringBuilder(clusterUri) .WithAadUserPromptAuthentication(); using (var kustoClient = KustoClientFactory.CreateCslAdminProvider(kcsb)) { } } } } ``` -------------------------------- ### Load Kusto Libraries and Connect to Cluster Source: https://learn.microsoft.com/en-us/kusto/api/powershell/powershell Demonstrates loading Kusto client libraries and establishing a connection to the 'help' cluster for query execution. This example uses interactive MS Entra user authentication. ```PowerShell # This is an example of the location from where you extract the Microsoft.Azure.Kusto.Tools package # Make sure you load the types from a local directory and not from a remote share # Make sure you load the version compatible with your PowerShell version (see explanations above) # Use `dir "$packagesRoot\*" | Unblock-File` to make sure all these files can be loaded and executed $packagesRoot = "C:\Microsoft.Azure.Kusto.Tools\tools\net472" # Load the Kusto client library and its dependencies [System.Reflection.Assembly]::LoadFrom("$packagesRoot\Kusto.Data.dll") # Define the connection to the help cluster and database $clusterUrl = "https://help.kusto.windows.net;Fed=True" $databaseName = "Samples" # MS Entra user authentication with interactive prompt $kcsb = New-Object Kusto.Data.KustoConnectionStringBuilder($clusterUrl, $databaseName) # Run a simple query $queryProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider($kcsb) $query = "StormEvents | take 5" $reader = $queryProvider.ExecuteQuery($query, $crp) ``` -------------------------------- ### Get column names from a function Source: https://learn.microsoft.com/en-us/kusto/query/column-names-of-function This example shows how to retrieve column names from a function that returns a tabular expression. ```APIDOC ## Get column names from a function ### Description This example demonstrates calling `column_names_of()` with functions. ### Method ```kusto let MyFunction1 = () { print A="", B=1 }; print Columns=column_names_of(MyFunction1()) ``` ### Output ```json [ "A", "B" ] ``` ``` -------------------------------- ### Create a client app that connects to the help cluster (Python) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-basic-query Establishes a connection to the Kusto help cluster using Python and interactive login. ```Python 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() ``` -------------------------------- ### Filter states not starting with 'i' and with event count > 2000 Source: https://learn.microsoft.com/en-us/kusto/query/not-startswith-operator This example demonstrates filtering the StormEvents table to find states whose names do not start with 'i' and have an event count greater than 2000. It uses the !startswith operator for case-insensitive filtering. ```kql StormEvents | summarize event_count=count() by State | where State !startswith "i" | where event_count > 2000 | project State, event_count ``` -------------------------------- ### Calculate Session Start Values with row_window_session() Source: https://learn.microsoft.com/en-us/kusto/query/row-window-session-function This example demonstrates how to use row_window_session to identify session start times. Sessions are defined by a maximum duration of one hour, with individual records within a session not exceeding five minutes apart. A new session also starts if the 'ID' column changes. ```kql datatable (ID:string, Timestamp:datetime) [ "1", datetime(2024-04-11 10:00:00), "2", datetime(2024-04-11 10:18:00), "1", datetime(2024-04-11 11:00:00), "3", datetime(2024-04-11 11:30:00), "2", datetime(2024-04-11 13:30:00), "2", datetime(2024-04-11 10:16:00) ] | sort by ID asc, Timestamp asc | extend SessionStarted = row_window_session(Timestamp, 1h, 5m, ID != prev(ID)) ``` -------------------------------- ### Send Multiple Prompts with Options (Impersonation) Source: https://learn.microsoft.com/en-us/kusto/query/ai-chat-completion-prompt-plugin Use this example to send multiple prompts with custom options and impersonation authentication. The `true` parameter at the end indicates that each row should be processed as a separate prompt. ```Kusto let connectionString = 'https://myaccount.openai.azure.com/openai/deployments/gpt4o/chat/completions?api-version=2024-06-01;impersonate'; let options = dynamic({ "RetriesOnThrottling": 1, "GlobalTimeout": 2m, "ModelParameters": { "temperature: 0.7 } }); datatable(Prompt: string) [ "Provide a summary of AI capabilities", "What is the answer to everything?", "What is 42?" ] | evaluate ai_chat_completion_prompt(prompt, connectionString, options , true) ``` -------------------------------- ### startofweek() function usage Source: https://learn.microsoft.com/en-us/kusto/query/startofweek-function This example demonstrates how to use the startofweek() function with an offset to find the start of the week for a given date. ```APIDOC ## startofweek(date, offset) ### Description Returns the start of the week containing the date, shifted by an offset, if provided. Start of the week is considered to be a Sunday. ### Parameters #### Path Parameters - **date** (datetime) - Required - The date for which to find the start of week. - **offset** (int) - Optional - The number of weeks to offset from the input date. The default is 0. ### Request Example ```kusto range offset from -1 to 1 step 1 | project weekStart = startofweek(datetime(2017-01-01 10:10:17), offset) ``` ### Response #### Success Response (200) - **weekStart** (datetime) - The start of the week for the given date value, with the offset, if specified. #### Response Example ``` weekStart --- 2016-12-25 00:00:00.0000000 2017-01-01 00:00:00.0000000 2017-01-08 00:00:00.0000000 ``` ``` -------------------------------- ### Numeric bin() example Source: https://learn.microsoft.com/en-us/kusto/query/bin-function Demonstrates the basic usage of the bin() function with a numeric value. ```Kusto print bin(4.5, 1) ``` -------------------------------- ### Example Output of Table Creation Command Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-management-commands This snippet shows the expected output after successfully running a command to create a table with specific schema definitions. ```bash -------------------- 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 ``` -------------------------------- ### Get H3 Cell and its Neighbors Source: https://learn.microsoft.com/en-us/kusto/query/geo-h3cell-neighbors-function This example shows how to combine the original H3 cell token with its neighbors into a single array. ```Kusto let h3cell = '862a1072fffffff'; print cells = array_concat(pack_array(h3cell), geo_h3cell_neighbors(h3cell)) ``` -------------------------------- ### Show all tables in the database Source: https://learn.microsoft.com/en-us/kusto/management/show-tables-command This example demonstrates how to display information for all tables present in the current database. ```APIDOC ## .show tables command ### Description Returns a set that contains the specified tables or all tables in the database. ### Syntax `.show` `tables` ### Permissions Requires Database User, Database Viewer, or Database Monitor permissions. ### Returns - **TableName** (string) - The name of the table. - **DatabaseName** (string) - The database that the table belongs to. - **Folder** (string) - The table's folder. - **DocString** (string) - A string documenting the table. ### Request Example ```kusto .show tables ``` ### Response Example ```json [ { "TableName": "StormEvents", "DatabaseName": "Samples", "Folder": "Storm_Events", "DocString": "US storm events. Data source: https://www.ncdc.noaa.gov/stormevents" }, { "TableName": "demo_make_series1", "DatabaseName": "Samples", "Folder": "TimeSeries_and_ML", "DocString": "" } ] ``` ``` -------------------------------- ### Joining Start and Stop Events with Aliased Keys Source: https://learn.microsoft.com/en-us/kusto/query/join-innerunique Similar to the previous example, this query joins 'Start' and 'Stop' events but uses explicit aliases for the ActivityId from both the left and right sides of the join. This is useful when the join key names are the same in both tables. ```Kusto let Events = MyLogTable | where type=="Event" ; Events | where Name == "Start" | project Name, City, ActivityIdLeft = ActivityId, StartTime=timestamp | join (Events | where Name == "Stop" | project StopTime=timestamp, ActivityIdRight = ActivityId) on $left.ActivityIdLeft == $right.ActivityIdRight | project City, ActivityId, StartTime, StopTime, Duration = StopTime - StartTime ``` -------------------------------- ### Get Time 2 Days Ago Source: https://learn.microsoft.com/en-us/kusto/query/now-function This example demonstrates how to retrieve the time from two days prior to the current UTC time. ```kusto print now(-2d) ``` -------------------------------- ### Create a client app that connects to the help cluster (C#) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-basic-query Establishes a connection to the Kusto help cluster using C# and Azure AD user prompt authentication. ```C# 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)) { } } } } ``` -------------------------------- ### Basic Usage Example Source: https://learn.microsoft.com/en-us/kusto/query/hash-md5-function This example demonstrates the basic usage of the hash_md5() function with different data types. ```APIDOC ## Examples ### Basic Usage ```kusto print h1=hash_md5("World"), h2=hash_md5(datetime(2020-01-01)) ``` ### Output ``` h1 | h2 -----------------------------------|----------------------------------- ``` | f5a7924e621e84c9280a9a27e1bcb7f6 | 786c530672d1f8db31fee25ea8a9390b ``` -------------------------------- ### Trim non-alphanumeric characters using trim_start() Source: https://learn.microsoft.com/en-us/kusto/query/trim-start-function This example shows how to remove all non-word characters from the start of a string using a regular expression with trim_start(). ```Kusto range x from 1 to 5 step 1 | project str = strcat("- ","Te st",x,@"// $") | extend trimmed_str = trim_start(@"[^"]+",str) ``` -------------------------------- ### Legacy Partition Strategy with Explicit Source and Union Source: https://learn.microsoft.com/en-us/kusto/query/partition-operator This example demonstrates the legacy partition strategy by creating a range of numbers and partitioning the StormEvents table based on a condition involving the partition variable 'x' and 'InjuriesIndirect'. It returns the total count of rows matching the conditions. ```kql range x from 1 to 2 step 1 | partition hint.strategy=legacy by x {StormEvents | where x == InjuriesIndirect} | count ``` -------------------------------- ### Get Current Principal Name Source: https://learn.microsoft.com/en-us/kusto/query/current-principal-function This example demonstrates how to use the current_principal() function to retrieve the current principal's fully qualified name. ```APIDOC ## current_principal() ### Description Provides the current principal name that runs the query. ### Syntax `current_principal()` ### Returns The current principal fully qualified name (FQN) as a `string`. The string format is: _PrinciplaType_`=` _PrincipalId_`;` _TenantId_ ### Examples #### Basic Usage ```kusto print fqn=current_principal() ``` #### Output Example ``` fqn --------------------------------------------------------------------------------------- aaduser=346e950e-4a62-42bf-96f5-4cf4eac3f11e;72f988bf-86f1-41af-91ab-2d7cd011db47 ``` ``` -------------------------------- ### Python Plugin Example in KQL Source: https://learn.microsoft.com/en-us/kusto/query/python-plugin Demonstrates how to use the Python plugin to add a new 'fx' column to the input data based on sine wave calculations. It utilizes reserved variables like 'df' and 'kargs', and requires numpy and pandas to be imported. ```kql range x from 1 to 360 step 1 | evaluate python( // typeof(*, fx:double), // Output schema: append a new fx column to original table ``` result = df n = df.shape[0] g = kargs["gain"] f = kargs["cycles"] result["fx"] = g * np.sin(df["x"]/n*2*np.pi*f) ``` , bag_pack('gain', 100, 'cycles', 4) // dictionary of parameters ) | render linechart ``` -------------------------------- ### Filter Datetime Values Using a Timespan Range Source: https://learn.microsoft.com/en-us/kusto/query/not-between-operator Filter records based on datetime values outside an inclusive range defined by a starting datetime and a timespan. This example counts events that did not occur within 3 days starting from July 27, 2007. ```Kusto StormEvents | where StartTime !between (datetime(2007-07-27) .. 3d) | count ``` -------------------------------- ### Example Retention Policy Output (Bash) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-management-commands This example shows the expected output format when retrieving a database's retention policy using the specified management command. ```bash -------------------- Command: .show database YourDatabase policy retention | project-away ChildEntities, EntityType Result: PolicyName - RetentionPolicy EntityName - [YourDatabase] Policy - { "SoftDeletePeriod": "365.00:00:00", "Recoverability": "Enabled" } ``` -------------------------------- ### Get 10 distinct values from a population Source: https://learn.microsoft.com/en-us/kusto/query/sample-distinct-operator This example shows how to retrieve a sample of 10 distinct EpisodeIds from the StormEvents table. The results are not guaranteed to be statistically representative. ```kusto StormEvents | sample-distinct 10 of EpisodeId ``` -------------------------------- ### Filter states not starting with 'P' (case-sensitive) Source: https://learn.microsoft.com/en-us/kusto/query/not-hasprefix-cs-operator Use !hasprefix_cs to filter out records where the 'State' column does not begin with the specified case-sensitive prefix. This example counts the remaining states. ```kusto StormEvents | summarize event_count=count() by State | where State !hasprefix_cs "P" | count ``` -------------------------------- ### Complete Kusto App Setup (Python) Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-hello-kusto A complete Python script demonstrating connection, query execution, and result printing using the Azure Kusto SDK. ```python 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 = "print Welcome='Hello Kusto!'" response = kusto_client.execute(database, query) print(response.primary_results[0][0]["Welcome"]) if __name__ == "__main__": main() ``` -------------------------------- ### Batch Ingest Example - C# Source: https://learn.microsoft.com/en-us/kusto/api/get-started/app-queued-ingestion An outline of a C# Main method demonstrating batch ingestion from a blob URI. It includes setting ingestion properties and calling IngestFromStorageAsync. ```csharp using Kusto.Data; using Kusto.Data.Net.Client; using Kusto.Data.Common; using Kusto.Ingest; using System.Data; namespace BatchIngest; class BatchIngest { static async Task Main() { string blobUri = ""; ... Console.WriteLine("\nIngesting data from memory:"); ingestProps.AdditionalProperties = new Dictionary() { { "ignoreFirstRecord", "True" } }; await ingestClient.IngestFromStorageAsync(blobUri, ingestProps); ... } static void PrintResultsAsValueList(IDataReader response) { ... } } ``` -------------------------------- ### Filter records using startswith operator Source: https://learn.microsoft.com/en-us/kusto/query/startswith-operator This example demonstrates how to filter records from the StormEvents table to find states that start with 'Lo'. It then further filters for event counts greater than 10. ```kql StormEvents | summarize event_count=count() by State | where State startswith "Lo" | where event_count > 10 | project State, event_count ```