次の方法で共有


MATLAB を使用してデータのクエリを実行する

MATLAB は、データの分析、アルゴリズムの開発、モデルの作成に使用されるプログラミングおよび数値コンピューティング プラットフォームです。 この記事では、MATLAB for Azure Data Explorerで承認トークンを取得する方法と、トークンを使用してクラスターと対話する方法について説明します。

前提条件

MATLAB の実行に使用するオペレーティング システムのタブを選択します。

  1. NuGet から Microsoft Identity Client パッケージと Microsoft Identity Abstractions パッケージをダウンロードします。

  2. ダウンロードしたパッケージと DLL ファイルを lib\net45 から任意のフォルダーに抽出します。 この記事では、 フォルダー C:\Matlab\DLL を使用します。

ユーザー認証を実行する

ユーザー認証を使用すると、ユーザーはブラウザー ウィンドウからサインインするように求められます。 サインインが成功すると、ユーザー承認トークンが付与されます。 このセクションでは、この対話型サインイン フローを構成する方法について説明します。

ユーザー認証を実行するには:

  1. 承認に必要な定数を定義します。 これらの値の詳細については、「 認証パラメーター」を参照してください。

    % The Azure Data Explorer cluster URL
    clusterUrl = 'https://<adx-cluster>.kusto.windows.net';
    % The Azure AD tenant ID
    tenantId = '';
    % Send a request to https://<adx-cluster>.kusto.windows.net/v1/rest/auth/metadata
    % The appId should be the value of KustoClientAppId
    appId = '';
    % The Azure AD scopes
    scopesToUse = strcat(clusterUrl,'/.default ');
    
  2. MATLAB Studio で、抽出された DLL ファイルを読み込みます。

    % Access the folder that contains the DLL files
    dllFolder = fullfile("C:","Matlab","DLL");
    
    % Load the referenced assemblies in the MATLAB session
    matlabDllFiles = dir(fullfile(dllFolder,'*.dll'));
    for k = 1:length(matlabDllFiles)
        baseFileName = matlabDllFiles(k).name;
        fullFileName = fullfile(dllFolder,baseFileName);
        fprintf(1, 'Reading  %s\n', fullFileName);
    end
        % Load the downloaded assembly in MATLAB
        NET.addAssembly(fullFileName);
    
  3. PublicClientApplicationBuilder を使用して、ユーザーの対話型サインインを求めます。

    % Create an PublicClientApplicationBuilder
    app = Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(appId)...
        .WithAuthority(Microsoft.Identity.Client.AzureCloudInstance.AzurePublic,tenantId)...
        .WithRedirectUri('http://localhost:8675')...
        .Build();
    
    % System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    NET.setStaticProperty ('System.Net.ServicePointManager.SecurityProtocol',System.Net.SecurityProtocolType.Tls12)
    % Start with creating a list of scopes
    scopes = NET.createGeneric('System.Collections.Generic.List',{'System.String'});
    % Add the actual scopes
    scopes.Add(scopesToUse);
    fprintf(1, 'Using appScope  %s\n', scopesToUse);
    
    % Get the token from the service
    % and show the interactive dialog in which the user can login
    tokenAcquirer = app.AcquireTokenInteractive(scopes);
    result = tokenAcquirer.ExecuteAsync;
    
    % Extract the token and when it expires
    % and retrieve the returned token
    token = char(result.Result.AccessToken);
    fprintf(2, 'User token aquired and will expire at %s & extended expires at %s', result.Result.ExpiresOn.LocalDateTime.ToString,result.Result.ExtendedExpiresOn.ToLocalTime.ToString);
    
  4. 承認トークンを使用して、 REST API を使用してクラスターに対してクエリを実行します。

    options=weboptions('HeaderFields',{'RequestMethod','POST';'Accept' 'application/json';'Authorization' ['Bearer ', token]; 'Content-Type' 'application/json; charset=utf-8'; 'Connection' 'Keep-Alive'; 'x-ms-app' 'Matlab'; 'x-ms-client-request-id' 'Matlab-Query-Request'});
    
    % The DB and KQL variables represent the database and query to execute
    querydata = struct('db', "<DB>", 'csl', "<KQL>");
    querryresults  = webwrite("https://sdktestcluster.westeurope.dev.kusto.windows.net/v2/rest/query", querydata, options);
    
    % Extract the results row
    results=querryresults{3}.Rows
    

アプリケーション認証を実行する

Microsoft Entraアプリケーションの承認は、対話型サインインが必要ではなく、自動実行が必要なシナリオに使用できます。

アプリケーション認証を実行するには:

  1. Microsoft Entra アプリケーションをプロビジョニングします。 [ リダイレクト URI] で、[ Web ] を選択し、URI として入力 http://localhost:8675 します。

  2. 承認に必要な定数を定義します。 これらの値の詳細については、「 認証パラメーター」を参照してください。

    % The Azure Data Explorer cluster URL
    clusterUrl = 'https://<adx-cluster>.kusto.windows.net';
    % The Azure AD tenant ID
    tenantId = '';
    % The Azure AD application ID and key
    appId = '';
    appSecret = '';
    
  3. MATLAB Studio で、抽出された DLL ファイルを読み込みます。

     % Access the folder that contains the DLL files
     dllFolder = fullfile("C:","Matlab","DLL");
    
     % Load the referenced assemblies in the MATLAB session
     matlabDllFiles = dir(fullfile(dllFolder,'*.dll'));
     for k = 1:length(matlabDllFiles)
         baseFileName = matlabDllFiles(k).name;
         fullFileName = fullfile(dllFolder,baseFileName);
         fprintf(1, 'Reading  %s\n', fullFileName);
     end
         % Load the downloaded assembly
         NET.addAssembly(fullFileName);
    
  4. ConfidentialClientApplicationBuilder を使用して、Microsoft Entra アプリケーションで非対話型の自動サインインを実行します。

    %  Create an ConfidentialClientApplicationBuilder
    app = Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.Create(appId)...
        .WithAuthority(Microsoft.Identity.Client.AzureCloudInstance.AzurePublic,tenantId)...
        .WithRedirectUri('http://localhost:8675')...
        .WithClientSecret(appSecret)...
        .Build();
    
    % System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    NET.setStaticProperty ('System.Net.ServicePointManager.SecurityProtocol',System.Net.SecurityProtocolType.Tls12)
    % Start with creating a list of scopes
    scopes = NET.createGeneric('System.Collections.Generic.List',{'System.String'});
    % Add the actual scopes
    scopes.Add(scopesToUse);
    fprintf(1, 'Using appScope  %s\n', scopesToUse);
    
    % Get the token from the service and cache it until it expires
    tokenAcquirer = app.AcquireTokenForClient(scopes);
    result = tokenAcquirer.ExecuteAsync;
    
    % Extract the token and when it expires
    % retrieve the returned token
    token = char(result.Result.AccessToken);
    fprintf(2, 'User token aquired and will expire at %s & extended expires at %s', result.Result.ExpiresOn.LocalDateTime.ToString,result.Result.ExtendedExpiresOn.ToLocalTime.ToString);
    
  5. 承認トークンを使用して、 REST API を使用してクラスターに対してクエリを実行します。

    options=weboptions('HeaderFields',{'RequestMethod','POST';'Accept' 'application/json';'Authorization' ['Bearer ', token]; 'Content-Type' 'application/json; charset=utf-8'; 'Connection' 'Keep-Alive'; 'x-ms-app' 'Matlab'; 'x-ms-client-request-id' 'Matlab-Query-Request'});
    
    % The DB and KQL variables represent the database and query to execute
    querydata = struct('db', "<DB>", 'csl', "<KQL>");
    querryresults  = webwrite("https://sdktestcluster.westeurope.dev.kusto.windows.net/v2/rest/query", querydata, options);
    
    % Extract the results row
    results=querryresults{3}.Rows
    
  • REST API を使用してクラスターにクエリを実行する