快速入门:使用客户端库或 REST API 自定义解决方案Quickstart: Use the client libraries or REST APIs to customize your solution

开始使用指标顾问 REST API 或客户端库。Get started with the the Metrics Advisor REST API or client libraries. 请按照以下步骤安装程序包并试用基本任务的示例代码。Follow these steps to install the package and try out the example code for basic tasks.

使用指标顾问执行以下操作:Use Metrics Advisor to perform:

  • 从数据源添加数据馈送Add a data feed from a data source
  • 检查引入状态Check ingestion status
  • 配置检测和警报Configure detection and alerts
  • 查询异常情况检测结果Query the anomaly detection results
  • 诊断异常Diagnose anomalies

参考文档 | 库源代码 | 包 (NuGet) | 示例Reference documentation | Library source code | Package (NuGet) | Samples

先决条件Prerequisites

提示

  • 可以在 GitHub 上找到 .NET 指标顾问示例。You can find .NET Metrics Advisor samples on GitHub.
  • 指标顾问资源可能需要 10 到 30 分钟才能部署一个服务实例供你使用。It may take 10 to 30 minutes for your Metrics Advisor resource to deploy a service instance for you to use. 部署成功后,单击“转到资源”。Click Go to resource once it successfully deploys. 部署完成后,可以通过 Web 门户和 REST API 这两种方式开始使用指标顾问实例。After deployment, you can start using your Metrics Advisor instance with both the web portal and REST API.
  • 可以在 Azure 门户的资源“概述”部分中找到 REST API 的 URL。You can find the URL for the REST API in Azure portal, in the Overview section of your resource. 它将如下所示:It will look like this:
    • https://<instance-name>.cognitiveservices.azure.cn/

设置Setting up

安装客户端库Install the client library

创建新项目后,右键单击“解决方案资源管理器”中的项目解决方案,然后选择“管理 NuGet 包”,以安装客户端库 。Once you've created a new project, install the client library by right-clicking on the project solution in the Solution Explorer and selecting Manage NuGet Packages. 在打开的包管理器中,选择“浏览”,选中“包括预发行版”并搜索 Azure.AI.MetricsAdvisorIn the package manager that opens select Browse, check Include prerelease, and search for Azure.AI.MetricsAdvisor. 选择版本 1.0.0-beta.2,然后选择“安装”。Select version 1.0.0-beta.2, and then Install.

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 metrics-advisor-quickstart 的新控制台应用。In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name metrics-advisor-quickstart. 此命令将创建包含单个源文件的简单“Hello World”C# 项目:program.csThis command creates a simple "Hello World" C# project with a single source file: program.cs.

dotnet new console -n metrics-advisor-quickstart

将目录更改为新创建的应用文件夹。Change your directory to the newly created app folder. 可使用以下代码生成应用程序:You can build the application with:

dotnet build

生成输出不应包含警告或错误。The build output should contain no warnings or errors.

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

安装客户端库Install the client library

如果你使用的 IDE 而不是 Visual Studio,则可通过以下命令安装适用于 .NET 的指标顾问客户端库:If you are using an IDE other than Visual Studio you can install the Metrics Advisor client library for .NET with the following command:

dotnet add package Azure.AI.MetricsAdvisor --version 1.0.0-beta.2

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

从项目目录中,打开 Program.cs 文件,并添加以下 using 指令:From the project directory, open the program.cs file and add the following using directives:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.AI.MetricsAdvisor.Administration;
using Azure.AI.MetricsAdvisor;
using Azure.AI.MetricsAdvisor.Models;

在应用程序的 Main() 方法中,添加对本快速入门中使用的方法的调用。In the application’s Main() method, add calls for the methods used in this quickstart. 稍后将创建这些内容。You will create these later.

static void Main(string[] args){
    // You will create the below methods later in the quickstart
    exampleTask1();
}

对象模型Object model

以下类处理指标顾问 C# SDK 的某些主要功能。The following classes handle some of the major features of the Metrics Advisor C# SDK.

名称Name 说明Description
MetricsAdvisorClientMetricsAdvisorClient 用途:Used for:
- 列出事件- Listing incidents
- 列出事件的根本原因- Listing root cause of incidents
- 检索原始时序数据和由服务丰富的时序数据。- Retrieving original time series data and time series data enriched by the service.
- 列出警报- Listing alerts
- 添加反馈以优化模型- Adding feedback to tune your model
MetricsAdvisorAdministrationClientMetricsAdvisorAdministrationClient 允许你:Allows you to:
- 管理数据馈送- Manage data feeds
- 配置异常情况检测配置- Configure anomaly detection configurations
- 配置异常情况警报配置- Configure anomaly alerting configurations
- 管理挂钩- Manage hooks
DataFeedDataFeed 指标顾问从数据源中引入的内容。DataFeed 包含以下行:What Metrics Advisor ingests from your datasource. A DataFeed contains rows of:
- 时间戳- Timestamps
- 零维度或多个维度- Zero or more dimensions
- 一个或多个度量值- One or more measures
DataFeedMetricDataFeedMetric DataFeedMetric 是用于监视和评估特定业务流程状态的可计量度量值。A DataFeedMetric is a quantifiable measure that is used to monitor and assess the status of a specific business process. 它可以是划分为多个维度的多个时序值的组合。It can be a combination of multiple time series values divided into dimensions. 例如,Web 运行状况指标可能包含用户数和 en-us 市场的维度 。For example a web health metric might contain dimensions for user count and the en-us market.

代码示例Code examples

这些代码片段展示如何借助适用于 .NET 的指标顾问客户端库执行以下操作:These code snippets show you how to do the following tasks with the Metrics Advisor client library for .NET:

验证客户端Authenticate the client

在应用程序的 Program 类中,为资源的密钥和终结点创建变量。In the application's Program class, create variables for your resource's keys and endpoint.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的指标顾问资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Metrics Advisor resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到订阅密钥和终结点 。You can find your subscription keys and endpoint in the resource's Key and Endpoint page, under Resource Management.

若要检索 API 密钥,必须转到 https://metricsadvisor.chinacloudsites.cnTo retrieve your API key you must go to https://metricsadvisor.chinacloudsites.cn. 为资源选择相应的“目录”、“订阅”和“工作区”,然后选择“入门” 。Select the appropriate: Directory, Subscriptions, and Workspace for your resource and choose Get started. 然后,你就能够从 https://metricsadvisor.chinacloudsites.cn/api-key 检索 API 密钥。You will then be able to retrieve your API keys from https://metricsadvisor.chinacloudsites.cn/api-key.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

获得订阅和 API 密钥后,请创建一个 MetricsAdvisorKeyCredential。Once you have the subscription and API keys, create a MetricsAdvisorKeyCredential. 借助终结点和密钥凭据,可以创建 MetricsAdvisorClientWith the endpoint and the key credential, you can create a MetricsAdvisorClient:

string endpoint = "<endpoint>";
string subscriptionKey = "<subscriptionKey>";
string apiKey = "<apiKey>";
var credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);
var client = new MetricsAdvisorClient(new Uri(endpoint), credential);

你还可创建 MetricsAdvisorAdministrationClient 来执行管理操作:You can also create a MetricsAdvisorAdministrationClient to perform administrative operations:

string endpoint = "<endpoint>";
string subscriptionKey = "<subscriptionKey>";
string apiKey = "<apiKey>";
var credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);
var adminClient = new MetricsAdvisorAdministrationClient(new Uri(endpoint), credential);

添加数据馈送Add a data feed

指标顾问支持多种类型的数据源。Metrics Advisor supports multiple types of data sources. 在此示例中,我们将演示如何创建一个从 SQL Server 提取数据的 DataFeedIn this sample we'll illustrate how to create a DataFeed that extracts data from a SQL server. connection_String 替换为你自己的 SQL Server 连接字符串,并将 query 替换为在单个时间戳返回数据的查询。Replace connection_String with your own SQL server connection string, and replace query with a query that returns your data at a single timestamp. 你还需要根据自定义数据调整 DataFeedMetricDataFeedDimension 值。You will also need to adjust the DataFeedMetric and DataFeedDimension values based on your custom data.

string sqlServerConnectionString = "<connection_String>";
string sqlServerQuery = "<query>";

var dataFeedName = "Sample data feed";
var dataFeedSource = new SqlServerDataFeedSource(sqlServerConnectionString, sqlServerQuery);
var dataFeedGranularity = new DataFeedGranularity(DataFeedGranularityType.Daily);

var dataFeedMetrics = new List<DataFeedMetric>()
{
    new DataFeedMetric("cost"),
    new DataFeedMetric("revenue")
};
var dataFeedDimensions = new List<DataFeedDimension>()
{
    new DataFeedDimension("category"),
    new DataFeedDimension("city")
};
var dataFeedSchema = new DataFeedSchema(dataFeedMetrics)
{
    DimensionColumns = dataFeedDimensions
};

var ingestionStartTime = DateTimeOffset.Parse("2020-01-01T00:00:00Z");
var dataFeedIngestionSettings = new DataFeedIngestionSettings(ingestionStartTime);

var dataFeed = new DataFeed(dataFeedName, dataFeedSource, dataFeedGranularity, dataFeedSchema, dataFeedIngestionSettings);

Response<string> response = await adminClient.CreateDataFeedAsync(dataFeed);

string dataFeedId = response.Value;

Console.WriteLine($"Data feed ID: {dataFeedId}");

// Note that only the ID of the data feed is known at this point. You can perform another
// service call to GetDataFeedAsync or GetDataFeed to get more information, such as status,
// created time, the list of administrators, or the metric IDs.

Response<DataFeed> response = await adminClient.GetDataFeedAsync(dataFeedId);

DataFeed dataFeed = response.Value;

Console.WriteLine($"Data feed status: {dataFeed.Status.Value}");
Console.WriteLine($"Data feed created time: {dataFeed.CreatedTime.Value}");

Console.WriteLine($"Data feed administrators:");
foreach (string admin in dataFeed.Administrators)
{
    Console.WriteLine($" - {admin}");
}

Console.WriteLine($"Metric IDs:");
foreach (DataFeedMetric metric in dataFeed.Schema.MetricColumns)
{
    Console.WriteLine($" - {metric.MetricName}: {metric.MetricId}");
}

检查引入状态Check the ingestion status

检查以前创建的 DataFeed 的引入状态Check the ingestion status of a previously created DataFeed

string dataFeedId = "<dataFeedId>";

var startTime = DateTimeOffset.Parse("2020-01-01T00:00:00Z");
var endTime = DateTimeOffset.Parse("2020-09-09T00:00:00Z");
var options = new GetDataFeedIngestionStatusesOptions(startTime, endTime)
{
    TopCount = 5
};

Console.WriteLine("Ingestion statuses:");
Console.WriteLine();

int statusCount = 0;

await foreach (DataFeedIngestionStatus ingestionStatus in adminClient.GetDataFeedIngestionStatusesAsync(dataFeedId, options))
{
    Console.WriteLine($"Timestamp: {ingestionStatus.Timestamp}");
    Console.WriteLine($"Status: {ingestionStatus.Status}");
    Console.WriteLine($"Service message: {ingestionStatus.Message}");
    Console.WriteLine();

    // Print at most 5 statuses.
    if (++statusCount >= 5)
    {
        break;
    }
}

配置异常情况检测Configure anomaly detection

创建异常情况检测配置,告诉服务应将哪些数据点视为异常。Create an anomaly detection configuration to tell the service which data points should be considered anomalies.

string metricId = "<metricId>";
string configurationName = "Sample anomaly detection configuration";

var hardThresholdSuppressCondition = new SuppressCondition(1, 100);
var hardThresholdCondition = new HardThresholdCondition(AnomalyDetectorDirection.Down, hardThresholdSuppressCondition)
{
    LowerBound = 5.0
};

var smartDetectionSuppressCondition = new SuppressCondition(4, 50);
var smartDetectionCondition = new SmartDetectionCondition(10.0, AnomalyDetectorDirection.Up, smartDetectionSuppressCondition);

var detectionCondition = new MetricWholeSeriesDetectionCondition()
{
    HardThresholdCondition = hardThresholdCondition,
    SmartDetectionCondition = smartDetectionCondition,
    CrossConditionsOperator = DetectionConditionsOperator.Or
};

var detectionConfiguration = new AnomalyDetectionConfiguration(metricId, configurationName, detectionCondition);

Response<string> response = await adminClient.CreateDetectionConfigurationAsync(detectionConfiguration);

string detectionConfigurationId = response.Value;

Console.WriteLine($"Anomaly detection configuration ID: {detectionConfigurationId}");

创建挂钩Create a hook

指标顾问支持 EmailNotificationHookWebNotificationHook 类作为警报通知的订阅方法。Metrics Advisor supports the EmailNotificationHook and WebNotificationHook classes as means of subscribing to alerts notifications. 在此示例中,我们将演示如何创建 EmailNotificationHookIn this example we'll illustrate how to create an EmailNotificationHook. 需要将挂钩传递到异常情况警报配置以开始获取通知。You need to pass the hook to an anomaly alert configuration to start getting notifications. 有关详细信息,请参阅创建异常情况警报配置这一示例。See the sample create an anomaly alert configuration for more information.

string hookName = "Sample hook";
var emailsToAlert = new List<string>()
{
    "email1@sample.com",
    "email2@sample.com"
};

var emailHook = new EmailNotificationHook(hookName, emailsToAlert);

Response<string> response = await adminClient.CreateHookAsync(emailHook);

string hookId = response.Value;

Console.WriteLine($"Hook ID: {hookId}");

创建警报配置Create an alert configuration

创建一个 AnomalyAlertConfiguration,告诉服务哪些异常会触发警报。Create an AnomalyAlertConfiguration to tell the service which anomalies should trigger alerts.

string hookId = "<hookId>";
string anomalyDetectionConfigurationId = "<anomalyDetectionConfigurationId>";

string configurationName = "Sample anomaly alert configuration";
var idsOfHooksToAlert = new List<string>() { hookId };

var scope = MetricAnomalyAlertScope.GetScopeForWholeSeries();
var metricAlertConfigurations = new List<MetricAnomalyAlertConfiguration>()
{
    new MetricAnomalyAlertConfiguration(anomalyDetectionConfigurationId, scope)
};

AnomalyAlertConfiguration alertConfiguration = new AnomalyAlertConfiguration(configurationName, idsOfHooksToAlert, metricAlertConfigurations);

Response<string> response = await adminClient.CreateAlertConfigurationAsync(alertConfiguration);

string alertConfigurationId = response.Value;

Console.WriteLine($"Alert configuration ID: {alertConfigurationId}");

查询警报Query the alert

查看由给定异常警报配置创建的警报。Look through the alerts created by a given anomaly alert configuration.

string anomalyAlertConfigurationId = "<anomalyAlertConfigurationId>";

var startTime = DateTimeOffset.Parse("2020-01-01T00:00:00Z");
var endTime = DateTimeOffset.UtcNow;
var options = new GetAlertsOptions(startTime, endTime, AlertQueryTimeMode.AnomalyTime)
{
    TopCount = 5
};

int alertCount = 0;

await foreach (AnomalyAlert alert in client.GetAlertsAsync(anomalyAlertConfigurationId, options))
{
    Console.WriteLine($"Alert created at: {alert.CreatedTime}");
    Console.WriteLine($"Alert at timestamp: {alert.Timestamp}");
    Console.WriteLine($"Id: {alert.Id}");
    Console.WriteLine();

    // Print at most 5 alerts.
    if (++alertCount >= 5)
    {
        break;
    }
}

知道警报的 ID 后,列出触发此警报的异常Once you know an alert's ID, list the anomalies that triggered this alert.

string alertConfigurationId = "<alertConfigurationId>";
string alertId = "<alertId>";

var options = new GetAnomaliesForAlertOptions() { TopCount = 3 };

int anomalyCount = 0;

await foreach (DataPointAnomaly anomaly in client.GetAnomaliesAsync(alertConfigurationId, alertId, options))
{
    Console.WriteLine($"Anomaly detection configuration ID: {anomaly.AnomalyDetectionConfigurationId}");
    Console.WriteLine($"Metric ID: {anomaly.MetricId}");
    Console.WriteLine($"Anomaly at timestamp: {anomaly.Timestamp}");
    Console.WriteLine($"Anomaly detected at: {anomaly.CreatedTime}");
    Console.WriteLine($"Status: {anomaly.Status}");
    Console.WriteLine($"Severity: {anomaly.Severity}");
    Console.WriteLine("Series key:");

    foreach (KeyValuePair<string, string> keyValuePair in anomaly.SeriesKey.AsDictionary())
    {
        Console.WriteLine($"  Dimension '{keyValuePair.Key}': {keyValuePair.Value}");
    }

    Console.WriteLine();

    // Print at most 3 anomalies.
    if (++anomalyCount >= 3)
    {
        break;
    }
}

运行应用程序Run the application

从应用程序目录使用 dotnet run 命令运行应用程序。Run the application from your application directory with the dotnet run command.

dotnet run

参考文档 | 库源代码 | 项目 (Maven) | 示例Reference documentation | Library source code | Artifact (Maven) | Samples

先决条件Prerequisites

提示

  • 可以在 GitHub 上找到 Java 指标顾问示例。You can find Java Metrics Advisor samples on GitHub.
  • 指标顾问资源可能需要 10 到 30 分钟才能部署一个服务实例供你使用。It may take 10 to 30 minutes for your Metrics Advisor resource to deploy a service instance for you to use. 部署成功后,单击“转到资源”。Click Go to resource once it successfully deploys. 部署完成后,可以通过 Web 门户和 REST API 这两种方式开始使用指标顾问实例。After deployment, you can start using your Metrics Advisor instance with both the web portal and REST API.
  • 可以在 Azure 门户的资源“概述”部分中找到 REST API 的 URL。You can find the URL for the REST API in Azure portal, in the Overview section of your resource. 它将如下所示:It will look like this:
    • https://<instance-name>.cognitiveservices.azure.cn/

设置Setting up

创建新的 Gradle 项目Create a new Gradle project

本快速入门使用 Gradle 依赖项管理器。This quickstart uses the Gradle dependency manager. 可在 Maven 中央存储库中找到有关客户端库的详细信息。You can find more client library information on the Maven Central Repository.

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

从工作目录运行 gradle init 命令。Run the gradle init command from your working directory. 此命令将创建 Gradle 的基本生成文件,包括 build.gradle.kts,在运行时将使用该文件创建并配置应用程序。This command will create essential build files for Gradle, including build.gradle.kts which is used at runtime to create and configure your application.

gradle init --type basic

当提示你选择一个 DSL 时,选择 KotlinWhen prompted to choose a DSL, select Kotlin.

安装客户端库Install the client library

找到 build.gradle.kts,并使用喜好的 IDE 或文本编辑器将其打开。Locate build.gradle.kts and open it with your preferred IDE or text editor. 然后将以下生成配置复制到其中。Then copy in this build configuration. 请确保包含项目依赖项。Be sure to include the project dependencies.

dependencies {
    compile("com.azure:azure-ai-metricsadvisor:1.0.0-beta.2")
}

创建 Java 文件Create a Java file

为示例应用创建一个文件夹。Create a folder for your sample app. 在工作目录中运行以下命令:From your working directory, run the following command:

mkdir -p src/main/java

导航到新文件夹,并创建名为 MetricsAdvisorQuickstarts.java 的文件。Navigate to the new folder and create a file called MetricsAdvisorQuickstarts.java. 在喜好的编辑器或 IDE 中打开该文件并添加以下 import 语句:Open it in your preferred editor or IDE and add the following import statements:

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

在应用程序的 MetricsAdvisorQuickstarts 类中,为资源的密钥和终结点创建变量。In the application's MetricsAdvisorQuickstarts class, create variables for your resource's key and endpoint.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的指标顾问资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Metrics Advisor resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到订阅密钥和终结点 。You can find your subscription keys and endpoint in the resource's Key and Endpoint page, under Resource Management.

若要检索 API 密钥,必须转到 https://metricsadvisor.chinacloudsites.cnTo retrieve your API key you must go to https://metricsadvisor.chinacloudsites.cn. 为资源选择相应的“目录”、“订阅”和“工作区”,然后选择“入门” 。Select the appropriate: Directory, Subscriptions, and Workspace for your resource and choose Get started. 然后,你就能够从 https://metricsadvisor.chinacloudsites.cn/api-key 检索 API 密钥。You will then be able to retrieve your API keys from https://metricsadvisor.chinacloudsites.cn/api-key.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

private static String SUBSCRIPTION_KEY = "<replace-with-your-metrics-advisor-subscription-key-here>";
private static String API_KEY = "<replace-with-your-metrics-advisor-api-key-here>"
private static String ENDPOINT = "<replace-with-your-metrics-advisor-endpoint-here>";

在应用程序的 Main() 方法中,添加对本快速入门中使用的方法的调用。In the application’s Main() method, add calls for the methods used in this quickstart. 稍后将创建这些内容。You’ll create these later.

static void Main(string[] args){

    // You will create the below methods later in the quickstart
    exampleTask1();
}

对象模型Object model

以下类处理指标顾问 Java SDK 的某些主要功能。The following classes handle some of the major features of the Metrics Advisor Java SDK.

名称Name 说明Description
MetricsAdvisorClientMetricsAdvisorClient 用途:Used for:
- 列出异常事件- Listing anomaly incidents
- 列出事件的根本原因- Listing root cause of incidents
- 检索原始时序数据和由服务丰富的时序数据。- Retrieving original time series data and time series data enriched by the service.
- 列出警报- Listing alerts
- 添加反馈以优化模型- Adding feedback to tune your model
MetricsAdvisorAdministrationClientMetricsAdvisorAdministrationClient 允许你:Allows you to:
- 管理数据馈送- Manage data feeds
- 配置异常情况检测配置- Configure anomaly detection configurations
- 配置异常情况警报配置- Configure anomaly alerting configurations
- 管理挂钩- Manage hooks
DataFeedDataFeed 指标顾问从数据源中引入的内容。DataFeed 包含以下行:What Metrics Advisor ingests from your datasource. A DataFeed contains rows of:
- 时间戳- Timestamps
- 零维度或多个维度- Zero or more dimensions
- 一个或多个度量值- One or more measures
DataFeedMetricDataFeedMetric DataFeedMetric 是用于监视和评估特定业务流程状态的可计量度量值。A DataFeedMetric is a quantifiable measure that is used to monitor and assess the status of a specific business process. 它可以是划分为多个维度的多个时序值的组合。It can be a combination of multiple time series values divided into dimensions. 例如,Web 运行状况指标可能包含用户数和 en-us 市场的维度 。For example a web health metric might contain dimensions for user count and the en-us market.

代码示例Code examples

这些代码片段展示如何借助适用于 Java 的指标顾问客户端库执行以下操作:These code snippets show you how to do the following tasks with the Metrics Advisor client library for Java:

验证客户端Authenticate the client

使用 MetricsAdvisorKeyCredential 创建指标顾问客户端Create a Metrics Advisor client using MetricsAdvisorKeyCredential

MetricsAdvisorKeyCredential credential = new MetricsAdvisorKeyCredential(SUBSCRIPTION_KEY, API_KEY);
MetricsAdvisorClient metricsAdvisorClient = new MetricsAdvisorClientBuilder()
    .endpoint(ENDPOINT)
    .credential(credential)
    .buildClient();

使用 MetricsAdvisorKeyCredential 创建指标管理客户端Create a Metrics Administration client using MetricsAdvisorKeyCredential

MetricsAdvisorKeyCredential credential = new MetricsAdvisorKeyCredential(SUBSCRIPTION_KEY, API_KEY);
MetricsAdvisorAdministrationClient metricsAdvisorAdministrationClient =
    new MetricsAdvisorAdministrationClientBuilder()
        .endpoint(ENDPOINT)
        .credential(credential)
        .buildClient();

添加数据馈送Add a data feed

sql_server_connection_string 替换为你自己的 SQL Server 连接字符串,并将 query 替换为在单个时间戳返回数据的查询。Replace sql_server_connection_string with your own SQL server connection string, and replace query with a query that returns your data at a single timestamp. 你还需要根据自定义数据调整 DataFeedMetricDataFeedDimension 值。You will also need to adjust the DataFeedMetric and DataFeedDimension values based on your custom data.

重要

对于每个维度组合,查询应在每个时间戳处最多返回一条记录。The query should return at most one record for each dimension combination, at each timestamp. 查询返回的所有记录必须具有相同的时间戳。And all records returned by the query must have the same timestamps. 指标顾问将针对每个时间戳运行此查询以引入数据。Metrics Advisor will run this query for each timestamp to ingest your data. 有关详细信息和示例,请参阅查询常见问题解答部分See the FAQ section on queries for more information, and examples.

DataFeed dataFeed = new DataFeed()
    .setName("dataFeedName")
    .setSource(new MySqlDataFeedSource("sql_server_connection_string", "query"))
    .setGranularity(new DataFeedGranularity().setGranularityType(DataFeedGranularityType.DAILY))
    .setSchema(new DataFeedSchema(
        Arrays.asList(
            new DataFeedMetric().setName("cost"),
            new DataFeedMetric().setName("revenue")
        )).setDimensions(
        Arrays.asList(
            new DataFeedDimension().setName("city"),
            new DataFeedDimension().setName("category")
        ))
    )
    .setIngestionSettings(new DataFeedIngestionSettings(OffsetDateTime.parse("2020-01-01T00:00:00Z")))
    .setOptions(new DataFeedOptions()
        .setDescription("data feed description")
        .setRollupSettings(new DataFeedRollupSettings()
            .setRollupType(DataFeedRollupType.AUTO_ROLLUP)));
final DataFeed createdSqlDataFeed = metricsAdvisorAdminClient.createDataFeed(dataFeed);

System.out.printf("Data feed Id : %s%n", createdSqlDataFeed.getId());
System.out.printf("Data feed name : %s%n", createdSqlDataFeed.getName());
System.out.printf("Is the query user is one of data feed administrator : %s%n", createdSqlDataFeed.isAdmin());
System.out.printf("Data feed created time : %s%n", createdSqlDataFeed.getCreatedTime());
System.out.printf("Data feed granularity type : %s%n",
    createdSqlDataFeed.getGranularity().getGranularityType());
System.out.printf("Data feed granularity value : %d%n",
    createdSqlDataFeed.getGranularity().getCustomGranularityValue());
System.out.println("Data feed related metric Ids:");
createdSqlDataFeed.getMetricIds().forEach(System.out::println);
System.out.printf("Data feed source type: %s%n", createdSqlDataFeed.getSourceType());

if (SQL_SERVER_DB == createdSqlDataFeed.getSourceType()) {
    System.out.printf("Data feed sql server query: %s%n",
        ((SQLServerDataFeedSource) createdSqlDataFeed.getSource()).getQuery());
}

检查引入状态Check the ingestion status

此示例检查以前提供的数据馈送源的引入状态。This example checks the ingestion status of a previously provided data feed source.

String dataFeedId = "<use-the-data-feed-id-from-createdSqlDataFeed.getId()"; 

metricsAdvisorAdminClient.listDataFeedIngestionStatus(
    dataFeedId,
    new ListDataFeedIngestionOptions(
        OffsetDateTime.parse("2020-01-01T00:00:00Z"),
        OffsetDateTime.parse("2020-09-09T00:00:00Z"))
).forEach(dataFeedIngestionStatus -> {
    System.out.printf("Message : %s%n", dataFeedIngestionStatus.getMessage());
    System.out.printf("Timestamp value : %s%n", dataFeedIngestionStatus.getTimestamp());
    System.out.printf("Status : %s%n", dataFeedIngestionStatus.getStatus());
});

配置异常情况检测Configure anomaly detection

此示例演示用户如何为其数据配置异常情况检测配置。This example demonstrates how a user can configure an anomaly detection configuration for their data.

String metricId = "<metric-id-from-adding-data-feed>";

ChangeThresholdCondition changeThresholdCondition = new ChangeThresholdCondition()
    .setAnomalyDetectorDirection(AnomalyDetectorDirection.BOTH)
    .setChangePercentage(20)
    .setShiftPoint(10)
    .setWithinRange(true)
    .setSuppressCondition(new SuppressCondition().setMinNumber(1).setMinRatio(2));

HardThresholdCondition hardThresholdCondition = new HardThresholdCondition()
    .setAnomalyDetectorDirection(AnomalyDetectorDirection.DOWN)
    .setLowerBound(5.0)
    .setSuppressCondition(new SuppressCondition().setMinNumber(1).setMinRatio(1));

SmartDetectionCondition smartDetectionCondition = new SmartDetectionCondition()
    .setAnomalyDetectorDirection(AnomalyDetectorDirection.UP)
    .setSensitivity(10.0)
    .setSuppressCondition(new SuppressCondition().setMinNumber(1).setMinRatio(2));

final AnomalyDetectionConfiguration anomalyDetectionConfiguration =
    metricsAdvisorAdminClient.createMetricAnomalyDetectionConfig(
        metricId,
        new AnomalyDetectionConfiguration("My dataPoint anomaly detection configuration")
            .setDescription("anomaly detection config description")
            .setWholeSeriesDetectionCondition(
                new MetricWholeSeriesDetectionCondition()
                    .setChangeThresholdCondition(changeThresholdCondition)
                    .setHardThresholdCondition(hardThresholdCondition)
                    .setSmartDetectionCondition(smartDetectionCondition)
                    .setCrossConditionOperator(DetectionConditionsOperator.OR))
    );

创建挂钩Create a hook

此示例创建一个接收异常事件警报的电子邮件挂钩。This example creates an email hook that receives anomaly incident alerts.

NotificationHook emailNotificationHook = new EmailNotificationHook("email Hook")
    .setDescription("my email Hook")
    .addEmailToAlert("alertme@alertme.com")
    .setExternalLink("https://example.com/handleAlerts"); // you must enter a valid webhook url to post the alert payload

final NotificationHook notificationHook = metricsAdvisorAdminClient.createHook(emailNotificationHook);
EmailNotificationHook createdEmailHook = (EmailNotificationHook) notificationHook;
System.out.printf("Email Hook Id: %s%n", createdEmailHook.getId());
System.out.printf("Email Hook name: %s%n", createdEmailHook.getName());
System.out.printf("Email Hook description: %s%n", createdEmailHook.getDescription());
System.out.printf("Email Hook external Link: %s%n", createdEmailHook.getExternalLink());
System.out.printf("Email Hook emails to alert: %s%n",
    String.join(",", createdEmailHook.getEmailsToAlert()));

创建警报配置Create an alert configuration

此示例演示用户如何为其数据中检测到的异常配置警报配置。This example demonstrates how a user can configure an alerting configuration for detected anomalies in their data.

String detectionConfigurationId1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
String detectionConfigurationId2 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
String hookId1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
String hookId2 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

final AnomalyAlertConfiguration anomalyAlertConfiguration
    = metricsAdvisorAdminClient.createAnomalyAlertConfig(
        new AnomalyAlertConfiguration("My anomaly alert config name")
            .setDescription("alert config description")
            .setMetricAlertConfigurations(
                Arrays.asList(
                    new MetricAnomalyAlertConfiguration(detectionConfigurationId1,
                        MetricAnomalyAlertScope.forWholeSeries()),
                    new MetricAnomalyAlertConfiguration(detectionConfigurationId2,
                        MetricAnomalyAlertScope.forWholeSeries())
                        .setAlertConditions(new MetricAnomalyAlertConditions()
                            .setSeverityRangeCondition(new SeverityCondition()
                                .setMaxAlertSeverity(AnomalySeverity.HIGH)))
                ))
            .setCrossMetricsOperator(MetricAnomalyAlertConfigurationsOperator.AND)
            .setIdOfHooksToAlert(Arrays.asList(hookId1, hookId2)));

查询警报Query the alert

此示例演示用户如何查询警报检测配置触发的警报,并获取该警报的异常。This example demonstrates how a user can query alerts triggered for an alert detection configuration and get anomalies for that alert.

String alertConfigurationId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
final OffsetDateTime startTime = OffsetDateTime.parse("2020-01-01T00:00:00Z");
final OffsetDateTime endTime = OffsetDateTime.parse("2020-09-09T00:00:00Z");
metricsAdvisorClient.listAlerts(
    alertConfigurationId,
        startTime, endTime)
    .forEach(alert -> {
        System.out.printf("AnomalyAlert Id: %s%n", alert.getId());
        System.out.printf("AnomalyAlert created on: %s%n", alert.getCreatedTime());

        // List anomalies for returned alerts
        metricsAdvisorClient.listAnomaliesForAlert(
            alertConfigurationId,
            alert.getId())
            .forEach(anomaly -> {
                System.out.printf("DataPoint Anomaly was created on: %s%n", anomaly.getCreatedTime());
                System.out.printf("DataPoint Anomaly severity: %s%n", anomaly.getSeverity().toString());
                System.out.printf("DataPoint Anomaly status: %s%n", anomaly.getStatus());
                System.out.printf("DataPoint Anomaly related series key: %s%n", anomaly.getSeriesKey().asMap());
            });
    });

可使用以下命令生成应用:You can build the app with:

gradle build

运行应用程序Run the application

使用 run 目标运行应用程序:Run the application with the run goal:

gradle run

库源代码 | 包 (npm) | 示例Library source code | Package (npm) | Samples

先决条件Prerequisites

提示

  • 可以在 GitHub 上找到 JavaScript 指标顾问示例。You can find JavaScript Metrics Advisor samples on GitHub.
  • 指标顾问资源可能需要 10 到 30 分钟才能部署一个服务实例供你使用。It may take 10 to 30 minutes for your Metrics Advisor resource to deploy a service instance for you to use. 部署成功后,单击“转到资源”。Click Go to resource once it successfully deploys. 部署完成后,可以通过 Web 门户和 REST API 这两种方式开始使用指标顾问实例。After deployment, you can start using your Metrics Advisor instance with both the web portal and REST API.
  • 可以在 Azure 门户的资源“概述”部分中找到 REST API 的 URL。You can find the URL for the REST API in Azure portal, in the Overview section of your resource. 它将如下所示:It will look like this:
    • https://<instance-name>.cognitiveservices.azure.cn/

设置Setting up

创建新的 Node.js 应用程序Create a new Node.js application

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

运行 npm init 命令以使用 package.json 文件创建一个 node 应用程序。Run the npm init command to create a node application with a package.json file.

npm init

安装客户端库Install the client library

安装 @azure/ai-metrics-advisor NPM 包:Install the @azure/ai-metrics-advisor NPM package:

npm install @azure/ai-metrics-advisor@1.0.0-beta.2

应用的 package.json 文件将使用依赖项进行更新。Your app's package.json file will be updated with the dependencies.

创建一个名为 index.js 的文件,并导入以下库:Create a file named index.js and import the following libraries:

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

为资源的 Azure 终结点和密钥创建变量。Create variables for your resource's Azure endpoint and key.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的指标顾问资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Metrics Advisor resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到订阅密钥和终结点 。You can find your subscription keys and endpoint in the resource's Key and Endpoint page, under Resource Management.

若要检索 API 密钥,必须转到 https://metricsadvisor.chinacloudsites.cnTo retrieve your API key you must go to https://metricsadvisor.chinacloudsites.cn. 为资源选择相应的“目录”、“订阅”和“工作区”,然后选择“入门” 。Select the appropriate: Directory, Subscriptions, and Workspace for your resource and choose Get started. 然后,你就能够从 https://metricsadvisor.chinacloudsites.cn/api-key 检索 API 密钥。You will then be able to retrieve your API keys from https://metricsadvisor.chinacloudsites.cn/api-key.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

subscriptionKey = "<paste-your-metrics-advisor-key-here>";
apiKey ="<paste-your-metrics-advisor-api-key-here>";
endpoint = "<paste-your-metrics-advisor-endpoint-here>";

对象模型Object model

以下类和接口处理指标顾问 JavaScript SDK 的某些主要功能。The following classes and interfaces handle some of the major features of the Metrics Advisor JavaScript SDK.

名称Name 说明Description
MetricsAdvisorClientMetricsAdvisorClient 用途:Used for:
- 列出事件- Listing incidents
- 列出事件的根本原因- Listing root cause of incidents
- 检索原始时序数据和由服务丰富的时序数据。- Retrieving original time series data and time series data enriched by the service.
- 列出警报- Listing alerts
- 添加反馈以优化模型- Adding feedback to tune your model
MetricsAdvisorAdministrationClientMetricsAdvisorAdministrationClient 允许你:Allows you to:
- 管理数据馈送- Manage data feeds
- 创建、配置、检索、列出和删除异常情况警报配置- Create, configure, retrieve, list, and delete anomaly alerting configurations
- 管理挂钩- Manage hooks
DataFeedDataFeed 指标顾问从数据源中引入的内容。DataFeed 包含以下行:What Metrics Advisor ingests from your datasource. A DataFeed contains rows of:
- 时间戳- Timestamps
- 零维度或多个维度- Zero or more dimensions
- 一个或多个度量值- One or more measures
DataFeedMetricDataFeedMetric DataFeedMetric 是用于监视和评估特定业务流程状态的可计量度量值。A DataFeedMetric is a quantifiable measure that is used to monitor and assess the status of a specific business process. 它可以是划分为多个维度的多个时序值的组合。It can be a combination of multiple time series values divided into dimensions. 例如,Web 运行状况指标可能包含用户数和 en-us 市场的维度 。For example a web health metric might contain dimensions for user count and the en-us market.

代码示例Code examples

这些代码片段展示如何借助适用于 JavaScript 的指标顾问客户端库执行以下操作:These code snippets show you how to do the following with the Metrics Advisor client library for JavaScript:

验证客户端Authenticate the client

拥有两个密钥和终结点地址后,可以使用 MetricsAdvisorKeyCredential 类对客户端进行身份验证,如下所示:Once you have the two keys and endpoint address, you can use the MetricsAdvisorKeyCredential class to authenticate the clients as follows:

const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorClient,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);
const client = new MetricsAdvisorClient(endpoint, credential);
const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);

添加数据馈送Add a data feed

指标顾问支持连接不同类型的数据源。Metrics Advisor supports connecting different types of data sources. 下面是从 SQL Server 引入数据的示例。Here is a sample to ingest data from SQL Server.

sql_server_connection_string 替换为你自己的 SQL Server 连接字符串,并将 query 替换为在单个时间戳返回数据的查询。Replace sql_server_connection_string with your own SQL server connection string, and replace query with a query that returns your data at a single timestamp. 你还需要根据自定义数据调整 metricdimension 值。You will also need to adjust the metric and dimension values based on your custom data.

重要

对于每个维度组合,查询应在每个时间戳处最多返回一条记录。The query should return at most one record for each dimension combination, at each timestamp. 查询返回的所有记录必须具有相同的时间戳。And all records returned by the query must have the same timestamps. 指标顾问将针对每个时间戳运行此查询以引入数据。Metrics Advisor will run this query for each timestamp to ingest your data. 有关详细信息和示例,请参阅查询常见问题解答部分See the FAQ section on queries for more information, and examples.

const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

async function main() {
  subscriptionKey = "<paste-your-metrics-advisor-key-here>";
  apiKey ="<paste-your-metrics-advisor-api-key-here>";
  endpoint = "<paste-your-metrics-advisor-endpoint-here>";
  const sqlServerConnectionString ="<sql_server_connection_string>";
  const sqlServerQuery ="<query>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);

  const created = await createDataFeed(adminClient, sqlServerConnectionString, sqlServerQuery);
  console.log(`Data feed created: ${created.id}`);
}

async function createDataFeed(adminClient, sqlServerConnectionString, sqlServerQuery) {
  console.log("Creating Datafeed...");
  const dataFeed = {
    name: "test_datafeed_" + new Date().getTime().toString(),
    source: {
      dataSourceType: "SqlServer",
      dataSourceParameter: {
        connectionString: sqlServerConnectionString,
        query: sqlServerQuery
      }
    },
    granularity: {
      granularityType: "Daily"
    },
    schema: {
      metrics: [
        {
          name: "revenue",
          displayName: "revenue",
          description: "Metric1 description"
        },
        {
          name: "cost",
          displayName: "cost",
          description: "Metric2 description"
        }
      ],
      dimensions: [
        { name: "city", displayName: "city display" },
        { name: "category", displayName: "category display" }
      ],
      timestampColumn: null
    },
    ingestionSettings: {
      ingestionStartTime: new Date(Date.UTC(2020, 5, 1)),
      ingestionStartOffsetInSeconds: 0,
      dataSourceRequestConcurrency: -1,
      ingestionRetryDelayInSeconds: -1,
      stopRetryAfterInSeconds: -1
    },
    rollupSettings: {
      rollupType: "AutoRollup",
      rollupMethod: "Sum",
      rollupIdentificationValue: "__CUSTOM_SUM__"
    },
    missingDataPointFillSettings: {
      fillType: "SmartFilling"
    },
    accessMode: "Private",
    adminEmails: ["xyz@example.com"]
  };
  const result = await adminClient.createDataFeed(dataFeed);

  return result;
}

检查引入状态Check ingestion status

开始数据引入后,我们可以检查引入状态。After we start the data ingestion, we can check the ingestion status.

const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

async function main() {
  // You will need to set these environment variables or edit the following values
  const endpoint = "<service endpoint>";
  const subscriptionKey = "<subscription key>";
  const apiKey = "<api key>";
  const dataFeedId = "<data feed id>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);
  await checkIngestionStatus(
    adminClient,
    dataFeedId,
    new Date(Date.UTC(2020, 8, 1)),
    new Date(Date.UTC(2020, 8, 12))
  );
}

async function checkIngestionStatus(adminClient, datafeedId, startTime, endTime) {
  // This shows how to use for-await-of syntax to list status
  console.log("Checking ingestion status...");
  const iterator = adminClient.listDataFeedIngestionStatus(datafeedId, startTime, endTime);
  for await (const status of iterator) {
    console.log(`  [${status.timestamp}] ${status.status} - ${status.message}`);
  }
}

配置异常情况检测Configure anomaly detection

我们需要异常情况检测配置来确定时序中的某个点是否异常。We need an anomaly detection configuration to determine whether a point in the time series is an anomaly. 虽然默认检测配置会自动应用于每个指标,但你可以创建自定义的异常情况检测配置来调整对数据使用的检测模式。While a default detection configuration is automatically applied to each metric, you can tune the detection modes used on your data by creating a customized anomaly detection configuration.

const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

async function main() {
  const endpoint = "<service endpoint>";
  const subscriptionKey = "<subscription key>";
  const apiKey = "<api key>";
  const metricId =  "<metric id>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);

  const detectionConfig = await configureAnomalyDetectionConfiguration(adminClient, metricId);
  console.log(`Detection configuration created: ${detectionConfig.id}`);
}

async function configureAnomalyDetectionConfiguration(adminClient, metricId) {
  console.log(`Creating an anomaly detection configuration on metric '${metricId}'...`);
  const detectionConfig = {
    name: "test_detection_configuration" + new Date().getTime().toString(),
    metricId,
    wholeSeriesDetectionCondition: {
      smartDetectionCondition: {
        sensitivity: 100,
        anomalyDetectorDirection: "Both",
        suppressCondition: {
          minNumber: 1,
          minRatio: 1
        }
      }
    },
    description: "Detection configuration description"
  };
  return await adminClient.createDetectionConfig(detectionConfig);
}

创建挂钩Create a hook

我们使用挂钩来订阅实时警报。We use hooks to subscribe to real-time alerts. 在此示例中,我们为指标顾问服务创建一个 Webhook,以将警报 POST 到该服务。In this example, we create a webhook for the Metrics Advisor service to POST the alert to.


const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

async function main() {
  // You will need to set these environment variables or edit the following values
  const endpoint = "<service endpoint>";
  const subscriptionKey = "<subscription key>";
  const apiKey = "<api key>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);
  const hook = await createWebhookHook(adminClient);
  console.log(`Webhook hook created: ${hook.id}`);
}

async function createWebhookHook(adminClient) {
  console.log("Creating a webhook hook");
  const hook = {
    hookType: "Webhook",
    name: "web hook " + new Date().getTime().toFixed(),
    description: "description",
    hookParameter: {
      endpoint: "https://example.com/handleAlerts", // you must enter a valid webhook url to post the alert payload
      username: "username",
      password: "password"
      // certificateKey: "certificate key",
      // certificatePassword: "certificate password"
    }
  };

  return await adminClient.createHook(hook);
}

创建警报配置Create an alert configuration

此示例将演示如何配置需要触发警报的条件,以及要使用哪些挂钩作为警报的目标。This sample will show you how to configure conditions an alert needs to be triggered and which hooks to use as a destination for an alert.

const {
  MetricsAdvisorKeyCredential,
  MetricsAdvisorAdministrationClient
} = require("@azure/ai-metrics-advisor");

async function main() {
  // You will need to set these environment variables or edit the following values
  const endpoint = "<service endpoint>";
  const subscriptionKey = "<subscription key>";
  const apiKey = "<api key>";
  const detectionConfigId = "<detection id>";
  const hookId = "<hook id>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const adminClient = new MetricsAdvisorAdministrationClient(endpoint, credential);
  const alertConfig = await configureAlertConfiguration(adminClient, detectionConfigId, [hookId]);
  console.log(`Alert configuration created: ${alertConfig.id}`);
}

async function configureAlertConfiguration(adminClient, detectionConfigId, hookIds) {
  console.log("Creating a new alerting configuration...");
  const anomalyAlertConfig = {
    name: "test_alert_config_" + new Date().getTime().toString(),
    crossMetricsOperator: "AND",
    metricAlertConfigurations: [
      {
        detectionConfigurationId: detectionConfigId,
        alertScope: {
          scopeType: "All"
        },
        alertConditions: {
          severityCondition: { minAlertSeverity: "Medium", maxAlertSeverity: "High" }
        },
        snoozeCondition: {
          autoSnooze: 0,
          snoozeScope: "Metric",
          onlyForSuccessive: true
        }
      }
    ],
    hookIds,
    description: "Alerting config description"
  };
  return await adminClient.createAlertConfig(anomalyAlertConfig);
}

查询警报Query the alert

const { MetricsAdvisorKeyCredential, MetricsAdvisorClient } = require("@azure/ai-metrics-advisor");

async function main() {
  // You will need to set these environment variables or edit the following values
  const endpoint = "<service endpoint>";
  const subscriptionKey = "<subscription key>";
  const apiKey = "<api key>";
  const alertConfigId = "<alert config id>";
  const credential = new MetricsAdvisorKeyCredential(subscriptionKey, apiKey);

  const client = new MetricsAdvisorClient(endpoint, credential);

  const alertIds = await queryAlerts(
    client,
    alertConfigId,
    new Date(Date.UTC(2020, 8, 1)),
    new Date(Date.UTC(2020, 8, 12))
  );

  if (alertIds.length > 1) {
    // query anomalies using an alert id.
    await queryAnomaliesByAlert(client, alertConfigId, alertIds[0]);
  } else {
    console.log("No alerts during the time period");
  }
}

async function queryAlerts(client, alertConfigId, startTime, endTime) {
  let alerts = [];
  const iterator = client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime");
  for await (const alert of iterator) {
    alerts.push(alert);
  }

  return alerts;
}

async function queryAnomaliesByAlert(client, alert) {
  console.log(
    `Listing anomalies for alert configuration '${alert.alertConfigId}' and alert '${alert.id}'`
  );
  const iterator = client.listAnomalies(alert);
  for await (const anomaly of iterator) {
    console.log(
      `  Anomaly ${anomaly.severity} ${anomaly.status} ${anomaly.seriesKey.dimension} ${anomaly.timestamp}`
    );
  }
}

运行应用程序Run the application

在快速入门文件中使用 node 命令运行应用程序。Run the application with the node command on your quickstart file.

node index.js

参考文档 | 库源代码 | 包 (PiPy) | 示例Reference documentation | Library source code | Package (PiPy) | Samples

先决条件Prerequisites

提示

  • 可以在 GitHub 上找到 Python 指标顾问示例。You can find Python Metrics Advisor samples on GitHub.
  • 指标顾问资源可能需要 10 到 30 分钟才能部署一个服务实例供你使用。It may take 10 to 30 minutes for your Metrics Advisor resource to deploy a service instance for you to use. 部署成功后,单击“转到资源”。Click Go to resource once it successfully deploys. 部署完成后,可以通过 Web 门户和 REST API 这两种方式开始使用指标顾问实例。After deployment, you can start using your Metrics Advisor instance with both the web portal and REST API.
  • 可以在 Azure 门户的资源“概述”部分中找到 REST API 的 URL。You can find the URL for the REST API in Azure portal, in the Overview section of your resource. 它将如下所示:It will look like this:
    • https://<instance-name>.cognitiveservices.azure.cn/

设置Setting up

安装客户端库Install the client library

在安装 Python 后,可以通过以下命令安装客户端库:After installing Python, you can install the client library with:

pip install azure-ai-metricsadvisor --pre

创建新的 Python 应用程序Create a new python application

创建新的 Python 文件并导入以下库。Create a new Python file and import the following libraries.

import os
import datetime

为资源的 Azure 终结点和密钥创建变量。Create variables for your resource's Azure endpoint and key.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的指标顾问资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Metrics Advisor resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到订阅密钥和终结点 。You can find your subscription keys and endpoint in the resource's Key and Endpoint page, under Resource Management.

若要检索 API 密钥,必须转到 https://metricsadvisor.chinacloudsites.cnTo retrieve your API key you must go to https://metricsadvisor.chinacloudsites.cn. 为资源选择相应的“目录”、“订阅”和“工作区”,然后选择“入门” 。Select the appropriate: Directory, Subscriptions, and Workspace for your resource and choose Get started. 然后,你就能够从 https://metricsadvisor.chinacloudsites.cn/api-key 检索 API 密钥。You will then be able to retrieve your API keys from https://metricsadvisor.chinacloudsites.cn/api-key.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

subscription_key = "<paste-your-metrics-advisor-subscription-key-here>"
api_key = "<paste-your-metrics-advisor-api-key-here>"
service_endpoint = "<paste-your-metrics-advisor-endpoint-here>"

对象模型Object model

以下类处理指标顾问 Python SDK 的某些主要功能。The following classes handle some of the major features of the Metrics Advisor Python SDK.

名称Name 说明Description
MetricsAdvisorClientMetricsAdvisorClient 用途:Used for:
- 列出事件- Listing incidents
- 列出事件的根本原因- Listing root cause of incidents
- 检索原始时序数据和由服务丰富的时序数据。- Retrieving original time series data and time series data enriched by the service.
- 列出警报- Listing alerts
- 添加反馈以优化模型- Adding feedback to tune your model
MetricsAdvisorAdministrationClientMetricsAdvisorAdministrationClient 允许你:Allows you to:
- 管理数据馈送- Manage data feeds
- 创建、配置、检索、列出和删除异常情况检测配置- Create, configure, retrieve, list, and delete anomaly detection configurations
- 创建、配置、检索、列出和删除异常情况警报配置- Create, configure, retrieve, list, and delete anomaly alerting configurations
- 管理挂钩- Manage hooks
DataFeedDataFeed 指标顾问从数据源中引入的内容。DataFeed 包含以下行:What Metrics Advisor ingests from your datasource. A DataFeed contains rows of:
- 时间戳- Timestamps
- 零维度或多个维度- Zero or more dimensions
- 一个或多个度量值- One or more measures
DataFeedMetricDataFeedMetric DataFeedMetric 是用于监视和评估特定业务流程状态的可计量度量值。A DataFeedMetric is a quantifiable measure that is used to monitor and assess the status of a specific business process. 它可以是划分为多个维度的多个时序值的组合。It can be a combination of multiple time series values divided into dimensions. 例如,Web 运行状况指标可能包含用户数和 en-us 市场的维度 。For example a web health metric might contain dimensions for user count and the en-us market.

代码示例Code examples

这些代码片段展示如何借助适用于 Python 的指标顾问客户端库执行以下操作:These code snippets show you how to do the following with the Metrics Advisor client library for Python:

验证客户端Authenticate the client

在此示例中,客户端是一个使用终结点的 MetricsAdvisorAdministrationClient 对象,以及一个包含密钥的 MetricsAdvisorKeyCredential 对象。The client in this example is a MetricsAdvisorAdministrationClient object that uses your endpoint and a MetricsAdvisorKeyCredential object that contains your keys. 不需要复制此代码示例。You don't need to copy this code sample. 稍后创建的方法将实例化客户端。The methods you create later will instantiate the client. 备用客户端名为 MetricsAdvisorClient;有关此客户端的详细信息,请参阅参考文档The alternate client is called MetricsAdvisorClient more information on this client can be found in the reference documentation.

client = MetricsAdvisorAdministrationClient(service_endpoint,
                                MetricsAdvisorKeyCredential(subscription_key, api_key))

添加数据馈送Add a data feed

在新方法中,创建类似于以下示例的 import 语句。In a new method, create import statements like the example below. sql_server_connection_string 替换为你自己的 SQL Server 连接字符串,并将 query 替换为在单个时间戳返回数据的查询。Replace sql_server_connection_string with your own SQL server connection string, and replace query with a query that returns your data at a single timestamp. 你还需要根据自定义数据调整 DataFeedmetricDataFeedDimension 值。You will also need to adjust the DataFeedmetric and DataFeedDimension values based on your custom data.

重要

对于每个维度组合,查询应在每个时间戳处最多返回一条记录。The query should return at most one record for each dimension combination, at each timestamp. 查询返回的所有记录必须具有相同的时间戳。And all records returned by the query must have the same timestamps. 指标顾问将针对每个时间戳运行此查询以引入数据。Metrics Advisor will run this query for each timestamp to ingest your data. 有关详细信息和示例,请参阅查询常见问题解答部分See the FAQ section on queries for more information, and examples.

通过密钥和终结点创建客户端,并使用 client.create_data_feed() 配置名称、源、粒度和架构。Create a client with your keys and endpoint, and use client.create_data_feed() to configure the name, source, granularity, and schema. 你还可以设置引入时间、汇总设置等。You can also set the ingestion time, rollup settings and more.

def sample_create_data_feed():
    from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorAdministrationClient
    from azure.ai.metricsadvisor.models import (
        SQLServerDataFeed,
        DataFeedSchema,
        DataFeedMetric,
        DataFeedDimension,
        DataFeedOptions,
        DataFeedRollupSettings
    )
    sql_server_connection_string = "<replace-with-your-sql-server-connection-string>"
    query = "<replace-with-metrics-advisor-sql-server-query>"

    client = MetricsAdvisorAdministrationClient(service_endpoint,
                                  MetricsAdvisorKeyCredential(subscription_key, api_key))

    data_feed = client.create_data_feed(
    name="My data feed",
    source=SQLServerDataFeed(
        connection_string=sql_server_connection_string,
        query=query,
    ),
    granularity="Daily",
    schema=DataFeedSchema(
        metrics=[
            DataFeedMetric(name="cost", display_name="Cost"),
            DataFeedMetric(name="revenue", display_name="Revenue")
        ],
        dimensions=[
            DataFeedDimension(name="category", display_name="Category"),
            DataFeedDimension(name="city", display_name="City")
        ],
        timestamp_column="Timestamp"
    ),
    ingestion_settings=datetime.datetime(2019, 10, 1),
    options=DataFeedOptions(
        data_feed_description="cost/revenue data feed",
        rollup_settings=DataFeedRollupSettings(
            rollup_type="AutoRollup",
            rollup_method="Sum",
            rollup_identification_value="__CUSTOM_SUM__"
        ),
        missing_data_point_fill_settings=DataFeedMissingDataPointFillSettings(
            fill_type="SmartFilling"
        ),
        access_mode="Private"
    )
)

return data_feed
sample_create_data_feed()

检查引入状态Check the ingestion status

在新方法中,创建类似于以下示例的 import 语句。In a new method, create an import statement like the example below. data_feed_id 替换为你创建的数据馈送的 ID。Replace data_feed_id with the ID for the data feed you created. 通过密钥和终结点创建客户端,并使用 client.list_data_feed_ingestion_status() 获取引入进度。Create a client with your keys and endpoint, and use client.list_data_feed_ingestion_status() to get the ingestion progress. 输出详细信息,如最后一个有效且成功的时间戳。Print out the details, such as the last active and successful timestamps.

    from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorAdministrationClient

    data_feed_id = "<replace-with-your-metrics-advisor-data-feed-id>"

   client = MetricsAdvisorAdministrationClient(service_endpoint,
    MetricsAdvisorKeyCredential(subscription_key, api_key)
)

ingestion_status = client.list_data_feed_ingestion_status(
    data_feed_id,
    datetime.datetime(2020, 9, 20),
    datetime.datetime(2020, 9, 25)
)
for status in ingestion_status:
    print("Timestamp: {}".format(status.timestamp))
    print("Status: {}".format(status.status))
    print("Message: {}\n".format(status.message))

配置异常情况检测Configure anomaly detection

在新方法中,创建类似于以下示例的 import 语句。In a new method, create import statements like the example below. metric_id 替换为要配置的指标的 ID。Replace metric_id with the ID for the metric you want to configure. 通过密钥和终结点创建客户端,并使用 client.create_detection_configuration 创建新的检测配置。Create a client with your keys and endpoint, and use client.create_detection_configuration to create a new detection configuration. 阈值条件为异常情况检测指定参数。The threshold conditions specify the parameters for anomaly detection.

    from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorAdministrationClient
    from azure.ai.metricsadvisor.models import (
        ChangeThresholdCondition,
        HardThresholdCondition,
        SmartDetectionCondition,
        SuppressCondition,
        MetricDetectionCondition,
    )
    metric_id = "replace-with-your-metric-id"

    
client = MetricsAdvisorAdministrationClient(
    service_endpoint,
    MetricsAdvisorKeyCredential(subscription_key, api_key)
)

change_threshold_condition = ChangeThresholdCondition(
    anomaly_detector_direction="Both",
    change_percentage=20,
    shift_point=10,
    within_range=True,
    suppress_condition=SuppressCondition(
        min_number=5,
        min_ratio=2
    )
)
hard_threshold_condition = HardThresholdCondition(
    anomaly_detector_direction="Up",
    upper_bound=100,
    suppress_condition=SuppressCondition(
        min_number=2,
        min_ratio=2
    )
)
smart_detection_condition = SmartDetectionCondition(
    anomaly_detector_direction="Up",
    sensitivity=10,
    suppress_condition=SuppressCondition(
        min_number=2,
        min_ratio=2
    )
)

detection_config = client.create_detection_configuration(
    name="my_detection_config",
    metric_id=metric_id,
    description="anomaly detection config for metric",
    whole_series_detection_condition=MetricDetectionCondition(
        cross_conditions_operator="OR",
        change_threshold_condition=change_threshold_condition,
        hard_threshold_condition=hard_threshold_condition,
        smart_detection_condition=smart_detection_condition
    )
)
return detection_config

创建挂钩Create a hook

在新方法中,创建类似于以下示例的 import 语句。In a new method, create import statements like the example below. 通过密钥和终结点创建客户端,并使用 client.create_hook() 创建挂钩。Create a client with your keys and endpoint, and use client.create_hook() to create a hook. 输入说明、要向其发送警报的电子邮件列表,以及用于接收警报的外部链接。Enter a description, a list of emails to send the alert to, and an external link for receiving the alert.

def sample_create_hook():

    from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorAdministrationClient
    from azure.ai.metricsadvisor.models import EmailNotificationHook

    client = MetricsAdvisorAdministrationClient(service_endpoint,
                                  MetricsAdvisorKeyCredential(subscription_key, api_key))

client = MetricsAdvisorAdministrationClient(service_endpoint,
    MetricsAdvisorKeyCredential(subscription_key, api_key))

hook = client.create_hook(
    hook=EmailNotificationHook(
        name="email hook",
        description="my email hook",
        emails_to_alert=["alertme@alertme.com"],
        external_link="https://example.com/handleAlerts", # you must enter a valid webhook url to post the alert payload
    )
)

创建警报配置Create an alert configuration

在新方法中,创建类似于以下示例的 import 语句。In a new method, create import statements like the example below. detection_configuration_id 替换为异常情况检测配置的 ID,并将 hook_id 替换为之前创建的挂钩。Replace detection_configuration_id with the ID for your anomaly detection configuration, and replace hook_id with the hook that you created earlier. 通过密钥和终结点创建客户端,并使用 client.create_alert_configuration() 创建警报配置。Create a client with your keys and endpoint, and use client.create_alert_configuration() to create an alert configuration.

def sample_create_alert_config():
    from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorAdministrationClient
    from azure.ai.metricsadvisor.models import (
        MetricAlertConfiguration,
        MetricAnomalyAlertScope,
        TopNGroupScope,
        MetricAnomalyAlertConditions,
        SeverityCondition,
        MetricBoundaryCondition,
        MetricAnomalyAlertSnoozeCondition
    )
    anomaly_detection_configuration_id = "<replace-with-your-detection-configuration-id"
    hook_id = "<replace-with-your-hook-id>"

    client = MetricsAdvisorAdministrationClient(
    service_endpoint,
    MetricsAdvisorKeyCredential(subscription_key, api_key)
)

alert_config = client.create_alert_configuration(
        name="my alert config",
        description="alert config description",
        cross_metrics_operator="AND",
        metric_alert_configurations=[
            MetricAlertConfiguration(
                detection_configuration_id=detection_configuration_id,
                alert_scope=MetricAnomalyAlertScope(
                    scope_type="WholeSeries"
                ),
                alert_conditions=MetricAnomalyAlertConditions(
                    severity_condition=SeverityCondition(
                        min_alert_severity="Low",
                        max_alert_severity="High"
                    )
                )
            ),
            MetricAlertConfiguration(
                detection_configuration_id=detection_configuration_id,
                alert_scope=MetricAnomalyAlertScope(
                    scope_type="TopN",
                    top_n_group_in_scope=TopNGroupScope(
                        top=10,
                        period=5,
                        min_top_count=5
                    )
                ),
                alert_conditions=MetricAnomalyAlertConditions(
                    metric_boundary_condition=MetricBoundaryCondition(
                        direction="Up",
                        upper=50
                    )
                ),
                alert_snooze_condition=MetricAnomalyAlertSnoozeCondition(
                    auto_snooze=2,
                    snooze_scope="Metric",
                    only_for_successive=True
                )
            ),
        ],
        hook_ids=[hook_id]
    )

    return alert_config

查询警报Query the alert

在新方法中,创建类似于以下示例的 import 语句。In a new method, create an import statement like the example below. alert_id 替换为警报的 ID,并将 alert_config_id 替换为警报配置 ID。Replace alert_id with the ID for your alert, and replace alert_config_id with the alert configuration ID. 通过密钥和终结点创建客户端,并使用 client.list_anomalies 列出要警报的异常。Create a client with your keys and endpoint, and use client.list_anomalies to list the anomalies for an alert.

from azure.ai.metricsadvisor import MetricsAdvisorKeyCredential, MetricsAdvisorClient
    
alert_id = "<replace-with-your-alert-id>"
alert_config_id = "<replace-with-your-alert-configuration-id"

client = MetricsAdvisorClient(service_endpoint,
    MetricsAdvisorKeyCredential(subscription_key, api_key)
)

results = client.list_alerts(
    alert_configuration_id=alert_config_id,
    start_time=datetime.datetime(2020, 1, 1),
    end_time=datetime.datetime(2020, 9, 9),
    time_mode="AnomalyTime",
)
for result in results:
    print("Alert id: {}".format(result.id))
    print("Create on: {}".format(result.created_on))

results = client.list_anomalies(
    alert_configuration_id=alert_config_id,
    alert_id=alert_id,
)
for result in results:
    print("Create on: {}".format(result.created_on))
    print("Severity: {}".format(result.severity))
    print("Status: {}".format(result.status))

运行应用程序Run the application

在快速入门文件中使用 python 命令运行应用程序。Run the application with the python command on your quickstart file.

python quickstart-file.py

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅Azure subscription - Create one for trial
  • 获得 Azure 订阅后,在 Azure 门户中创建“指标顾问”资源 ,以部署“指标顾问”实例。Once you have your Azure subscription, create a Metrics Advisor resource in the Azure portal to deploy your Metrics Advisor instance.
  • 最新版本的 cURLThe current version of cURL. 本文使用了 cURL 文档中所述的多个命令行开关。Several command-line switches are used in this article, which are noted in the cURL documentation.
    • 以下 BASH 示例使用 \ 行继续符。The following BASH examples use the \ line continuation character. 如果你的控制台或终端使用不同的行继续符,请使用此字符。If you console or terminal uses a different line continuation character, use this character.

提示

  • 可以在 GitHub 上找到调用 REST API 的 Python 示例。You can find a Python sample that calls the REST API on GitHub.
  • 指标顾问资源可能需要 10 到 30 分钟才能部署一个服务实例供你使用。It may 10 to 30 minutes for your Metrics Advisor resource to deploy a service instance for you to use. 部署成功后,单击“转到资源”。Click Go to resource once it successfully deploys. 部署完成后,可以通过 Web 门户和 REST API 这两种方式开始使用指标顾问实例。After deployment, you can start using your Metrics Advisor instance with both the web portal and REST API.
  • 可以在 Azure 门户的资源“概述”部分中找到 REST API 的 URL。You can find the URL for the REST API in Azure portal, in the Overview section of your resource. 它将如下所示:it will look like this:
    • https://<instance-name>.cognitiveservices.azure.cn/

开始使用 REST API 需要两个密钥:You will need two keys to start using the REST API:

  • 指标顾问资源的密钥。The key to your Metrics Advisor resource. 可以在 Azure 门户中资源的“密钥和终结点”部分中找到此密钥。You can find this in the Keys and Endpoint section of your resource in the Azure portal.
    • 稍后要将示例中的 Ocp-Apim-Subscription-Key 替换为此密钥。Later you will replace Ocp-Apim-Subscription-Key in the examples with this key.
  • 指标顾问实例的 API 密钥。The API key for your Metrics Advisor instance. 可以在指标顾问的 Web 门户中左侧导航菜单上的“API 密钥”中找到此密钥。You can find this in the web portal for Metrics Advisor, in API keys on the left navigation menu.
    • 稍后要将示例中的 x-api-key 替换为此密钥。Later you will replace x-api-key in the examples with this key.

从示例或数据源添加数据馈送Add a data feed from a sample or data source

若要开始监视时序数据,需要添加一个数据馈送。To start monitoring your time series data, you need add a data feed. 若要添加数据馈送,需要根据数据源类型和参数提供数据架构。To add a data feed, you need to provide a data schema according to the data source type and parameters. 将以下 JSON 请求正文保存到名为 body.json 的文件中,然后运行 cURL 命令。Save the below JSON request body to a file named body.json, and run the cURL command.

{
        "dataSourceType": "SqlServer",
        "dataFeedName": "test_data_feed_00000001",
        "dataFeedDescription": "",
        "dataSourceParameter": {
            "connectionString": "Server=ad-sample.database.chinacloudapi.cn,1433;Initial Catalog=ad-sample;Persist Security Info=False;User ID=adreadonly;Password=Readonly@2020;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
            "query": "select * from adsample3 where Timestamp = @StartTime"
        },
        "granularityName": "Daily",
        "granularityAmount": 0,
        "metrics": [
            {
                "metricName": "revenue",
                "metricDisplayName": "revenue",
                "metricDescription": ""
            },
            {
                "metricName": "cost",
                "metricDisplayName": "cost",
                "metricDescription": ""
            }
        ],
        "dimension": [
            {
                "dimensionName": "city",
                "dimensionDisplayName": "city"
            },
            {
                "dimensionName": "category",
                "dimensionDisplayName": "category"
            }
        ],
        "timestampColumn": "timestamp",
        "dataStartFrom": "2020-06-01T00:00:00.000Z",
        "startOffsetInSeconds": 0,
        "maxConcurrency": -1,
        "minRetryIntervalInSeconds": -1,
        "stopRetryAfterInSeconds": -1,
        "needRollup": "NoRollup",
        "fillMissingPointType": "SmartFilling",
        "fillMissingPointValue": 0,
        "viewMode": "Private",
        "admins": [
            "xxx@microsoft.com"
        ],
        "viewers": [
        ],
        "actionLinkTemplate": ""
}

cURL 命令将从 BASH shell 执行。The cURL command is executed from a BASH shell. 请使用自己的资源名称、资源密钥和 JSON 值编辑此命令。Edit this command with your own resource name, resource key, and JSON values.

curl -i https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/datafeeds \
-X POST \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY" \
-H "Content-Type:application/json" \
-d @body.json

示例响应Example response

HTTP/1.1 201 Created
Content-Length: 0
Location: https://gualala-beta-0617.cognitiveservices.azure.cn/metricsadvisor/v1.0/datafeeds/b5921405-8001-42b2-8746-004ddeeb780d
x-envoy-upstream-service-time: 564
apim-request-id: 4e4fe70b-d663-4fb7-a804-b9dc14ba02a3
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Thu, 03 Sep 2020 18:29:27 GMT

在上面的响应中,“位置”标头是所创建的数据馈送的 URL,其中包含“dataFeedID” 。In above response, Location header is the URL of data feed you created, and it contains dataFeedID.

使用上述 URL,可以查询在上一步中创建的数据馈送的详细信息。Using above URL, you can query detailed information of the data feed you've created in previous step. (在以下步骤中,我们将使用数据馈送信息中的“metricID”)(We will use metricID in data feed info in the following steps)

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/datafeeds/REPLACE-WITH-YOUR-DATA-FEED-ID \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "dataFeedId":"90919c03-be13-4efa-86e5-aa9dc72764ce",
   "dataFeedName":"test_data_feed_00000007",
   "metrics":[
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "metricName":"cost",
         "metricDisplayName":"cost",
         "metricDescription":""
      },
      {
         "metricId":"82bbc63d-3739-4d57-b190-accb69721b6a",
         "metricName":"revenue",
         "metricDisplayName":"revenue",
         "metricDescription":""
      }
   ],
   "dimension":[
      {
         "dimensionName":"category",
         "dimensionDisplayName":"category"
      },
      {
         "dimensionName":"city",
         "dimensionDisplayName":"city"
      }
   ],
   "dataStartFrom":"2020-06-01T00:00:00Z",
   "dataSourceType":"SqlServer",
   "timestampColumn":"timestamp",
   "startOffsetInSeconds":0,
   "maxQueryPerMinute":30.0,
   "granularityName":"Daily",
   "granularityAmount":null,
   "allUpIdentification":null,
   "needRollup":"NoRollup",
   "fillMissingPointType":"SmartFilling",
   "fillMissingPointValue":0.0,
   "rollUpMethod":"None",
   "rollUpColumns":[
      
   ],
   "dataFeedDescription":"",
   "stopRetryAfterInSeconds":-1,
   "minRetryIntervalInSeconds":-1,
   "maxConcurrency":-1,
   "viewMode":"Private",
   "admins":[
      "xyz@microsoft.com"
   ],
   "viewers":[
      
   ],
   "creator":"xyz@microsoft.com",
   "status":"Active",
   "createdTime":"2020-09-08T08:39:28Z",
   "isAdmin":true,
   "actionLinkTemplate":"",
   "dataSourceParameter":{
      "connectionString":"Server=ad-sample.database.chinacloudapi.cn,1433;Initial Catalog=ad-sample;Persist Security Info=False;User ID=adreadonly;Password=Readonly@2020;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
      "query":"select * from adsample3 where Timestamp = @StartTime"
   }
}

检查引入状态Check ingestion status

添加数据馈送后,若要检查引入作业的进度,可以检查其状态。After adding data feed, if you want to check the progress of an ingestion job, you can check the status of it. 将以下 JSON 请求正文保存到名为 body.json 的文件中,然后运行 cURL 命令。Save the below JSON request body to a file named body.json, and run the cURL command.

{
  "startTime": "2020-01-01T00:00:00.0000000+00:00",
  "endTime": "2020-01-04T00:00:00.0000000+00:00"
}

cURL 命令将从 BASH shell 执行。The cURL command is executed from a BASH shell. 请使用自己的资源名称、资源密钥、JSON 值和 JSON 大小编辑此命令。Edit this command with your own resource name, resource key, and JSON values and size of JSON.

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/datafeeds/REPLACE-WITH-YOUR-DATA-FEED-ID/ingestionStatus/query \
-X POST \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY" \
-H "Content-Type:application/json" \
-d @body.json

示例响应Example response

{
  "@nextLink": "https://demo.example.com/datafeeds/01234567-8901-2345-6789-012345678901/ingestionStatus/query?$skip=3&$top=1",
  "value": [
    {
      "timestamp": "2020-09-03T00:00:00.0000000+00:00",
      "status": "Running",
      "message": ""
    },
    {
      "timestamp": "2020-09-02T00:00:00.0000000+00:00",
      "status": "Succeeded",
      "message": ""
    },
    {
      "timestamp": "2020-09-01T00:00:00.0000000+00:00",
      "status": "Failed",
      "message": "No valid record pulled from source for current timestamp 2020-01-01T00:00:00Z"
    }
  ]
}

配置异常情况检测配置Configure anomaly detection configuration

虽然默认配置会自动应用于每个指标,但可以调整对数据用的检测模式。While a default configuration is automatically applied to each metric, you can tune the detection modes used on your data. 将以下 JSON 请求正文保存到名为 body.json 的文件中,然后运行 cURL 命令。Save the below JSON request body to a file named body.json, and run the cURL command.

{
        "name": "test_detection_config0000000001",
        "description": "string",
        "metricId": "8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
        "wholeMetricConfiguration": {
            "smartDetectionCondition": {
                "sensitivity": 100,
                "anomalyDetectorDirection": "Both",
                "suppressCondition": {
                    "minNumber": 1,
                    "minRatio": 1
                }
            }
        },
        "dimensionGroupOverrideConfigurations": [
        ],
        "seriesOverrideConfigurations": [
        ]
}

cURL 命令将从 BASH shell 执行。The cURL command is executed from a BASH shell. 请使用自己的资源名称、资源密钥、JSON 值和 JSON 大小编辑此命令。Edit this command with your own resource name, resource key, and JSON values and size of JSON.

curl -i https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/enrichment/anomalyDetection/configurations \
-X POST \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY" \
-H "Content-Type:application/json" \
-d @body.json

示例响应Example response

HTTP/1.1 201 Created
Content-Length: 0
Location: https://gualala-beta-0617.cognitiveservices.azure.cn/metricsadvisor/v1.0/enrichment/anomalyDetection/configurations/6a977d61-f0f5-488a-a162-2feb4643ae09
x-request-id: 17752fcc-9085-46d5-ad37-c4e9e9ba6a5a
x-envoy-upstream-service-time: 253
apim-request-id: 17752fcc-9085-46d5-ad37-c4e9e9ba6a5a
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Tue, 08 Sep 2020 09:50:38 GMT

在上述“Location”标头中,包含新创建的资源(检测配置)的 URL。In above Location header, it contains the URL of the new created resource(detection configuration).

使用上述“Location”标头的 URL,可以查询已创建的检测配置(在以下步骤中,将在响应内容中使用“anomalyDetectionConfigurationId” )Using above URL in Location header , you can query detection configuration you've created (We will use anomalyDetectionConfigurationId in response content in the following steps)

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/enrichment/anomalyDetection/configurations/REPLACE-WITH-YOUR-DETECTION-CONFIGURATION-ID \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
   "name":"test_detection_config0000000001",
   "description":"string",
   "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
   "wholeMetricConfiguration":{
      "smartDetectionCondition":{
         "sensitivity":100.0,
         "anomalyDetectorDirection":"Both",
         "suppressCondition":{
            "minNumber":1,
            "minRatio":1.0
         }
      }
   },
   "dimensionGroupOverrideConfigurations":[
      
   ],
   "seriesOverrideConfigurations":[
      
   ]
}

配置警报配置Configure alert configuration

在配置警报之前,需要创建一个将用于通知警报的挂钩。Before configuring alert, you need create a hook which will be used to notify alert. 有两种方法可以在触发警报时获取通知,即 Webhook 和电子邮件。There are two ways to get notified if an alert is triggered, that is webhook and email. 创建挂钩时,可以在挂钩配置中将其中之一指定为挂钩类型。You can specify either of them in hook configuration as hook type while creating a hook.

将以下 JSON 请求正文保存到名为 body.json 的文件中,然后运行 cURL 命令。Save the below JSON request body to a file named body.json, and run the cURL command.

{
        "hookType": "Webhook",
        "hookName": "test_web_hook000001",
        "description": "",
        "externalLink": "",
        "hookParameter": {
            "endpoint": "https://www.xxx.com/aaa",
            "username": "",
            "password": ""
        }
}

cURL 命令将从 BASH shell 执行。The cURL command is executed from a BASH shell. 请使用自己的资源名称、资源密钥、JSON 值和 JSON 大小编辑此命令。Edit this command with your own resource name, resource key, and JSON values and size of JSON.

curl -i https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/hooks \
-X POST \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY" \
-H "Content-Type:application/json" \
-d @body.json

示例响应Example response

HTTP/1.1 201 Created
Content-Length: 0
Location: https://gualala-beta-0617.cognitiveservices.azure.cn/metricsadvisor/v1.0/hooks/34d677bd-0875-4760-8bf6-24d48abde7c3
x-request-id: 7b6cc1a6-02cb-405b-bee3-174fdae0a7d2
x-envoy-upstream-service-time: 1640
apim-request-id: 7b6cc1a6-02cb-405b-bee3-174fdae0a7d2
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Tue, 08 Sep 2020 10:37:59 GMT

使用上述“Location”标头中的 URL,可以查询已创建的 Webhook。Using above URL in Location header , you can query the webhook you've created.

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/hooks/REPLACE-WITH-YOUR-HOOK-ID \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "hookId":"34d677bd-0875-4760-8bf6-24d48abde7c3",
   "hookName":"test_web_hook000001",
   "hookType":"Webhook",
   "externalLink":"",
   "description":"",
   "admins":[
      "bowgong@microsoft.com"
   ],
   "hookParameter":{
      "endpoint":"https://www.xxx.com/aaa",
      "username":"",
      "password":"",
      "headers":{
         

      },
      "certificateKey":"",
      "certificatePassword":""

   }
}

通过配置警报配置,可以指定可用于触发警报的检测条件。By configuring alert configuration, you can specify detection condition which can be used to trigger alert. 将以下 JSON 请求正文保存到名为 body.json 的文件中,然后运行 cURL 命令。Save the below JSON request body to a file named body.json, and run the cURL command.

{
        "name": "test_alert_config00000001",
        "description": "",
        "crossMetricsOperator": "AND",
        "hookIds": [
           "34d677bd-0875-4760-8bf6-24d48abde7c3" 
        ],
        "metricAlertingConfigurations": [
            {
                "anomalyDetectionConfigurationId": "6a977d61-f0f5-488a-a162-2feb4643ae09",
                "anomalyScopeType": "All",
                "severityFilter": {
                    "minAlertSeverity": "Low",
                    "maxAlertSeverity": "High"
                },
                "snoozeFilter": {
                    "autoSnooze": 0,
                    "snoozeScope": "Metric",
                    "onlyForSuccessive": true
                },
            }
        ]
}

cURL 命令将从 BASH shell 执行。The cURL command is executed from a BASH shell. 请使用自己的资源名称、资源密钥、JSON 值和 JSON 大小编辑此命令。Edit this command with your own resource name, resource key, and JSON values and size of JSON.

curl -i https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/alert/anomaly/configurations \
-X POST \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY" \
-H "Content-Type:application/json" \
-d @body.json

示例响应Example response

HTTP/1.1 201 Created
Content-Length: 0
Location: https://gualala-beta-0617.cognitiveservices.azure.cn/metricsadvisor/v1.0/alert/anomaly/configurations/40004c91-6996-47c0-b8c8-fd20a8f4f0ab
x-request-id: 17752fcc-9085-46d5-ad37-c4e9e9ba6a5a
x-envoy-upstream-service-time: 253
apim-request-id: 17752fcc-9085-46d5-ad37-c4e9e9ba6a5a
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Tue, 08 Sep 2020 09:50:38 GMT

在上述“Location”标头中,包含新创建的资源(检测配置)的 URL。In above Location header, it contains the URL of the new created resource(detection configuration).

使用上述“Location”标头中的 URL,可以查询已创建的警报配置。Using above URL in Location header , you can query alert configuration you've created. (在以下步骤中,将在警报配置中使用“anomalyAlertingConfigurationId”)(We will use anomalyAlertingConfigurationId in alert configuration in the following steps)

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/alert/anomaly/configurations/REPLACE-WITH-YOUR-ANOMALY-ALERTING-CONFIGURATION-ID \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "anomalyAlertingConfigurationId":"40004c91-6996-47c0-b8c8-fd20a8f4f0ab",
   "name":"test_alert_config00000001",
   "description":"",
   "hookIds":[
      "34d677bd-0875-4760-8bf6-24d48abde7c3"
   ],
   "metricAlertingConfigurations":[
      {
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "anomalyScopeType":"All",
         "negationOperation":false,
         "severityFilter":{
            "minAlertSeverity":"Low",
            "maxAlertSeverity":"High"
         },
         "snoozeFilter":{
            "autoSnooze":0,
            "snoozeScope":"Metric",
            "onlyForSuccessive":true
         }
      }
   ]
}

查询异常情况检测结果Query anomaly detection results

可以通过不同的方式获取检测结果。There are different ways to get detection result. 例如,可以使用创建的检测配置定期主动查询检测结果,也可以通过警报获取通知,然后可以使用此警报来查询相应的异常。For instance, you can actively query detection result periodically using detection config you created, or you could be notified through alert, and then you can use this alert to query corresponding anomalies.

以下示例中演示了如何查询警报,并使用此警报来查询与其相关的异常。In following sample, it shows how to query alert, and using this alert to query anomalies related to this alert.

查询警报Query alert

可以使用在上述步骤中创建的警报配置来查询警报。You can use alert configuration created in above step to query the alert.

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/alert/anomaly/configurations/REPLACE-WITH-YOUR-ANOMALY-ALERTING-CONFIGURATION-ID/alerts/query \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "value":[
      {
         "alertId":"17465dcc000",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.532Z",
         "modifiedTime":"2020-09-08T19:12:46.588Z"
      }
   ],
   "@nextLink":null
}

在上述响应中,我们收到了一个警报。In above response, we got an alert. 使用此“alertID”,我们可以查询导致此警报的所有相关异常。Using this alertID, we can query all related anomalies caused this alert.

(获取警报的另一种方法是配置 Webhook,并在发现警报后被动收到警报)(Another way to get alert is to configure webhook, and passively received alert once it is found)

使用 alertID 查询异常Query anomalies using alertID

curl https://REPLACE-WITH-YOUR-ENDPOINT/metricsadvisor/v1.0/alert/anomaly/configurations/REPLACE-WITH-YOUR-ANOMALY-ALERTING-CONFIGURATION-ID/alerts/REPLACE-WITH-YOUR-ALERTID/anomalies \
-H "Ocp-Apim-Subscription-Key: REPLACE-WITH-YOUR-RESOURCE-KEY" \
-H "x-api-key: REPLACE-WITH-YOUR-API-KEY"

示例响应Example response

{
   "value":[
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Amphibian",
            "category":"Caucasian Fir"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Animals by number of neurons",
            "category":"Crack willow"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Amphibian",
            "category":"Crack willow"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Animals by number of neurons",
            "category":"Common Lime"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Chickadee",
            "category":"Common Lime"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Amphibian",
            "category":"Common Lime"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      },
      {
         "metricId":"8d03e541-a56d-4c28-8d9c-09ce91c6d95f",
         "anomalyDetectionConfigurationId":"6a977d61-f0f5-488a-a162-2feb4643ae09",
         "timestamp":"2020-09-07T00:00:00Z",
         "createdTime":"2020-09-08T19:12:46.566Z",
         "modifiedTime":"2020-09-08T19:12:46.566Z",
         "dimension":{
            "city":"Chickadee",
            "category":"Crack willow"
         },
         "property":{
            "anomalySeverity":"High",
            "anomalyStatus":"Active"
         }
      }
   ],
   "@nextLink":null
}

清理资源Clean up resources

如果想要清理并删除认知服务订阅,可以删除资源或资源组。If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. 删除资源组同时也会删除与之相关联的任何其他资源。Deleting the resource group also deletes any other resources associated with it.

后续步骤Next steps