Oracle olap что это
Когда Дмитрий Волков предложил мне выступить на семинаре Database Options Details с рассказом про OLAP опцию в 11g, я сначала подумал - да о чем тут рассказывать? Между девятой и десятой версией было много различий. А между 10 и 11 вроде ничего особо не было. Ну, кроме Cube-Organized Materialized Views. Потом решил, что на семинаре будет масса людей, которые вообще с OLAP не работали, ни с какой версией, поэтому им, возможно, будет интересно узнать об OLAP вообще. Заодно при подготовке и посмотрю внимательнее, что там изменилось. Но оказалось, что изменений неожиданно много.
В этой статье я ориентируюсь на людей, которые уже знакомы с Oracle Express или Oracle OLAP, ну или хотя бы в общих чертах представляет, что это. Для начального ознакомления предлагаю почитать мои статьи "Что такое OLAP" (Часть 1 Часть 2)
Интеграция метаданных с Oracle Database
Первое, что бросилось в глаза, это то, что действительно через любой SQL инструмент теперь стало очень удобно смотреть на данные, лежащие в OLAP кубах. Причем, как только вы создаете какой-то объект с помощью Analytic Workspace Manager (AWM) (показатель, измерение и т.д.) он тут же становится виден из SQL. Для этого автоматически создается обвязка из VIEW, каждый из которых содержит вызов CUBE_TABLE. Выглядит это примерно так:
GLOBAL.UNITS_CUBE - это указание на то, что данные лежат в кубе UNITS_CUBE, который создавался в AWM. А CUBE_TABLE - табличная функция, такой универсальный вызов данных из объектов, лежащих в аналитическом прострастве.
В 10й версии тоже была возможность увидеть данные через SQL. Для этого была табличная функция OLAP_TABLE. (Собственно, она и сейчас есть, но смысла ее использовать, наверное, не очень много) Но чтобы заставить ее работать, нужно было предварительно создать кучу разных абстрактных типов данных, описания LIMITMAP и проч. Причем можно было ошибиться на любом шаге. В общем, для начинающих совершенно не подходило. Даже был такой плагин к AWM, который эти типы мог создать сам, что, в общем, частично проблему решало. Сейчас ничего делать не надо. Для каждого измерения и куба есть соответствующая вьюшка. Вы можете легко делать запросы к этим VIEW для того, чтобы например, фильтровать измерения по атрибутам. То есть, в вашем SQL запросе будут объединяться вьюшки измерений и куба, а оптимизатор сам знает как весь этот запрос протолкнуть через CUBE_TABLE внутрь OLAP движка, где он и будет отработан. Более того, никто не запрещает объединять данные из OLAP с данными из реляционки в любом запросе. Например, для того чтобы соединить агрегированные данные с детальными.
Кроме того, в 10g вызовы OLAP_TABLE работали довольно медленно. В 11g разница в скорости заметна невооруженным глазом. Причем, встроенная смотрелка AWM работает достаточно медленно, но если такой же запрос выполнить из SQL, он работает гораздо быстрее. Что говорит скорее всего о том, что смотрелка AWM генерирует запросы не так, или медленно обрабатывает результаты. Вообще, при желании это можно оттрассировать, но мне пока не хватило времени.
Увеличение скорости работы SQL связано с тем, что теперь обработка запросов оптимизатором сделана более умно и фильтрация значений по измерениям происходит внутри аналитического пространства, то есть в движке OLAP, а не в самом Oracle, как это было в 10g. Если сравнить запрос SQL и аналогичный ему DML запрос выполнять из OLAP Worksheet, то разница в скорости не заметна. То есть, SQL отрабатыват примерно также как и запрос непосредственно к движку.
Можно сделать вывод, что связка SQL - CUBE_TABLE - стала вполне пригодной для того, чтобы пользоваться ей для доступа к OLAP.
Как следствие, к данным OLAP можно обращаться любым ROLAP инструментом, например Oracle Business Intelligence Enterprise Edition, который работает с базой Oracle через SQL. Другие API не обязательны.
При этом, любые манипуляции с движком OLAP, если это необходимо, можно делать используя пакет DBMS_AW.
Упрощение стандартной формы
Когда я запустил новый AWM, оказалось, что в нем исчезла возможность смотреть структуру AW в режиме Object View.
Тут надо сделать небольшое отступление.
В Oracle Express были пользовательские объекты. Были и внутренние объекты, хранящие метаданные, которые физически были реализованы объектами Express, такими как измерения, отношения, переменные и и.д. Но внутренние были в основном скрыты от конечного пользователя. Да и большой небходимости в них залезать не было. В 9й версии, когда OLAP стал частью СУБД Oracle, сначала все оставалось, как было в Express, но потом, в районе 9.2.0.4 (точно не помню) была придумана так называемая стандартная форма (Standard Form, SF)
Это специальная обвязка метаданных, нужная для интеграции с СУБД Oracle. Но проблема в том, что те объекты, которые создавались в AWM и которые пользователь считал измерениями, показателями и т.д., на самом деле физически лежат совершенно в других объектах, а добраться до них можно было лишь расшифорвав сложный слой метаданных SF. А SF сама по себе менялась с каждым патчсетом. Express всегда славился своим очень гибким языком, который сейчас называется OLAP DML. На нем можно было написать очень сложные расчетные формулы и программы, для работы с многомерными объектами. Но сложность SF по сути убивала эту возможность, так как было довольно сложно расшифровывать метаданные, к тому же, велика вероятность, что в следующем релизе что-то поменяется и ваша программа перестанет работать. А SF считается объектом внутренним и поддержка прошлых версий SF не гарантируется.
Поэтому, в AWM прошлых версий было два вида представления объектов OLAP - Model View и Object View. Model View показывал как объекты выглядят через призму SF, Object View - как они хранятся на самом деле. Что и говорить, найти соответствия между двумя предствлениями было очень сложно.
В 11 версии все стало гораздо проще. Создаем мы из AWM куб UNITS_CUBE, а в нем показатель SALES. Теперь в OLAP DML мы можем увидеть объект UNITS_CUBE_SALES, название которого составлено из названия куба и названия показателя. Это же распространяется и на вычисляемые показатели. У нас теперь опять есть простой путь использования наших показателей в формулах и программах. И не важно, что на самом деле, это не куб, а формула, которая смотрит на другой объект. Для нас уже не важно знать, как именно он хранится.
Хотя, если кому интересно, можно и посмотреть:
Напомню, что через SQL тот же куб можно увидеть через вьюшку UNITS_CUBE_VIEW, а показатель SALES соответственно будет UNITS_CUBE_VIEW.SALES
И вот тут видно основное отличие данных, которые достаются из OLAP от данных, которые берутся из обычных таблиц Oracle. Обратите внимание на первую строчку, где четыре слова "TOTAL". В этой строке - агрегат (сумма) по продажам по всем измерениям. Если бы мы хотели достать сумму по всем измерениям из обычной таблицы, нам нужно было написать что-то вроде
А OLAP уже выдает все возможные агрегаты, поэтому вместо суммирования, нам нужно в условиях SQL запроса WHERE описать фильтр этой строки. Само суммирование делать не надо. Сумму уже посчитал OLAP сервер.
Это естественно накладывает некоторые условия на программирование SQL над OLAP. Например, в том же BI EE нужно специальным образом описать правила обсчета уровней иерархий, что бы не пошло суммирование по уже агрегированным данным.
Вторая тонкость в том, что если я напишу запрос по данным о продаже определенного продукта, и не укажу условия по другим измерениям, то из таблицы фактов мне выпадут все продажи этого продкута. Но если тоже самое сделать над OLAP, то кроме фактов детального уровня выйдут и все возможные комбинации агрегатов по разным измерениям, что в зависимости от структуры куба может быть объемом в десятки раз превышающим количество детальных фактов.
Иными словами, когда вы пишете запрос к OLAP нужно всегда ограничивать все измерения
This chapter describes the preliminary steps you should take to use Oracle OLAP. It assumes that you have installed Oracle Database 12 c Enterprise Edition. The OLAP option is installed automatically as part of a Basic installation of Oracle Database.
To start querying dimensional objects immediately, install the Global analytic workspace, as described in "Installing the Sample Schema" . Then follow the instructions in Querying Dimensional Objects.
This chapter includes the following topics:
2.1 Installing the Sample Schema
You can download and install the sample Global schema from the Oracle website and use it to try the examples shown throughout this guide:
Instructions for installing the schema are provided in the README file.
2.2 Database Management Tasks
You should create undo, permanent, and temporary tablespaces that are appropriate for use by dimensional objects. Follow the recommendations in "Storage Management" .
2.3 Granting Privileges to DBAs and Application Developers
Anyone who must create or manage dimensional objects in Oracle Database needs the necessary privileges. These privileges are different from those needed just to query the data stored in dimensional objects. The security system is discussed in Security.
DBAs and application developers need the following roles and privileges.
To create dimensional objects in the user's own schema:
CREATE SESSION privilege
To create dimensional objects in different schemas:
CREATE SESSION privilege
To administer data security:
To create cube materialized views in the user's own schema:
CREATE MATERIALIZED VIEW privilege
CREATE DIMENSION privilege
To create cube materialized views in different schemas:
CREATE ANY MATERIALIZED VIEW privilege
CREATE ANY DIMENSION privilege
Users also need an unlimited quota on the tablespace in which the dimensional objects are stored. The tablespaces should be defined specifically for OLAP use, as described in Administering Oracle OLAP.
If the source tables are in a different schema, then the owner of the dimensional objects must have READ or SELECT object privileges on those tables.
Example 2-1 shows the SQL statements for creating the GLOBAL user.
Example 2-1 SQL Statements for Creating the GLOBAL User
2.4 Getting Started with Analytic Workspace Manager
In this section, you learn how to install Analytic Workspace Manager software and make a connection to Oracle Database.
2.4.1 Installing Analytic Workspace Manager
Analytic Workspace Manager is distributed on the Oracle Database Client installation disk.
If you are installing on the same system as the database, then select a Custom installation and install into the same Oracle home directory as the database. Select OLAP Analytic Workspace Manager and Worksheet from the list of components.
If you are installing on a remote system, then select either an Administrator or a Custom installation. The Administrator choice automatically installs Analytic Workspace Manager on the client.
The installation guide for your client platform.
2.4.2 Opening Analytic Workspace Manager
Use the appropriate procedure for your platform.
On Windows, to open Analytic Workspace Manager:
From the Start menu, select Oracle - Oracle_home , then Integrated Management Tools , and then OLAP Analytic Workspace Manager and Worksheet .
On Linux, to open Analytic Workspace Manager:
From the shell command line, enter this command:
Figure 2-1 shows the initial display.
Figure 2-1 Opening Analytic Workspace Manager
If Analytic Workspace Manager does not have access to the Internet, the property viewer shows links to several useful sites. It also shows an exception, because Analytic Workspace Manager cannot display the OLAP home page. To connect to the Internet, you typically need to identify the proxy server.
To identify the proxy server:
From the Tools menu, select Configuration to display the Configuration dialog box.
Under OLAP Home Page Settings, enter the address of the proxy server.
Enter the port number for the proxy server, if it is not default port 80.
Click OK to save these settings. The OLAP Home page appears the next time you start Analytic Workspace Manager.
2.4.3 Defining a Database Connection
You can define a connection to each database that you use for OLAP. After you define a connection, the database instance is listed in the navigation tree for you to access at any time.
To define a database connection:
Right-click the top Databases folder in the navigation tree, then select New Database Connection from the shortcut menu.
Complete the New Database Connection dialog box.
Figure 2-2 shows the connection information on the General tab of the New Database Connection dialog box.
Figure 2-2 Defining a Database Connection
2.4.4 Opening a Database Connection
To connect to a database:
Click the plus icon (+) next to a database connection in the navigation tree.
Supply your database user name and password in the Connect to Database dialog box.
2.4.5 Showing the Analytic Workspace Attachment Modes
You can specify an analytic workspace attachment mode when you open an analytic workspace. The modes are the following:
In this mode a user can view the analytic workspace objects and data but cannot create or change objects. The user can export an object by copying it or saving it as a template. Any number of users can open an analytic workspace in Read Only mode.
In this mode a user can view the analytic workspace objects and data and create or change objects. The user can export or import an object. Only one user can open an analytic workspace in Read Write mode but any number of other users can open it in Read Only mode. This is the default mode.
Read Write Exclusive
In this mode a user has the same access rights as in Read Write mode but no one else can open the analytic workspace. This mode is not available if another user has the analytic workspace open.
To specify showing attachment modes:
From the Tools menu, select Configuration .
The Configuration dialog box opens.
Select Show Analytic Workspace Attachment Options . Click OK .
2.4.6 Installing Plug-ins
Plug-ins extend the functionality of Analytic Workspace Manager. Plug-ins are distributed as JAR files. Any Java developer can create a plug-in. The developer should provide information about what the plug-in does and how to use it.
If you have one or more plug-ins, then you must identify their location to Analytic Workspace Manager.
Create a local directory for storing the plug-ins.
Copy the JAR files to that directory.
Open Analytic Workspace Manager.
Select Configuration from the Tools menu.
The Configuration dialog box opens.
Select Enable Plugins and identify the plug-in directory. Click OK .
Close and reopen Analytic Workspace Manager.
The functionality provided by the plug-ins is available in the navigator.
To see a list of the currently installed plug-ins:
On the Help menu, click About and then click Plugins .
Some Analytic Workspace Manager plug-ins are available for download from the Oracle Technology Network (OTN).
To download plug-ins from OTN:
In a web browser, go the Oracle OLAP Downloads page at
2.5 Upgrading Metadata From Oracle OLAP 10 g
You can upgrade an Oracle OLAP 10 g analytic workspace to OLAP 11 g or 12 c by saving the objects as an XML template and importing the XML into a different schema. The original analytic workspace remains accessible and unchanged by the upgrade process.
The OLAP 10 g analytic workspace can use OLAP standard form metadata.
The original relational source data must be available to load into the new analytic workspace. If the data is in a different schema or the table names are different, then you must remap the dimensional objects to the new relational sources after the upgrade.
You can create the OLAP 12 c analytic workspace in the same schema as the OLAP 10 g analytic workspace. However, if you choose to create the OLAP 12 c analytic workspace in a different schema, you must grant the new user the appropriate privileges as described in "Granting Privileges to DBAs and Application Developers" .
To upgrade an OLAP 11 g analytic workspace:
Open Analytic Workspace Manager for Oracle Database 12 c Release 1.
If necessary, create a new database connection to the database instance with the analytic workspace. See "Defining a Database Connection" .
Open the database connection. On the Connect to Database dialog box, select OLAP 11g/12c for the Cube Type. See "Opening a Database Connection" .
Expand the navigation tree until the name of the analytic workspace appears.
Right-click the analytic workspace and select Create 12c Upgrade Template for 11g Analytic Workspace . Save the XML template to a file.
The Create 12c Upgrade Template for 12 c Analytic Workspace dialog box appears if any subobjects, such as a level and a hierarchy, have the same name.
Duplicate object names are changed automatically for the upgrade. You cannot edit the names now, but you can change them later.
Click Close to close the dialog box.
Right-click the connection in the tree and select Disconnect Database .
Right-click the connection again and select Connect Database .
On the Connect to Database dialog box, log in with the new user name and select OLAP 11g/12c for the Cube Type.
Expand the tree, right-click Analytic Workspaces under the new schema, and select Create Analytic Workspace From Template .
Open the upgrade template that you created previously.
The Correct Duplicate Names From Analytic Workspace Template Import dialog box appears if any objects, such as a cube, dimensions, or the analytic workspace, duplicate object names that already exist in the schema.
Enter new names to resolve any conflicts, then click OK .
Before loading the data, you may want to browse the dimensional objects and make any changes to the object names, cube partitioning, or aggregation strategy.
Load data into the new analytic workspace as described in "Loading Data Into Cubes" . Select all objects for maintenance.
This chapter introduces the powerful analytic resources available in the Oracle Database with the OLAP option. It consists of the following topics:
1.1 OLAP Technology in the Oracle Database
Oracle Database offers the industry's first and only embedded OLAP server. Oracle OLAP provides native multidimensional storage and speed-of-thought response times when analyzing data across multiple dimensions. The database provides rich support for analytics such as time series calculations, forecasting, advanced aggregation with additive and nonadditive operators, and allocation operators. These capabilities make the Oracle database a complete analytical platform, capable of supporting the entire spectrum of business intelligence and advanced analytical applications.
1.1.1 Full Integration of Multidimensional Technology
By integrating multidimensional objects and analytics into the database, Oracle provides the best of both worlds: the power of multidimensional analysis along with the reliability, availability, security, and scalability of the Oracle database.
Oracle OLAP is fully integrated into Oracle Database. At a technical level, this means:
Cubes and other dimensional objects are first class data objects represented in the Oracle data dictionary.
Cubes and other dimensional objects are supported by standard SQL syntax in the CREATE, ALTER, DROP, and SELECT statements.
The OLAP engine runs within the kernel of Oracle Database.
Dimensional objects are stored in Oracle Database in their native multidimensional format.
Data security is administered in the standard way, by granting and revoking privileges to Oracle Database users and roles.
The benefits to your organization are significant. Oracle OLAP offers the power of simplicity: One database, standard administration and security, standard interfaces and development tools.
1.1.2 Ease of Application Development
Oracle OLAP makes it easy to enrich your database and your applications with interesting analytic content. Native SQL access to Oracle multidimensional objects and calculations greatly eases the task of developing dashboards, reports, business intelligence (BI) and analytical applications of any type compared to systems that offer proprietary interfaces. Moreover, SQL access means that the power of Oracle OLAP analytics can be used by any database application, not just by the traditional, limited collection of OLAP applications.
1.1.3 Ease of Administration
Because Oracle OLAP is completely embedded in the Oracle database, there is no administration learning curve as is typically associated with standalone OLAP servers. You can leverage your existing DBA staff, rather than invest in specialized administration skills.
A major administrative advantage of Oracle's embedded OLAP technology is automated cube maintenance. With standalone OLAP servers, the burden of refreshing the cube is entirely the responsibility of the administrator. This can be a complex and potentially error-prone job. You must create procedures to extract the changed data from the relational source, move the data from the source system to the system running the standalone OLAP server, load and rebuild the cube. You must take responsibility for the security of the deltas (changed values) during this process as well.
With Oracle OLAP, in contrast, cube refresh is handled entirely by the Oracle database. The database tracks the staleness of the dimensional objects, automatically keeps track of the deltas in the source tables, and automatically applies only the changed values during the refresh process. You simply schedule the refresh at appropriate intervals, and Oracle Database takes care of everything else.
1.1.4 Security
With Oracle OLAP, standard Oracle Database security features are used to secure your multidimensional data.
In contrast, with a standalone OLAP server, administrators must manage security twice: once on the relational source system and again on the OLAP server system. Additionally, they must manage the security of data in transit from the relational system to the standalone OLAP system.
1.1.5 Unmatched Performance and Scalability
Business intelligence and analytical applications are dominated by actions such as drilling up and down hierarchies and comparing aggregate values such as period-over-period, share of parent, projections onto future time periods, and a myriad of similar calculations. Often these actions are essentially random across the entire space of potential hierarchical aggregations. Because Oracle OLAP precomputes or efficiently computes as needed all aggregates in the defined multidimensional space, it delivers unmatched performance for typical business intelligence applications.
Oracle OLAP queries take advantage of Oracle shared cursors, dramatically reducing memory requirements and increasing performance.
When Oracle Database is installed with Real Application Clusters (Oracle RAC), OLAP applications receive the same benefits in performance, scalability, fail over, and load balancing as any other application.
1.1.6 Reduced Costs
All these features add up to reduced costs. Administrative costs are reduced because existing personnel skills can be leveraged. Moreover, the Oracle database can manage the refresh of dimensional objects, a complex task left to administrators in other systems. Standard security reduces administration costs as well. Application development costs are reduced because the availability of a large pool of application developers who are SQL knowledgeable, and a large collection of SQL-based development tools means applications can be developed and deployed more quickly. Any SQL-based development tool can take advantage of Oracle OLAP. Hardware costs are reduced by Oracle OLAP's efficient management of aggregations, use of shared cursors, and Oracle RAC, which enables highly scalable systems to be built from low-cost commodity components.
1.2 Developing Reports and Dashboards Using SQL Tools and Application Builders
Analysts can choose any SQL query and analysis tool for selecting, viewing, and analyzing the data. You can use your favorite tool or application, or use a tool supplied with Oracle Database.
Figure 1-1 displays a portion of a dashboard created in Oracle Application Express, which is distributed with Oracle Database. Application Express generates HTML reports that display the results of SQL queries. It only understands SQL; it has no special knowledge of dimensional objects.
This dashboard demonstrates information-rich calculations such as ratio, share, prior period, and cumulative total. Separate tabs on the dashboard present Profitability Analysis, Sales Analysis, and Product Analysis. Each tab presents the data in dials, bar charts, horizontal bar charts, pie charts, and cross-tabular reports. A drop-down list in the upper left corner provides a choice of Customers.
The dial displays the quarterly profit margin. To the right is a bar chart that compares current profits with year-ago profits.
Figure 1-1 Dashboard Created in Oracle Application Express
The pie chart in Figure 1-2 displays the percent share that each product family contributed to the total profits in the last quarter.
Figure 1-2 Contributions of Product Families to Total Profits
The horizontal bar chart in Figure 1-3 displays ranked results for locations with the largest gains in profitability from a year ago. Decision makers can see at a glance how each location improved by the last quarter.
Figure 1-3 Ranking of Percent Change in Year-to-Date Profits From Year Ago
Figure 1-4 compares current profits with year-to-date, year-to-date year ago, the change between year-to-date and year-to-date year ago, and percent change between year-to-date and year-to-date year-ago profits. The cross-tabular report features interactive drilling, so that decision makers can easily see the detailed data that contributed to a parent value of interest.
Figure 1-4 Year-to-Date Profits Compared to Year Ago
1.3 Overview of the Dimensional Data Model
Dimensional objects are an integral part of OLAP. Because OLAP is on-line, it must provide answers quickly; analysts pose iterative queries during interactive sessions, not in batch jobs that run overnight. And because OLAP is also analytic, the queries are complex. The dimensional objects and the OLAP engine are designed to solve complex queries in real time.
The dimensional objects include cubes, measures, dimensions, attributes, levels, and hierarchies. The simplicity of the model is inherent because it defines objects that represent real-world business entities. Analysts know which business measures they are interested in examining, which dimensions and attributes make the data meaningful, and how the dimensions of their business are organized into levels and hierarchies.
Figure 1-5 shows the general relationships among dimensional objects.
Figure 1-5 Diagram of the OLAP Dimensional Model
The dimensional data model is highly structured. Structure implies rules that govern the relationships among the data and control how the data can be queried. Cubes are the physical implementation of the dimensional model, and thus are highly optimized for dimensional queries. The OLAP engine leverages this innate dimensionality in performing highly efficient cross-cube joins for inter-row calculations, outer joins for time series analysis, and indexing. Dimensions are pre-joined to the measures. The technology that underlies cubes is based on an indexed multidimensional array model, which provides direct cell access.
The OLAP engine manipulates dimensional objects in the same way that the SQL engine manipulates relational objects. However, because the OLAP engine is optimized to calculate analytic functions, and dimensional objects are optimized for analysis, analytic and row functions can be calculated much faster in OLAP than in SQL.
The dimensional model enables Oracle OLAP to support high-end business intelligence tools and applications such as OracleBI Discoverer Plus OLAP, OracleBI Spreadsheet Add-In, OracleBI Suite Enterprise Edition, BusinessObjects Enterprise, and Cognos ReportNet.
1.3.1 Cubes
Cubes provide a means of organizing measures that have the same shape, that is, they have the exact same dimensions. Measures in the same cube can easily be analyzed and displayed together.
A cube usually corresponds to a single fact table or view.
1.3.2 Measures
Measures populate the cells of a cube with the facts collected about business operations. Measures are organized by dimensions, which typically include a Time dimension.
An analytic database contains snapshots of historical data, derived from data in a transactional database, legacy system, syndicated sources, or other data sources. Three years of historical data is generally considered to be appropriate for analytic applications.
Measures are static and consistent while analysts are using them to inform their decisions. They are updated in a batch window at regular intervals: weekly, daily, or periodically throughout the day. Some administrators refresh their data by adding periods to the time dimension of a measure, and may also roll off an equal number of the oldest time periods. Each update provides a fixed historical record of a particular business activity for that interval. Other administrators do a full rebuild of their data rather than performing incremental updates.
A critical decision in defining a measure is the lowest level of detail. Users may never view this detail data, but it determines the types of analysis that can be performed. For example, market analysts (unlike order entry personnel) do not need to know that Beth Miller in Ann Arbor, Michigan, placed an order for a size 10 blue polka-dot dress on July 6, 2006, at 2:34 p.m. But they might want to find out which color of dress was most popular in the summer of 2006 in the Midwestern United States.
The base level determines whether analysts can get an answer to this question. For this particular question, Time could be rolled up into months, the Customer dimension could be rolled up into regions, and the Product dimension could be rolled up into items (such as dresses) with an attribute of color. However, this level of aggregate data could not answer the question: At what time of day are women most likely to place an order? An important decision is the extent to which the data has been aggregated before being loaded into a data warehouse.
Calculated measures return values that are computed at run time from data stored in one or more measures. Like relational views, calculated measures store queries against data stored in other objects. Because calculated measures do not store data, you can create dozens of them without increasing the size of the database. You can use them as the basis for defining other calculated measures, which adds depth to the types of calculations you can create.
1.3.3 Dimensions
Dimensions contain a set of unique values that identify and categorize data. They form the edges of a cube, and thus of the measures within the cube. Because measures are typically multidimensional, a single value in a measure must be qualified by a member of each dimension to be meaningful. For example, the Sales measure has four dimensions: Time, Customer, Product, and Channel. A particular Sales value (43,613.50) only has meaning when it is qualified by a specific time period (Feb-06), a customer (Warren Systems), a product (Portable PCs), and a channel (Catalog).
Base-level dimension values correspond to the unique keys of a fact table.
A measure dimension is a dimension that has measures as dimension members. With a measure dimension, you can generate calculated measures for all of the measures in the cube simultaneously. Also, you do not have to create a new set of calculated measures for each measure that you add to the cube. The existing calculated measures apply to the new measure in the measure dimension. This is especially useful if you create new measures frequently.
1.3.4 Hierarchies and Levels
A hierarchy is a way to organize data at different levels of aggregation. In viewing data, analysts use d imension hierarchies to recognize trends at one level, drill down to lower levels to identify reasons for these trends, and roll up to higher levels to see what affect these trends have on a larger sector of the business.
1.3.4.1 Level-Based Hierarchies
Each level represents a position in the hierarchy. Each level above the base (or most detailed) level contains aggregate values for the levels below it. The members at different levels have a one-to-many parent-child relation . For example, Q1-05 and Q2-05 are the children of 2005 , thus 2005 is the parent of Q1-05 and Q2-05 .
Suppose a data warehouse contains snapshots of data taken three times a day, that is, every 8 hours. Analysts might normally prefer to view the data that has been aggregated into days, weeks, quarters, or years. Thus, the Time dimension needs a hierarchy with at least five levels.
Similarly, a sales manager with a particular target for the upcoming year might want to allocate that target amount among the sales representatives in his territory; the allocation requires a dimension hierarchy in which individual sales representatives are the child values of a particular territory.
Hierarchies and levels have a many-to-many relationship. A hierarchy typically contains several levels, and a single level can be included in multiple hierarchies.
Each level typically corresponds to a column in a dimension table or view. The base level is the primary key.
1.3.4.2 Value-Based Hierarchies
Although hierarchies are typically composed of named levels, they do not have to be. The parent-child relations among dimension members may not define meaningful levels. For example, in an employee dimension, each manager has one or more reports, which forms a parent-child relation. Creating levels based on these relations (such as individual contributors, first-level managers, second-level managers, and so forth) may not be meaningful for analysis. Likewise, the line item dimension of financial data does not have levels. This type of hierarchy is called a value-based hierarchy.
1.3.5 Attributes
An attribute provides additional information about the data. Some attributes are used for display. For example, you might have a product dimension that uses Stock Keeping Units (SKUs) for dimension members. The SKUs are an excellent way of uniquely identifying thousands of products, but are meaningless to most people if they are used to label the data in a report or a graph. You would define attributes for the descriptive labels.
You might also have attributes like colors, flavors, or sizes. This type of attribute can be used for data selection and answering questions such as: Which colors were the most popular in women's dresses in the summer of 2005? How does this compare with the previous summer?
Time attributes can provide information about the Time dimension that may be useful in some types of analysis, such as identifying the last day or the number of days in each time period.
Each attribute typically corresponds to a column in dimension table or view.
Когда Дмитрий Волков предложил мне выступить на семинаре Database Options Details с рассказом про OLAP опцию в 11g, я сначала подумал - да о чем тут рассказывать? Между девятой и десятой версией было много различий. А между 10 и 11 вроде ничего особо не было. Ну, кроме Cube-Organized Materialized Views. Потом решил, что на семинаре будет масса людей, которые вообще с OLAP не работали, ни с какой версией, поэтому им, возможно, будет интересно узнать об OLAP вообще. Заодно при подготовке и посмотрю внимательнее, что там изменилось. Но оказалось, что изменений неожиданно много.
В этой статье я ориентируюсь на людей, которые уже знакомы с Oracle Express или Oracle OLAP, ну или хотя бы в общих чертах представляет, что это. Для начального ознакомления предлагаю почитать мои статьи "Что такое OLAP" (Часть 1 Часть 2)
Интеграция метаданных с Oracle Database
Первое, что бросилось в глаза, это то, что действительно через любой SQL инструмент теперь стало очень удобно смотреть на данные, лежащие в OLAP кубах. Причем, как только вы создаете какой-то объект с помощью Analytic Workspace Manager (AWM) (показатель, измерение и т.д.) он тут же становится виден из SQL. Для этого автоматически создается обвязка из VIEW, каждый из которых содержит вызов CUBE_TABLE. Выглядит это примерно так:
GLOBAL.UNITS_CUBE - это указание на то, что данные лежат в кубе UNITS_CUBE, который создавался в AWM. А CUBE_TABLE - табличная функция, такой универсальный вызов данных из объектов, лежащих в аналитическом прострастве.
В 10й версии тоже была возможность увидеть данные через SQL. Для этого была табличная функция OLAP_TABLE. (Собственно, она и сейчас есть, но смысла ее использовать, наверное, не очень много) Но чтобы заставить ее работать, нужно было предварительно создать кучу разных абстрактных типов данных, описания LIMITMAP и проч. Причем можно было ошибиться на любом шаге. В общем, для начинающих совершенно не подходило. Даже был такой плагин к AWM, который эти типы мог создать сам, что, в общем, частично проблему решало. Сейчас ничего делать не надо. Для каждого измерения и куба есть соответствующая вьюшка. Вы можете легко делать запросы к этим VIEW для того, чтобы например, фильтровать измерения по атрибутам. То есть, в вашем SQL запросе будут объединяться вьюшки измерений и куба, а оптимизатор сам знает как весь этот запрос протолкнуть через CUBE_TABLE внутрь OLAP движка, где он и будет отработан. Более того, никто не запрещает объединять данные из OLAP с данными из реляционки в любом запросе. Например, для того чтобы соединить агрегированные данные с детальными.
Кроме того, в 10g вызовы OLAP_TABLE работали довольно медленно. В 11g разница в скорости заметна невооруженным глазом. Причем, встроенная смотрелка AWM работает достаточно медленно, но если такой же запрос выполнить из SQL, он работает гораздо быстрее. Что говорит скорее всего о том, что смотрелка AWM генерирует запросы не так, или медленно обрабатывает результаты. Вообще, при желании это можно оттрассировать, но мне пока не хватило времени.
Увеличение скорости работы SQL связано с тем, что теперь обработка запросов оптимизатором сделана более умно и фильтрация значений по измерениям происходит внутри аналитического пространства, то есть в движке OLAP, а не в самом Oracle, как это было в 10g. Если сравнить запрос SQL и аналогичный ему DML запрос выполнять из OLAP Worksheet, то разница в скорости не заметна. То есть, SQL отрабатыват примерно также как и запрос непосредственно к движку.
Можно сделать вывод, что связка SQL - CUBE_TABLE - стала вполне пригодной для того, чтобы пользоваться ей для доступа к OLAP.
Как следствие, к данным OLAP можно обращаться любым ROLAP инструментом, например Oracle Business Intelligence Enterprise Edition, который работает с базой Oracle через SQL. Другие API не обязательны.
При этом, любые манипуляции с движком OLAP, если это необходимо, можно делать используя пакет DBMS_AW.
Упрощение стандартной формы
Когда я запустил новый AWM, оказалось, что в нем исчезла возможность смотреть структуру AW в режиме Object View.
Тут надо сделать небольшое отступление.
В Oracle Express были пользовательские объекты. Были и внутренние объекты, хранящие метаданные, которые физически были реализованы объектами Express, такими как измерения, отношения, переменные и и.д. Но внутренние были в основном скрыты от конечного пользователя. Да и большой небходимости в них залезать не было. В 9й версии, когда OLAP стал частью СУБД Oracle, сначала все оставалось, как было в Express, но потом, в районе 9.2.0.4 (точно не помню) была придумана так называемая стандартная форма (Standard Form, SF)
Это специальная обвязка метаданных, нужная для интеграции с СУБД Oracle. Но проблема в том, что те объекты, которые создавались в AWM и которые пользователь считал измерениями, показателями и т.д., на самом деле физически лежат совершенно в других объектах, а добраться до них можно было лишь расшифорвав сложный слой метаданных SF. А SF сама по себе менялась с каждым патчсетом. Express всегда славился своим очень гибким языком, который сейчас называется OLAP DML. На нем можно было написать очень сложные расчетные формулы и программы, для работы с многомерными объектами. Но сложность SF по сути убивала эту возможность, так как было довольно сложно расшифровывать метаданные, к тому же, велика вероятность, что в следующем релизе что-то поменяется и ваша программа перестанет работать. А SF считается объектом внутренним и поддержка прошлых версий SF не гарантируется.
Поэтому, в AWM прошлых версий было два вида представления объектов OLAP - Model View и Object View. Model View показывал как объекты выглядят через призму SF, Object View - как они хранятся на самом деле. Что и говорить, найти соответствия между двумя предствлениями было очень сложно.
В 11 версии все стало гораздо проще. Создаем мы из AWM куб UNITS_CUBE, а в нем показатель SALES. Теперь в OLAP DML мы можем увидеть объект UNITS_CUBE_SALES, название которого составлено из названия куба и названия показателя. Это же распространяется и на вычисляемые показатели. У нас теперь опять есть простой путь использования наших показателей в формулах и программах. И не важно, что на самом деле, это не куб, а формула, которая смотрит на другой объект. Для нас уже не важно знать, как именно он хранится.
Хотя, если кому интересно, можно и посмотреть:
Напомню, что через SQL тот же куб можно увидеть через вьюшку UNITS_CUBE_VIEW, а показатель SALES соответственно будет UNITS_CUBE_VIEW.SALES
И вот тут видно основное отличие данных, которые достаются из OLAP от данных, которые берутся из обычных таблиц Oracle. Обратите внимание на первую строчку, где четыре слова "TOTAL". В этой строке - агрегат (сумма) по продажам по всем измерениям. Если бы мы хотели достать сумму по всем измерениям из обычной таблицы, нам нужно было написать что-то вроде
А OLAP уже выдает все возможные агрегаты, поэтому вместо суммирования, нам нужно в условиях SQL запроса WHERE описать фильтр этой строки. Само суммирование делать не надо. Сумму уже посчитал OLAP сервер.
Это естественно накладывает некоторые условия на программирование SQL над OLAP. Например, в том же BI EE нужно специальным образом описать правила обсчета уровней иерархий, что бы не пошло суммирование по уже агрегированным данным.
Вторая тонкость в том, что если я напишу запрос по данным о продаже определенного продукта, и не укажу условия по другим измерениям, то из таблицы фактов мне выпадут все продажи этого продкута. Но если тоже самое сделать над OLAP, то кроме фактов детального уровня выйдут и все возможные комбинации агрегатов по разным измерениям, что в зависимости от структуры куба может быть объемом в десятки раз превышающим количество детальных фактов.
Иными словами, когда вы пишете запрос к OLAP нужно всегда ограничивать все измерения
На Хабре, хоть как то представлено описание решения от Microsoft для задач аналитической обработки данных в реальном времени, но нет ни слова о мировом лидере в данном вопросе Oracle Essbase Поэтому ниже привожу описание данной технологии.
Oracle EssBase – это OLAP сервер, отличающийся от конкурентов мощной поддержкой аналитических задач, позволяя производить многомерный анализ в разрезе множества аналитик, строить прогнозы развития компания, подготовить данные для отчетности. Он поддерживает весь спектр OLAP решений – MOLAP(двух видов Aggregate Storage и Block Storage), ROLAP и HOLAP (MOLAP+ROLAP).
Архитектуру схематически можно представить следующим образом:
Состоит из следующих компонент:
Этот модуль Analytic Services создает базу данных в основе, которой лежит понятие блок – это таблица, состоящая из всех возможных вариантов плотных направлений, и эти блоки размещаются на пересечении разряженных направлений. Данный модуль поддерживает запись значений с помощью пользовательских приложений и предназначен для комплексного финансового анализа.
- Для приложений, связанных с итеративным планированием, распределениями, сложным анализом (анализ продаж, анализ прибыльности)
- Если необходимо много процедурных вычислений и запись изменений на любой уровень агрегации
- Управление порядком вычисления измерений
- Вычисление всей или части БД
- Выполнение сложных вычислений
Этот модуль Analytic Services создает «агрегированную» базу данных, в себе хранит элементы нулевого уровня, автоматически рассчитывая все значения более высокого уровня, по своей структуре чем –то напоминает ROLAP. Предназначен для анализа сверхбольших данных (экстремально разряженных), с миллионами возможных показателей.
- Для крупномасштабных, разреженных данных
- Стандартный набор правил агрегации
Это интерфейс администратора базы данных Analytic Services, поддерживающий единую точку администрирования для множества серверов баз данных. Используя этот инструмент, Вы можете разрабатывать, обслуживать и управлять как серверами, так и приложениями и их базами данных.
• Интеграционная консоль — Essbase Integration Studio (не развивается, предшественик Essbase Integration Studio )
Integration Server это сервер, использующий многопоточную архитектуру, обслуживающий связь между реляционными источниками данных, OLAP каталогом метаданных и Analytic Server (сервером многомерных баз данных).
Это программное решение предназначено для получения AD-HOC отчетов в Microsoft Excel, оно непосредственно подключается к многомерной базе данных. Развитие остановлено.
Позволяет получить доступ к данным из всего пакета программ Microsoft Office, отличается от Essbase SpreadSheet технологическим решением. Усиленно развивается.
Интерфейс командный строки, предназначен для проведения административных задач, таких как остановка приложения, запуск сервисных утилит, резервное копирование и др.
Интерфейс командный строки, для проведения административных задач.
Это инструмент разработчика программного обеспечения, позволяет обращать к многомерной базе данных из VB, C, или JAVA.
• Обслуживающие сервисы — Analytic Deployment Services
Позволяет строить единую точку входа для обеспечения балансировки нагрузки и отказоустойчивости между приложениями пользователей и многомерными базами данных.
Ну и в конце несколько ресурсов, которые помогут в освоении данной технологии
Читайте также: