教程:探索 Azure 时序见解 JavaScript 客户端库Tutorial: Explore the Azure Time Series Insights JavaScript client library

为了帮助 Web 开发人员查询并可视化时序见解中存储的数据,我们开发了基于 JavaScript D3 的 Azure 时序见解客户端库。The JavaScript D3-based Azure Time Series Insights client library was developed to help web developers query and visualize data stored in Time Series Insights. 本教程将使用托管示例应用引导你完成时序见解客户端库和编程模型。This tutorial guides you through the Time Series Insights client library and programming model by using a hosted sample app.

本教程将详细介绍如何使用库、如何访问时序见解数据以及如何使用图表控件来呈现和可视化数据。The tutorial details how to work with the library, how to access Time Series Insights data, and how to use chart controls to render and visualize data. 还将介绍如何尝试使用不同类型的图形来可视化数据。You'll also learn how to experiment with different kinds of graphs to visualize data. 在本教程结束时,你将能够使用客户端库将时序见解功能合并到你自己的 Web 应用中。At the end of the tutorial, you'll be able to use the client library to incorporate Time Series Insights features into your own web app.

具体来说,将学习以下内容:Specifically, you'll learn about:

  • 时序见解示例应用程序The Time Series Insights sample application
  • 时序见解 JavaScript 客户端库The Time Series Insights JavaScript client library
  • 示例应用程序如何使用该库来可视化时序见解数据How the sample application uses the library to visualize Time Series Insights data

备注

如果没有 Azure 订阅,请注册一个试用的 Azure 订阅Sign up for a trial Azure subscription if you don't already have one.

必备条件Prerequisites

本教程使用浏览器的“开发人员工具”功能 。This tutorial uses your browser's Developer Tools feature. 现代 Web 浏览器(Microsoft Edge、Chrome、FirefoxSafari 等)通常可以通过键盘上的 F12 热键访问“Web 检查器视图” 。Modern web browsers (Microsoft Edge, Chrome, Firefox, Safari, and others) typically provide access to the Web Inspector View through the F12 hotkey on your keyboard. 访问该视图的另一种方法是右键单击网页,然后选择“检查元素” 。Another way to access the view is to right-click on a webpage, and then select Inspect Element.

示例应用程序Sample application

整篇教程都使用免费的托管时序见解示例应用来探索应用程序背后的源代码和时序见解 JavaScript 客户端库。Throughout this tutorial, we use a free, hosted Time Series Insights sample app to explore the source code behind the application and to explore the Time Series Insights JavaScript client library. 通过使用示例应用,你将了解如何在 JavaScript 中与时序见解进行交互并通过图表和图形可视化数据。By using the sample app, you'll learn how to interact with Time Series Insights in JavaScript and visualize data through charts and graphs.

  1. 转到时序见解示例应用程序Go to the Time Series Insights sample application. 将显示以下登录提示:The following sign-in prompt appears:

    时序见解客户端示例登录提示Time Series Insights client sample sign-in prompt

  2. 选择“登录”,输入或选择凭据 。Select Log in to enter or select your credentials. 可使用企业组织帐户 (Azure Active Directory) 或个人帐户(Microsoft 帐户)。Use either an enterprise organization account (Azure Active Directory) or a personal account (Microsoft account).

    时序见解客户端示例凭据提示Time Series Insights client sample credentials prompt

  3. 登录后,将显示一个页面,其中显示填充了时序见解数据的图表。After you sign in, a page that displays charts populated with Time Series Insights data is shown. 右上角显示了你自己的用户帐户和“注销”选项: Your user account and the Log out option are visible in the upper right corner:

    登录后的时序见解客户端示例主页Time Series Insights client sample main page after sign-in

页面源代码和结构Page source and structure

首先,让我们查看呈现的网页的 HTML 和 JavaScript 源代码First, let's view the HTML and JavaScript source code of the rendered webpage:

  1. 在浏览器中打开“开发人员工具”。 Open Developer Tools in your browser. 查看构成当前页面的 HTML 元素(也称为 HTML 或 DOM 树)。Inspect the HTML elements that make up the current page (also known as the HTML or DOM tree).

  2. 展开 <head><body> 元素并观察以下节:Expand the <head> and <body> elements and observe the following sections:

    • <head> 元素下,你将找到允许应用运行的页面元数据和依赖项:Under the <head> element, you'll find page metadata and dependencies that enable the app to run:

      • 用于引用 Azure Active Directory 身份验证库 (ADAL) 文件 adal.min.js<script> 元素。A <script> element that's used to reference the Azure Active Directory Authentication Library (ADAL) file adal.min.js. ADAL 是一个 JavaScript 库,它提供 OAuth 2.0 身份验证(登录),并获取用于访问 API 的令牌。ADAL is a JavaScript library that provides OAuth 2.0 authentication (sign-in) and token acquisition for accessing APIs.
      • 样式表(也称为 CSS,例如 sampleStyles.csstsiclient.css)的多个 <link> 元素。Multiple <link> elements for style sheets (also known as CSS) like sampleStyles.css and tsiclient.css. 样式表控制视觉页面样式详细信息,例如颜色、字体和间距。The style sheets control visual page styling details, such as colors, fonts, and spacing.
      • 用于引用时序见解 JavaScript 客户端库 tsiclient.js<script> 元素。A <script> element that's used to reference the Time Series Insights JavaScript client library tsiclient.js. 页面使用该库来调用时序见解服务 API,并在页面上呈现图表控件。The page uses the library to call Time Series Insights service APIs and to render chart controls on the page.

      备注

    • <body> 元素下,可看到帮助定义页面上项布局的 <div> 元素,以及另一个 <script> 元素:Under the <body> element, you'll find <div> elements, which help define the layout of items on the page, and another <script> element:

      • 第一个 <div> 元素指定“登录”对话框 (id="loginModal") 。The first <div> element specifies the Log in dialog box (id="loginModal").
      • 第二个 <div> 元素充当以下对象的父级:The second <div> element acts as a parent for:
        • 一个标头 <div> 元素,用于在页面顶部附近显示状态消息和登录信息 (class="header")。A header <div> element that's used for status messages and sign-in information near the top of the page (class="header").
        • 一个 <div> 元素,用于剩余的页面主体元素,包括图表 (class="chartsWrapper")。A <div> element for the remainder of the page body elements, including the charts (class="chartsWrapper").
        • 一个 <script> 节,其中包含用于控制页面的 JavaScript。A <script> section that contains the JavaScript that's used to control the page.

    包含开发人员工具的时序见解客户端示例Time Series Insights Client sample with Developer Tools

  3. 展开 <div class="chartsWrapper"> 元素,将看到其他 <div> 子元素。Expand the <div class="chartsWrapper"> element and you'll find more child <div> elements. 这些元素用于定位每个图表控件示例。These elements are used to position each chart control example. 有好几对 <div> 元素,每个图表示例各有一对:There are several pairs of <div> elements, one for each chart example:

    • 第一个 (class="rowOfCardsTitle") 元素包含描述性的标题,用于概括图表演示的内容。The first (class="rowOfCardsTitle") element contains a descriptive title to summarize what the chart(s) illustrate. 例如: Static Line Charts With Full-Size Legends.For example: Static Line Charts With Full-Size Legends.
    • 第二个 (class="rowOfCards") 元素是父级,包含用于在行中定位实际图表控件的其他 <div> 子元素。The second (class="rowOfCards") element is a parent that contains additional child <div> elements that position the actual chart controls within a row.

    正文 div 元素Body div elements

  4. 展开紧靠在 <div class="chartsWrapper"> 元素下面的 <script type="text/javascript"> 元素。Expand the <script type="text/javascript"> element that's directly below the <div class="chartsWrapper"> element. 页面级 JavaScript 节的开头部分用于处理所有页面逻辑(身份验证、调用时序见解服务 API、呈现图表控件等):The beginning of the page-level JavaScript section is used to handle all of the page logic (authentication, calling Time Series Insights service APIs, rendering the chart controls, and more):

    正文脚本Body script

JavaScript 客户端库JavaScript client library

时序见解客户端库 (tsiclient.js) 为两个重要的 JavaScript 功能提供抽象:The Time Series Insights client library (tsiclient.js) provides abstractions for two important JavaScript functionalities:

  • 用于调用时序见解查询 API 的包装器方法:可用于通过聚合表达式查询时序见解数据的 REST API。Wrapper methods for calling the Time Series Insights Query APIs: REST APIs you can use to query for Time Series Insights data by using aggregate expressions. 这些方法组织在库的 TsiClient.Server 命名空间下。The methods are organized under the TsiClient.Server namespace of the library.

  • 用于创建和填充多种图表控件的方法:可用于在网页中呈现时序见解聚合数据的方法。Methods for creating and populating several types of charting controls: Methods you can use to render the Time Series Insights aggregate data in a webpage. 这些方法组织在库的 TsiClient.UX 命名空间下。The methods are organized under the TsiClient.UX namespace of the library.

通过这些简化,开发人员可以更轻松地生成使用时序见解数据提供支持的 UI 图形和图表组件。Through these simplifications, developers can more easily build UI graph and chart components that are powered with Time Series Insights data.

身份验证Authentication

时序见解示例应用程序是具有 ADAL OAuth 2.0 用户身份验证支持的单页应用:The Time Series Insights sample application is a single-page app that has ADAL OAuth 2.0 user authentication support:

  1. 使用 ADAL 进行身份验证时,必须在 Azure Active Directory (Azure AD) 中注册客户端应用。When you use ADAL for authentication, the client app must be registered in Azure Active Directory (Azure AD). 注册单页应用是为了使用 OAuth 2.0 隐式授权流In fact, the single-page app is registered to use the OAuth 2.0 implicit grant flow.
  2. 应用程序必须在运行时指定一些注册属性。The application must specify some of the registration properties at runtime. 这些属性包括客户端 GUID (clientId) 和重定向 URI (postLogoutRedirectUri)。The properties include the client GUID (clientId) and the redirect URI (postLogoutRedirectUri).
  3. 稍后,应用会从 Azure AD 请求访问令牌Later, the app requests an access token from Azure AD. 将会针对特定的服务或 API 标识符 (https://api.timeseries.azure.com) 颁发拥有一组有限权限的访问令牌。The access token is issued for a finite set of permissions for a specific service or API identifier (https://api.timeseries.azure.com). 令牌权限是代表登录用户颁发的。The token permissions are issued on behalf of the signed-in user. 服务或 API 的标识符是包含在应用的 Azure AD 注册中的另一个属性。The identifier for the service or API is another property that's contained in the app's Azure AD registration.
  4. ADAL 向应用返回访问令牌后,在访问时序见解服务 API 时,系统会将该令牌作为持有者令牌传递。After ADAL returns the access token to the app, it's passed as a bearer token when it accesses the Time Series Insights service APIs.
// START: AUTHENTICATION RELATED CODE USING ADAL.JS
    // Set up ADAL
    var authContext = new AuthenticationContext({
        clientId: '000000-000000-000000-000000',
        postLogoutRedirectUri: 'https://tsiapp.azurewebsites.net/',
        cacheLocation: 'localStorage'
    });
    
    if (authContext.isCallback(window.location.hash)) {
    
        // Handle redirect after token requests
        authContext.handleWindowCallback();
        var err = authContext.getLoginError();
        if (err) {
            // TODO: Handle errors signing in and getting tokens
            document.getElementById('api_response').textContent = err;
            document.getElementById('loginModal').style.display = "block";
        }
    
    } else {
        var user = authContext.getCachedUser();
        if (user) {
            document.getElementById('username').textContent = user.userName;
            
        } else {
            document.getElementById('username').textContent = 'Not signed in.';
        }
    }
    
    authContext.getTsiToken = function(){
        document.getElementById('api_response2').textContent = 'Getting tsi token...';
        
        // Get an access token to the Microsoft TSI API
        var promise = new Promise(function(resolve,reject){
            authContext.acquireToken(
            'https://api.timeseries.azure.com/',
            function (error, token) {
    
                if (error || !token) {
                    // TODO: Handle error obtaining access token
                    document.getElementById('api_response').textContent = error;
                    document.getElementById('loginModal').style.display = "block";
                    document.getElementById('api_response2').textContent = '';
                    return;
                }
    
                // Use the access token
                document.getElementById('api_response').textContent = '';
                document.getElementById('api_response2').textContent = '';
                document.getElementById('loginModal').style.display = "none";
                resolve(token);
                }
            );
        });
        
        return promise;
    }
// END: AUTHENTICATION RELATED CODE USING ADAL.JS

提示

若要了解有关 Microsoft 支持的 Azure AD 身份验证库的详细信息,请参阅 Azure Active Directory 身份验证库参考文档To learn more about Microsoft-supported Azure AD authentication libraries, see the Azure Active Directory Authentication Library reference documentation.

控制标识Control identification

在提供的示例中,<div> 元素排列在父 <body> 元素中,以便为页面上呈现的图表控件提供合理的布局。In the provided example, <div> elements are arranged in the parent <body> element to provide a sensible layout for the chart controls that render on the page.

其中的每个 <div> 元素指定图表控件的位置和视觉对象特性的属性。Each <div> element specifies properties for the placement and visual attributes of chart controls. HTML 元素 id 属性用作唯一标识符,用于绑定到特定控件以呈现和更新可视化数据。HTML element id properties serve as unique identifiers to bind to specific controls to render and update visualized data.

聚合表达式Aggregate expressions

时序见解客户端库 API 使用聚合表达式:The Time Series Insights client library APIs use aggregate expressions:

  • 使用聚合表达式可以构造一个或多个“搜索词” 。An aggregate expression provides the ability to construct one or more search terms.

  • 客户端 API 的设计目的是提供与另一个演示应用(时序见解资源管理器)类似的功能,后者使用搜索范围、where 谓词、度量值和 splitBy 值。The client APIs are designed to provide similar functionality to another demo app (the Time Series Insights explorer), which uses search span, where predicates, measures, and splitBy values.

  • 大多数客户端库 API 都采用聚合表达式的数组,服务使用这些表达式来生成时序见解数据查询。Most client library APIs take an array of aggregate expressions that the service uses to build a Time Series Insights data query.

调用模式Call pattern

图表控件的填充和呈现遵循一种常规模式。Populating and rendering chart controls follows a general pattern. 你可以在整个示例应用中观察此常规模式,并在使用客户端库时获得帮助:You can observe the general pattern throughout the sample app, and can assist you when you use the client library:

  1. 声明一个 array 来保存一个或多个时序见解聚合表达式:Declare an array to hold one or more Time Series Insights aggregate expressions:

    var aes =  [];
    
  2. 构建“1”到“n”聚合表达式对象 。Build 1 to n aggregate expression objects. 然后将其添加到聚合表达式数组:Then, add them to the aggregate expression array:

    var ae = new tsiClient.ux.aggregateExpression(predicateObject, measureObject, measureTypes, searchSpan, splitByObject, color, alias, contextMenuActions);
    aes.push(ae);
    

    aggregateExpression 参数aggregateExpression parameters

    参数Parameter 说明Description 示例Example
    predicateObject 数据筛选表达式The data filtering expression {predicateString: "Factory = 'Factory3'"}
    measureObject 所用度量的属性名称The property name of the measure that's used {property: 'Temperature', type: "Double"}
    measureTypes 所需度量属性的聚合The aggregations of the measure property you want ['avg', 'min']
    searchSpan 聚合表达式的持续时间和间隔大小The duration and interval size of the aggregate expression {from: startDate, to: endDate, bucketSize: '2m'}
    splitByObject 用作拆分依据的字符串属性(可选:可为 null)The string property you want to split by (optional: can be null) {property: 'Station', type: 'String'}
    color 要呈现的对象的颜色The color of the objects you want to render 'pink'
    alias 聚合表达式的友好名称A friendly name for the aggregate expression 'Factory3Temperature'
    contextMenuActions 要在可视化效果中绑定到时序对象的操作数组(可选)An array of actions to be bound to the time series objects in a visualization (optional) 有关详细信息,请参阅弹出上下文菜单For more information, see Pop-up context menus.
  3. 使用 TsiClient.Server API 调用时序见解查询以请求聚合数据:Call a Time Series Insights query by using the TsiClient.Server APIs to request the aggregate data:

    tsiClient.server.getAggregates(token, envFQDN, aeTsxArray);
    

    getAggregates 参数getAggregates parameters

    参数Parameter 说明Description 示例Example
    token 时序见解 API 的访问令牌The access token for the Time Series Insights API authContext.getTsiToken()
    有关详细信息,请参阅身份验证For more information, see Authentication.
    envFQDN 时序见解环境的完全限定域名 (FQDN)The fully qualified domain name (FQDN) for the Time Series Insights environment 通过 Azure 门户。From the Azure portal. 例如:10000000-0000-0000-0000-100000000108.env.timeseries.azure.comFor example: 10000000-0000-0000-0000-100000000108.env.timeseries.azure.com.
    aeTsxArray 时序见解查询表达式的数组An array of Time Series Insights query expressions 如前所述使用 aes 变量:aes.map(function(ae){return ae.toTsx()}Use the aes variable as described earlier: aes.map(function(ae){return ae.toTsx()}.
  4. 将时序见解查询返回的压缩结果转换为 JSON 以进行可视化:Transform the compressed result that's returned from the Time Series Insights query into JSON for visualization:

    var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aes);
    
  5. 使用 TsiClient.UX API 创建图表控件。Create a chart control by using the TsiClient.UX APIs. 将其绑定到页面上的某个 <div> 元素:Bind it to one of the <div> elements on the page:

    var barChart = new tsiClient.ux.BarChart(document.getElementById('chart3'));
    
  6. 在图表控件中填充转换后的 JSON 数据对象,并在页面上呈现该控件:Populate the chart control with the transformed JSON data objects and render the control on the page:

    barChart.render(transformedResult, {grid: true, legend: 'compact', theme: 'light'}, aes);
    

呈现控件Render controls

时序见解客户端库提供八个独特的、开箱即用的分析控件:The Time Series Insights client library provides eight unique, out-of-the-box analytics controls:

  • 折线图line chart
  • 饼图pie chart
  • bar chart
  • heatmapheatmap
  • 层次结构控件hierarchy controls
  • 可访问网格accessible grid
  • 离散事件时间线discrete event timelines
  • 状态转换时间线state transition timelines

折线图、条形图和饼图示例Line chart, bar chart, and pie chart examples

查看用于呈现某些标准图表控件的演示代码。Look at the demo code that's used to render some of the standard chart controls. 请注意用于创建这些控件的编程模型和模式。Note the programming model and patterns for creating those controls. 具体而言,我们将查看 // Example 3/4/5 注释下面的 HTML,其中呈现了 HTML id 值为 chart3chart4chart5 的控件。Specifically, examine the HTML under the // Example 3/4/5 comment, which renders controls with the HTML id values chart3, chart4, and chart5.

回顾页面源代码和结构部分的步骤 3,图表控件在页面上按行排列。Recall from step 3 of the Page source and structure section that chart controls are arranged in rows on the page. 每个图表控件都有一个描述性的标题行。Each chart control has a descriptive title row. 在本示例中,要填充的三个图表都位于 Multiple Chart Types From the Same Data 标题 <div> 元素下面,并已绑定到标题下面的三个 <div> 元素:In this example, the three charts are populated under the Multiple Chart Types From the Same Data title <div> element and are bound to the three <div> elements that are below the title:

<div class="rowOfCardsTitle">Multiple Chart Types From the Same Data</div>
<div class="rowOfCards">
    <div class="card" style="flex-shrink: 1; height: 100%; width: 30%;">
        <div style="color: black; background: white; border-bottom: 1px solid silver;" class="cardTitle">Factory Temps Split by Station as a Line Chart, Light Theme</div>
        <div class="cardChart" id="chart3"></div>
    </div>
    <div class="card" style="flex-shrink: 1; height: 100%; width: 30%;">
        <div class="cardTitle">Factory Temps Split by Station as a Bar Chart</div>
        <div class="cardChart" id="chart4"></div>
    </div>
    <div class="card" style="flex-shrink: 1; height: 100%; width: 30%;">
        <div style="color: black; background: white; border-bottom: 1px solid silver;" class="cardTitle">Factory Temps Split by Station as a Pie Chart, Light Theme</div>
        <div class="cardChart" id="chart5"></div>
    </div>
</div>

以下 JavaScript 代码节使用前面所述的模式:生成时序见解聚合表达式,使用它们来查询时序见解数据,然后呈现三个图表。The following section of JavaScript code uses patterns that were outlined earlier: build Time Series Insights aggregate expressions, use them to query for Time Series Insights data, and then render the three charts. 使用 tsiClient.ux 命名空间中的三个图表类型:LineChartBarChartPieChartThree chart types are used from the tsiClient.ux namespace: LineChart, BarChart, and PieChart. 图表类型用于创建并呈现相应的图表。The chart types are used to create and render the respective charts. 所有三个图表都可以使用相同的聚合表达式数据 transformedResultAll three charts can use the same aggregate expression data transformedResult:

// Example 3/4/5
var aggregateExpressions4 = [];
var startDate = new Date('2017-04-19T13:00:00Z');
var endDate = new Date(startDate.valueOf() + 1000*60*60*1);
aggregateExpressions4.push(new tsiClient.ux.AggregateExpression({predicateString: "Factory = 'Factory3'"}, {property: 'Temperature', type: "Double"}, ['avg', 'min', 'max'],
    { from: startDate, to: endDate, bucketSize: '2m' }, {property: 'Station', type: 'String'}, 'green', 'Factory3Temperature'));
aggregateExpressions4.push(new tsiClient.ux.AggregateExpression({predicateString: "Factory = 'Factory1'"}, {property: 'Temperature', type: "Double"}, ['min', 'avg', 'max'],
    { from: startDate, to: endDate, bucketSize: '3m' }, {property: 'Station', type: 'String'}, 'purple', 'Factory1Temp'));
authContext.getTsiToken().then(function(token){
    tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', aggregateExpressions4.map(function(ae){return ae.toTsx()})).then(function(result){
        var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions4);
        
        var lineChart = new tsiClient.ux.LineChart(document.getElementById('chart3'));
        lineChart.render(transformedResult, {grid: true, legend: 'compact', theme: 'light'}, aggregateExpressions4);
        
        var barChart =  new tsiClient.ux.BarChart(document.getElementById('chart4'));
        barChart.render(transformedResult, {grid: true, timestamp: '2017-04-19T13:00:00Z', legend: 'compact'}, aggregateExpressions4);

        var pieChart =  new tsiClient.ux.PieChart(document.getElementById('chart5'));
        pieChart.render(transformedResult, {grid: true, theme: 'light', timestamp: '2017-04-19T13:00:00Z', arcWidthRatio: .4, legend: 'compact'}, aggregateExpressions4);
    });
});

在呈现时,三个图表如下所示:The three charts appear as follows when rendered:

基于相同数据的多个图表类型Multiple chart types from the same data

了解高级功能Learn about advanced features

时序见解客户端库具有一些其他功能,你可以使用它们创造性地实现数据可视化。The Time Series Insights client library has several additional features that you can use to implement data visualizations creatively.

状态和事件States and events

有一个高级功能是将状态转换和离散事件添加到图表中。An advanced functionality is the ability to add state transitions and discrete events to charts. 此功能可用于突出显示事件、发出警报,以及创建状态开关(例如打开/关闭开关)。This feature is useful for highlighting incidents, alerting, and creating state switches (on/off switches, for example).

查看 // Example 10 注释周围的代码。Look at the code surrounding the // Example 10 comment. 该代码在标题 Line Charts with Multiple Series Types 下面呈现一个线条控件,并将其绑定到 HTML id 值为 chart10<div> 元素。The code renders a line control under the title Line Charts with Multiple Series Types and binds it to the <div> element with the HTML id value chart10.

以下步骤描述了该过程:The following steps describe the process:

  1. 定义一个名为 events4 的结构,用于保存要跟踪的状态更改元素。结构包含:A structure named events4 is defined to hold the state-change elements to track. The structure contains:

    • 名为 Component States 的字符串键。A string key named Component States.
    • 表示状态的值对象数组。An array of value objects that represent the states. 每个对象包括:Each object includes:
      • 包含 JavaScript ISO 时间戳的字符串键。A string key that contains a JavaScript ISO timestamp.
      • 包含状态特征的数组:颜色和说明。An array that contains the characteristics of the state: a color and a description.
  2. 为保存要跟踪的事件元素数组的 Incidents 定义 events5 结构。数组结构的形状与概述的 events4 结构相同。The events5 structure is defined for Incidents, which holds an array of the event elements to track. The array structure is the same shape as the structure that's outlined for events4.

  3. 呈现折线图,并结合图表选项参数传入两个结构:events:states:The line chart is rendered and passes in the two structures with the chart options parameters: events: and states:. 请注意用于指定 tooltip:theme:grid: 的其他选项参数。Note the other option parameters for specifying a tooltip:, theme:, or grid:.

//Example 10
var startDate = new Date('2017-04-19T13:00:00Z');
var endDate = new Date(startDate.valueOf() + 1000*60*60*1);

var events4 = {"Component States" : [
    {
        '2017-04-19T13:05:00Z' : {
            'color': 'lightblue',
            'description' : 'Cooling fan on'
        }
    },
    {
        '2017-04-19T13:27:00Z' : {
            'color': 'yellow',
            'description' : 'Filling tank at maximum pressure'
        }
    },
    {
        '2017-04-19T13:47:00Z' : {
            'color': 'red',
            'description' : 'Pressing machine overheated'
        }
    }
]};

var events5 = {"Incidents" : [
    {
        '2017-04-19T13:12:00Z' : {
            'color': 'Yellow',
            'description' : 'Recoverable failure'
        }
    },
    {
        '2017-04-19T13:25:00Z' : {
            'color': 'red',
            'description' : 'Catastrophic failure'
        }
    },
        {
        '2017-04-19T13:47:00Z' : {
            'color': 'purple',
            'description' : 'Informational event'
        }
    }
]}

authContext.getTsiToken().then(function(token){
    tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', aggregateExpressions4.map(function(ae){return ae.toTsx()})).then(function(result){
        var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions4);
        var lineChart = new tsiClient.ux.LineChart(document.getElementById('chart10'));
        lineChart.render(transformedResult, {tooltip: true, grid: true, theme: "dark", events: [events5], states: [events4]}, aggregateExpressions4);
    });
});

菱形标记/弹出窗口用于指示事件,沿时间刻度显示的彩色条块/弹出窗口指示状态更改:The diamond markers/pop-up windows that are used to indicate incidents and the colored bars/pop-up windows along the time scale indicate state changes:

具有多个序列类型的折线图Line charts with multiple series types

弹出上下文菜单Pop-up context menus

另一个高级功能是能够创建自定义上下文菜单(右键单击弹出菜单)。Another advanced functionality is the ability to create custom context menus (right-click pop-up menus). 自定义的上下文菜单可用于在应用程序范围内启用操作和逻辑后续步骤。Custom context menus are useful for enabling actions and logical next steps within the scope of your application.

查看 // Example 13/14/15 注释周围的代码。Look at the code around the // Example 13/14/15 comment. 此代码最初在标题 Line Chart with Context Menu to Create Pie/Bar Chart 下面呈现折线图。This code initially renders a line chart under the title Line Chart with Context Menu to Create Pie/Bar Chart. 该图表已绑定到 HTML id 值为 chart13<div> 元素。The chart is bound to the <div> element with the HTML id value chart13.

使用上下文菜单可在折线图中动态创建绑定到 ID 为 chart14chart15<div> 元素的饼图和条形图。By using context menus, the line chart provides the capability to dynamically create a pie and bar chart that are bound to <div> elements with the IDs chart14 and chart15. 饼图和条形图也使用上下文菜单来实现其自身的功能:分别是将数据从饼图复制到条形图,以及将条形图数据输出到浏览器控制台窗口中。Both the pie chart and the bar chart also use context menus to enable their own features: the ability to copy data from the pie chart to the bar chart and to print the bar chart data to the browser console window, respectively.

以下步骤描述了该过程:The following steps describe the process:

  1. 定义一系列自定义操作。A series of custom actions are defined. 每个操作包含由一个或多个元素构成的数组。Each action contains an array with one or more elements. 每个元素定义单个上下文菜单项:Each element defines a single context menu item:

    • barChartActions:此操作定义饼图的上下文菜单,该菜单包含一个元素用于定义单个项:barChartActions: This action defines the context menu for the pie chart, which contains one element to define a single item:

      • name:用于菜单项的文本:“将参数输出到控制台。”name: The text that's used for the menu item: "Print parameters to console."
      • action:与菜单项关联的操作。action: The action that's associated with the menu item. 该操作始终是一个匿名函数,根据用于创建图表的聚合表达式采用三个参数。The action is always an anonymous function that takes three arguments that are based on the aggregate expression that's used to create the chart. 在本例中,这些参数将写入浏览器控制台窗口:In this case, the arguments are written to the browser console window:
        • ae:聚合表达式数组。ae: The aggregate expression array.
        • splitBysplitBy 值。splitBy: The splitBy value.
        • timestamp:时间戳。timestamp: The timestamp.
    • pieChartActions:此操作定义条形图的上下文菜单,该菜单包含一个元素用于定义单个项。pieChartActions: This action defines the context menu for the bar chart, which contains one element to define a single item. 形状和架构与前面所述的 barChartActions 元素相同,但 action 函数明显不同:它实例化并呈现条形图。The shape and schema is the same as the barChartActions element described earlier, but the action function is dramatically different: it instantiates and renders the bar chart. ae 参数用于指定聚合表达式数组,在运行时打开菜单项期间,会传递该数组。The ae argument is used to specify the aggregate expression array that's passed at runtime when the menu item opens. 该函数还使用 barChartActions 上下文菜单设置 ae.contextMenu 属性。The function also sets the ae.contextMenu property with the barChartActions context menu.

    • contextMenuActions:此操作定义折线图的上下文菜单,其中包含用于定义三个菜单项的三个元素。contextMenuActions: This action defines the context menu for the line chart, which contains three elements to define three menu items. 每个元素的形状和架构与前面所述的元素相同。The shape and schema for each element is the same as the elements that were described earlier. barChartActions 元素一样,第一个项将三个函数参数写入浏览器控制台窗口。Just like the barChartActions element, the first item writes the three function arguments to the browser console window. pieChartActions 元素一样,另外的两个项分别实例化并呈现饼图和条形图。Similar to the pieChartActions element, the second two items instantiate and render the pie chart and bar chart, respectively. 此外,另外的两个项分别使用 pieChartActionsbarChartActions 上下文菜单设置其 ae.contextMenu 属性。The second two items also set their ae.contextMenu properties with the pieChartActions and barChartActions context menus, respectively.

  2. 将两个聚合表达式推送到 aes 聚合表达式数组。Two aggregate expressions are pushed onto the aes aggregate expression array. 它们为每个项指定 contextMenuActions 数组。They specify the contextMenuActions array for each item. 将在折线图控件中使用这些表达式。These expressions are used with the line chart control.

  3. 一开始只呈现折线图,在运行时,即可从折线图呈现饼图和条形图。Only the line chart is initially rendered, from which both the pie chart and the bar chart can be rendered at runtime.

// example 13/14/15
// Line chart with a context menu which generates pie and bar chart
var aggregateExpressions9 = [];
var pieChart2 = new tsiClient.ux.PieChart(document.getElementById('chart14'));
var barChart2 = new tsiClient.ux.BarChart(document.getElementById('chart15'));

var barChartActions = [{
    name: "Print parameters to console",
    action: function(ae, splitBy, timestamp) {
        console.log(ae);
        console.log(splitBy);
        console.log(timestamp);
    }
}];

var pieChartActions = [{
    name: "Copy to Bar Chart",
    action: function(ae, splitBy, timestamp) {
        ae.contextMenu = barChartActions;
        authContext.getTsiToken().then(function(token){
            tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', [ae].map(function(ae){return ae.toTsx()})).then(function(result){
                var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, [ae]); 
                barChart2.render(transformedResult, {grid: true, theme: 'light', timestamp: timestamp, arcWidthRatio: .6}, [ae]);
            });
        });
    }
}]

var contextMenuActions = [{
    name: "Print parameters to console",
    action: function(ae, splitBy, timestamp) {
        console.log(ae);
        console.log(splitBy);
        console.log(timestamp);
    }
}, 
{
    name: "Plot as a Pie Chart",
    action: function(ae, splitBy, timestamp) {
        ae.contextMenu = pieChartActions;
        authContext.getTsiToken().then(function(token){
            tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', [ae].map(function(ae){return ae.toTsx()})).then(function(result){
                var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, [ae]); 
                pieChart2.render(transformedResult, {grid: true, theme: 'light', timestamp: timestamp, arcWidthRatio: .6}, [ae]);
            });
        });
    }
}, {
    name: "Plot as a Bar Chart",
    action: function(ae, splitBy, timestamp) {
        ae.contextMenu = barChartActions;
        authContext.getTsiToken().then(function(token){
            tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', [ae].map(function(ae){return ae.toTsx()})).then(function(result){
                var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, [ae]); 
                barChart2.render(transformedResult, {grid: true, theme: 'light', timestamp: timestamp }, [ae]);
            });
        });
    }
}];

aggregateExpressions9.push(new tsiClient.ux.AggregateExpression({predicateString: "Factory = 'Factory3'"}, {property: 'Temperature', type: "Double"}, ['avg', 'min'],
    { from: startDate, to: endDate, bucketSize: '2m' }, {property: 'Station', type: 'String'}, 'pink', 'Factory3Temperature', contextMenuActions));
aggregateExpressions9.push(new tsiClient.ux.AggregateExpression({predicateString: "Factory = 'Factory1'"}, {property: 'Temperature', type: "Double"}, ['avg', 'min'],
    { from: startDate, to: endDate, bucketSize: '2m' }, {property: 'Station', type: 'String'}, 'green', 'Factory1Temperature', contextMenuActions));

var brushActions = [{
    name: "Print parameters to console",
    action: function(fromTime, toTime) {
        console.log(fromTime);
        console.log(toTime);
    }
}];

authContext.getTsiToken().then(function(token){
    tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', aggregateExpressions9.map(function(ae){return ae.toTsx()})).then(function(result){
        var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions9);
        var lineChart = new tsiClient.ux.LineChart(document.getElementById('chart13'));
        lineChart.render(transformedResult, {theme: "light", legend: "compact", brushContextMenuActions: brushActions, grid: true, snapBrush: true}, aggregateExpressions9);
    });
});

下面的屏幕截图显示了这些图表及其各自的弹出上下文菜单。The following screenshot shows the charts with their respective pop-up context menus. 饼图和条形图是使用折线图上下文菜单选项动态创建的。The pie chart and bar chart were created dynamically by using the line chart context menu options.

包含用于创建饼图和条形图的上下文菜单的折线图Line chart with context menu to create pie chart and bar chart

画笔Brushes

可以使用画笔限定定义操作(例如缩放和浏览)的时间范围。You can use brushes to scope a time range to define actions like zoom and explore.

描述弹出上下文菜单的 Line Chart with Context Menu to Create Pie/Bar Chart 示例中显示了用于演示画笔的代码。The code that's used to illustrate brushes is shown in the Line Chart with Context Menu to Create Pie/Bar Chart example that describes pop-up context menus.

  • 画笔操作类似于上下文菜单,为画笔定义一系列自定义操作。Brush actions are similar to a context menu in that they define a series of custom actions for the brush. 每个操作均包含一个由一个或多个元素构成的数组。Each action contains an array that has one or more elements. 每个元素定义单个上下文菜单项:Each element defines a single context menu item:

    • name:用于菜单项的文本:“将参数输出到控制台。”name: The text that's used for the menu item: "Print parameters to console."
    • action:与菜单项关联的操作,始终是采用两个参数的匿名函数。action: The action that's associated with the menu item, which is always an anonymous function that takes two arguments. 在本例中,这些参数将写入浏览器控制台窗口:In this case, the arguments are written to the browser console window:
      • fromTime:画笔选项的 from 时间戳。fromTime: The from timestamp of the brush selection.
      • toTime:画笔选项的 to 时间戳。toTime: The to timestamp of the brush selection.
  • 画笔操作将添加为另一个图表选项属性。Brush actions are added as another chart option property. brushContextMenuActions: brushActions 属性传递给 linechart.Render 调用。The brushContextMenuActions: brushActions property is passed to the linechart.Render call.

var brushActions = [{
    name: "Print parameters to console",
    action: function(fromTime, toTime) {
        console.log(fromTime);
        console.log(toTime);
    }
}];

authContext.getTsiToken().then(function(token){
    tsiClient.server.getAggregates(token, '10000000-0000-0000-0000-100000000108.env.timeseries.azure.com', aggregateExpressions9.map(function(ae){return ae.toTsx()})).then(function(result){
        var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions9);
        var lineChart = new tsiClient.ux.LineChart(document.getElementById('chart13'));
        lineChart.render(transformedResult, {theme: "light", legend: "compact", brushContextMenuActions: brushActions, grid: true, snapBrush: true}, aggregateExpressions9);
    });
});

包含用于通过画笔创建饼图和条形图的上下文菜单的折线图Line chart with context menu to create pie chart and bar chart by using brushes

清理资源Clean up resources

现在你已完成本教程,请清除已创建的资源:Now that you've completed the tutorial, clean up the resources you created:

  1. Azure 门户的左侧菜单中,选择“所有资源” ,找到“Azure 时序见解”资源组。From the left menu in the Azure portal, select All resources, locate your Azure Time Series Insights resource group.
  2. 通过选择“删除” 来删除整个资源组(以及其中包含的所有资源),或者单独删除每个资源。Either delete the entire resource group (and all resources contained within it) by selecting Delete or remove each resource individually.

后续步骤Next steps

在本教程中,你已学习了如何执行以下操作:In this tutorial, you learned how to:

  • 登录到时序见解示例应用程序并探索其源代码Sign in and explore the Time Series Insights sample application and its source
  • 使用时序见解 JavaScript 客户端库中的 APIUse APIs in the Time Series Insights JavaScript client library
  • 使用 JavaScript 创建图表控件并在其中填充时序见解数据Use JavaScript to create and populate chart controls with Time Series Insights data

时序见解示例应用程序使用演示数据集。The Time Series Insights sample application uses a demo dataset. 若要了解如何创建自己的时序见解环境和数据集,请阅读下文:To learn how you can create your own Time Series Insights environment and dataset, read the following article:

或查看时序见解示例应用程序源文件:Or, view the Time Series Insights sample application source files:

请阅读时序见解客户端 API 参考文档:Read the Time Series Insights client API reference documentation: