Professional Documents
Culture Documents
Table of Contents
Lab Introduction .......................................................................................................................... 3
Lab Pre-requisites ................................................................................................................... 3
Getting Started and Lab 100 .....................................................................................................4
Download the lab script bundle ...........................................................................................4
Create your Oracle Cloud Trial Account ............................................................................4
Lab 100 - Provision your Autonomous Database ...........................................................8
Configure Auto-Scaling in the Autonomous Database ........................................... 14
Accessing the Performance Hub ................................................................................... 15
Prepare the APEX Workspace ........................................................................................ 17
Create an Oracle Analytics Cloud (OAC) instance to prepare for Lab 500 .............. 22
Lab 200: Adding Spatial to an APEX Application ............................................................. 24
Import the Application ........................................................................................................ 24
Review the APEX application before Spatial functionality ......................................... 28
Improve the application by adding Geocoding ............................................................. 28
Add verification that the flight will not take place in an urban zone ....................... 36
Lab 300: Adding Machine Learning to an APEX application .......................................... 41
Import the APEX application .............................................................................................. 41
Review the APEX application before Machine Learning ............................................. 45
Create an Oracle Machine Learning user ....................................................................... 47
Build the machine learning model using Zeppelin ...................................................... 50
Validate the results and the quality of the model .........................................................52
Create the prediction output ............................................................................................. 54
Integrate the result into the APEX application ...............................................................55
Review the ML-enabled APEX application ...................................................................... 61
Want to learn more about APEX? ......................................................................................... 63
Lab Introduction
In this hands-on lab you will get first-hand experience of using Oracle Autonomous
Database (ADB) and Oracle Application Express (APEX). The lab is split into 2 parts
to allow it to be delivered in a virtual classroom environment.
The lab is structured in several sections. Everyone must complete the "Getting
Started and Lab 100" section, but after that the individual APEX Labs are
standalone.
Lab Pre-requisites
This lab requires you to install the following desktop applications so that you can
complete this hands-on lab:
As you will be registering for services in Oracle Cloud, you will also need
This means you will have credit for experimenting with a large variety of Oracle
Cloud services, and you will not need a credit card to sign up.
On the "Account Detail" page you will be asked for the Cloud Account Name (also
known as Tenancy Name). This will uniquely identify your cloud environment and
will be visible in your URL later, so please choose wisely.
You will also be asked for the "Home Region". This is the location of the physical
datacenter. Choose your nearest location.
Complete all other mandatory fields on the form (indicated with a * ) and select
Next: Verify Your Mobile Phone Number.
At the end of this process, you will receive an email titled "Get Started Now With
Oracle Cloud". This will contain all the information you need to sign into your trial
cloud account and include a link to the login page for your region.
To login to your cloud account, use the same email address that you used for
registration and the password provided in the email. You will be prompted to set a
new, more memorable password.
This will produce a drop-down menu, where you should select Autonomous
Transaction Processing
This will take you to the management console page for ATP in the root
compartment of the tenancy.
To create a new instance, click the blue Create Autonomous Database button.
Enter the required information and click the Create Autonomous Database button
at the bottom of the form. For the purposes of this lab, use the information below:
Display Name: Enter the display name for your ATP Instance.
Database Name: Enter any database name you choose that fits the
requirements for ATP. The database name must consist of letters and
numbers only, starting with a letter. The maximum length is 14 characters.
(Hint- use your username so you can identify your instance more easily)
CPU Count: 1
Administrator Password: Enter any password you wish to use noting the
specific requirements imposed by ATP. A suggested password for this lab is
ATPwelcome-1234
When you enter the administrator password, note the specific requirements
imposed by Autonomous Database:
When you have completed the required fields, scroll down and click on the blue
Create Autonomous Database button at the bottom of the form:
The Autonomous Database Details page will show information about your new
instance. You should notice the various menu buttons that help you manage your
new instance – because the instance is currently being provisioned all the
management buttons are grayed out.
A summary of your instance status is shown in the large box on the left. In this
example, the color is amber and the status is Provisioning
After a short while the status will change to Available and the “ATP” box will
change color to green:
Oracle Solution Center
Version 1.1
13
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
Once the Lifecycle Status is Available, additional summary information about your
instance is populated, including workload type. You can also see the Lifecycle
Status reported in this region.
When you select auto scaling Autonomous Database can use up to three times
more CPU and IO resources than specified by the number of OCPUs currently
shown in the Scale Up/Down dialog without any manual intervention required.
On the "Autonomous Database Details" page for your Autonomous Database, click
the Scale Up/Down button.
In the "Scale Up/Down" pop-up, select the Auto Scaling checkbox and click
Update.
The status of your instance will change to "Scaling in Progress". You do not have to
wait for this to complete before moving onto the next step.
Performance Hub allows you to examine real-time and historical performance data,
view Active Session History (ASH) Analytics and SQL Monitoring.
From your Autonomous Database Details page, select Performance Hub from the
Action Menu.
Your Performance Hub page may not have any monitored SQL sessions available
in the screen. If this is the case, just examine the screenshots and use the menu
bars within the Performance Hub to examine what data you could use.
The "Time Range Selector" is on the top of the Performance Hub page. You can
use the "Select Duration" field to set the time duration displayed. You can choose to
view Last Hour (default), Last 8 hours, Last 24 hours, Last week, or specify a
custom time range using the Custom option.
The Time Range field shows active sessions in chart form for the time period
selected. The active sessions chart displays the average number of active sessions
broken down by CPU, User I/O, and Wait. The active sessions chart also shows the
Max CPU usage.
This shows Active Session History (ASH) analytics charts to explore Active Session
History data. You can drill down into database performance across multiple
dimensions such as Consumer Group, Wait Class, SQL ID, and User Name.
SQL Monitoring
The SQL statements by default are only monitored if they have been running for at
least five seconds or if they have run in parallel.
The table displays the top 100 monitored SQL statement executions, and you can
choose to alter the display by dimensions such as Last Active Time, CPU Time, and
Database Time. You can also choose to kill badly behaved SQL sessions from this
screen.
From your Autonomous Database Details page, select Service Console from the
Action Menu.
Oracle Solution Center
Version 1.1
17
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
This will open a new browser tab for Application Express Administration.
Login as the Admin user, with the Admin password you specified at Autonomous
Database creation time.
You will be returned to the Oracle APEX administration page, and a message will be
displayed "Workspace Created".
Logout as the Admin user by selecting the icon in the top right hand side of the
screen and selecting Sign Out.
Provisioning an Oracle Analytics Cloud instance can take over 40 minutes. If you
plan to run Lab 4 during the classroom session, then you can provision the
instance now and have it ready for use later.
Return to the Oracle Cloud Infrastructure console, click on the menu icon on the
left.
Note: You must be connected as an idcs user to see this menu item. Local OCI
users are not able to do this.
License Type: "Subscribe to a new Analytics Cloud software license and the
Analytics Cloud." (You will use this service as part of the free Oracle Cloud
trial that you requested for this workshop)
Region: No preference
Select Next.
The fictional scenario for the app is 'Drone Licensing'. The APEX application will be
used by an institution to process drone license requests and decide whether the
drone-flight is allowed. A drone flight will be allowed when its location is not within
an urban area.
Objectives
Open the APEX login screen. If you do not have a direct link or an open browser
window to this page you can access it by returning to the Service Console of your
Autonomous Database, select Development, and then Apex.
As part of the workshop preparation you downloaded a zip file containing the lab
script files. If you have not done so already, unzip this file so you can access the
files it contains.
At the top of the Workspace home page, click the App Builder menu and select
Import.
Use the Choose File button to select 'lab200-apex-app.sql' from the lab scripts zip
file.
Select Next
On the "File Import Confirmation" screen do not make any changes and select
Next.
On the "Install Database Application" screen no changes are required, select Install
Application.
On the App Builder page for your new application, select Run Application
If prompted, login to the application as WORKSHOPATP with the password you set
for the user.
You will now see the "Drone Requests Interactive Report" page.
Notice how we only have a textual address here at the moment, without
coordinates.
The application currently has textual addresses that have not yet been verified in
any way. Our goal is to check whether the address is within an urban area.
However, before we can do that we must first convert the address into a geo-
location, getting the latitude and longitude of the location. The process of
converting an address from text format to coordinates is called Geo-coding.
There are several publicly available web services that provide this service. Oracle
provides the eLocation service for this. Please read the license and usage terms
here before using the service commercially.
There is a built-in plugin in APEX called "Elocation Geocoder", which takes care of
the communication with this webservice. The input parameters for the plugin are:
The output of the plugin is an APEX collection, of which the following columns are
most important for us:
APEX collections provide a mechanism for you to store information on the user
session level. An APEX collection is a matrix of values (rows + columns). We will use
a collection as a way to retrieve the output from the geocoding webservice call,
wherein the rows are the returned unique locations and N002 and N003 are the
longitude-latitude components. Note that geocoding could in some cases return
multiple possible coordinates for the same written address. In our (simplified)
example we will only look at the first row, ignoring any additional rows.
On the App Builder page for your new application, select the Drone Flight Request
– Details to open it for editing.
In the left-hand sidebar, select "Items", right click and select Create Page Item to
add a new field.
On the right hand side of the page you will now have the properties related to your
new item 'P6_NEW'. Edit this item as follows:
Identification
Name: P6_CONCATENATED_ADDRESS
Type: Hidden
Return to the left-hand side and scroll down to locate "Region Buttons"
Right click on Region Buttons and click Create button to add a button.
On the right hand side of the page change the properties of your new button to :
Identification
Name: OBTAIN_FLY_ZONE_INFO
Now you will set the button to prepare the concatenated address field in the format
expected by the webservice.
Now you are going to prepare the concatenated address field for the webservice.
On the right-hand side, select your new button OBTAIN_FLY_ZONE_INFO and right
click and select Create Dynamic Action.
Oracle Solution Center
Version 1.1
31
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
On the right hand side change the properties of your new Dynamic
Action as follows:
Identification
Settings
JavaScript Expression:
$v("P6_ADDRESS").replace(",", " ") + ", " +
$v("P6_POSTAL_CODE").replace(",", " ") + ", " +
$v("P6_CITY").replace(",", " ")
Affected Elements
Items: P6_CONCATENATED_ADDRESS
Execution Options
Fire on Initialization: No
All the preparation is in place, now to configure the call to the webservice.
On your new Dynamic Action, right-click and select Create TRUE action. This
creates a new action below the "Set Value" action.
Identification
Settings
Execution Options
Fire on Initialization: No
The web service call is an asynchronous process. This means that an event will be
raised when the call completes. It is our task to correctly handle this event.
On the left-hand side change to the Dynamic Action tab, on "Events" right-click and
select Create Dynamic Action.
When
Event: elocation_geocoder_success
On the left-hand side, click the True action of the newly created Dynamic Action,
and then the Show action. Change the properties for the Show action as follows.
Identification
Settings
PL/SQL Code: (this code is available in lab zip file as the text file lab200-
plsql-check.txt)
declare
cursor c_geocoded_address
is
SELECT n002, n003
from apex_collections where collection_name =
'GEOCODER_RESULTS'
and n002 is not null and n003 is not null
order by seq_id;
r_geocoded_address c_geocoded_address%rowtype;
lon varchar2(100);
lat varchar2(100);
coordinates MDSYS.SDO_GEOMETRY;
overlap_count number;
result varchar2(100) := '';
begin
open c_geocoded_address;
fetch c_geocoded_address into r_geocoded_address;
lon := r_geocoded_address.n002;
lat := r_geocoded_address.n003;
close c_geocoded_address;
if lon is not null and lat is not null then
result := result || 'Address found: ' || '[' || lat || ',' ||
lon || ']';
else
result := result || 'Address not found';
end if;
:P6_PERMIT := result;
exception
when others then
:P6_PERMIT := sqlerrm;
end;
Items to Return : P6_PERMIT
Execution Options
Fire on Initialization: No
You can see a Click event that will a) construct the concatenated address and b) call
the webservice. You see the elocator "success" event that is called to process the
results of the geocoder service.
Edit any request on the report by selecting the pencil icon to open the "Drone
Flight Request – Details" page.
The Permitted? Box should be populated with either "Address Found" with the
latitude/logitude combination or "Address Not Found".
In our Lab application, the urban areas have been predefined and the collection of
polygons is already provided in a database table (URBAN_AREAS_UK) which was
imported as part of the application import at the start of the lab.
You will verify that the coordinate of the proposed drone flight is not within any
urban area by using the Oracle Spatial operators. The operator
SDO_ANYINTERACT will check if the coordinate overlaps/is inside any of the urban
area polygons defined.
You are going to change the PL/SQL that is executed when the web service returns
the result to check for interaction between the Drone flight co-ordinates and the
urban area.
Return to the App Builder page and edit the "Drone Flight Request - Details" page.
Settings
PL/SQL Code: (this code is available in lab zip file as the text file lab200-
plsql-check.txt)
declare
Oracle Solution Center
Version 1.1
37
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
cursor c_geocoded_address
is
SELECT n002, n003
from apex_collections where collection_name =
'GEOCODER_RESULTS'
and n002 is not null and n003 is not null
order by seq_id;
r_geocoded_address c_geocoded_address%rowtype;
lon varchar2(100);
lat varchar2(100);
result varchar2(100) := '';
coordinates MDSYS.SDO_GEOMETRY; --Add
overlap_count number; --Add
begin
open c_geocoded_address;
fetch c_geocoded_address into r_geocoded_address;
lon := r_geocoded_address.n002;
lat := r_geocoded_address.n003;
close c_geocoded_address;
if lon is not null and lat is not null then
result := result || 'Address found: ' || '[' || lat || ',' ||
lon || ']';
else
result := result || 'Address not found';
end if;
:P6_PERMIT := result;
exception
when others then
:P6_PERMIT := sqlerrm;
end;
Save your changes and re-run your application.
Edit the request for "Isaias Edwards" in Galashiels, and then click the Obtain Fly
Zone Info button.
This address does not intersect with the urban areas defined in the database,
therefore the permit results is "Allowed".
Select Cancel
Now use the search field to look for a request by "Maverick Rich".
You see that this address is inside an urban area and, therefore the permit results is
"No Fly Zone".
In this lab you will add machine learning to an existing APEX application. The actual
machine learning logic takes place in the database and the APEX application will
pick up the predictions. As an example, we will apply machine learning on a sales
scenario, in this case we will predict which customers are most likely to buy a
certain product.
The product is called "Y Box Games". Our fictional company has been moderately
successful in selling this product so far. Although some of our existing customers
already own this product, we believe that we could sell more. The problem is that it
is very difficult to understand what type of customer will be interested in it. That is
why we are re calling in the help of machine learning!
You will use Apache Zeppelin, which comes pre-installed with the autonomous
database. This will be your frontend for the Machine Learning algorithms in the
database.
For more background on machine learning in the database see Oracle Advanced
Analytics documentation.
Objectives
Open the APEX login screen. If you do not have a direct link or an open browser
window to this page you can access it by returning to the Service Console of your
Autonomous Database, select Development, and then Apex.
Oracle Solution Center
Version 1.1
41
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
As part of the workshop preparation you downloaded a zip file containing the lab
script files. If you have not done so already, unzip this file so you can access the
files it contains.
At the top of the Workspace home page, click the App Builder menu and select
Import.
Use the Choose File button to select 'lab300-apex-app.sql' from the lab scripts zip
file.
Select Next
On the "File Import Confirmation" screen do not make any changes and select
Next.
On the "Install Database Application" screen no changes are required, select Install
Application.
On the final screen of the wizard, select Edit Application to be placed into the App
Builder screen.
If prompted, login to the application as WORKSHOPATP with the password you set
for the user.
You see the simple Customer Service Application, with a list of customers.
During this lab you will add a column to this screen that shows whether this
customer is a good candidate for upselling.
From your Autonomous Database Details page, select Service Console from the
Action Menu.
On the Machine Learning User Administration page select Create to add a new
user.
Create a user called "MLUSER1". You can choose to have the password
automatically generated and emailed, but you must supply a valid email address.
Alternatively, you can select to enter your own password that complies with the
Oracle password complexity rules.
Return to the Service Console, select Development, and then ML SQL Notebooks.
Sign in as your new user, MLUSER1 with the password you set at user creation time.
Set the name of your new notebook to Predict Y Box Games and click OK
All of the SQL text for this lab is stored in the lab zip file as the text file lab300-
mlsql.txt.
Review the table that contains the customer information that we will use as input
data for the model. Enter the select statement and then use the symbol on the
right had side to run the statement in this paragraph.
SELECT * FROM SH.SUPPLEMENTARY_DEMOGRAPHICS;
The magic of machine learning is that it will find out what the relationships are
between these variables and our target variable, Y Box Games.
Split the input data into two sets: 60% for training and 40% for testing.
The model will contain the definition of the relationship between the driving
attributes and the target attribute (Y Box Games). Creating those relationships is
done during the training phase.
Defining a model requires several parameters which are stored in a table. This table
can have any name. In this lab the only parameter is the type of algorithm, which is
a decision tree model.
Now you are ready to create and train the model. Run the following PL/SQL.
%script
CALL DBMS_DATA_MINING.CREATE_MODEL('N1_CLASS_MODEL', 'CLASSIFICATION',
'N1_TRAIN_DATA', 'CUST_ID', 'Y_BOX_GAMES', 'N1_BUILD_SETTINGS');
Create a new placeholder column in the test data table to hold the predicted value.
ALTER TABLE N1_TEST_DATA ADD Y_BOX_GAMES_PRED NUMBER(1);
Then run the prediction and store the result in this column.
UPDATE N1_TEST_DATA SET Y_BOX_GAMES_PRED = PREDICTION(N1_CLASS_MODEL USING
*);
This statement means that you want to predict the value using model
'N1_CLASS_MODEL' and all of the driving columns in the dataset will be used.
Now calculate the percentage of the cases where the prediction is correct.
You can get more detail on this result using a confusion matrix. This can easily be
created by grouping on the two Y Box Games columns to see when false positives
and negatives have occurred.
Actual Y_BOX_GAMES
Predicted 0 1
Y_BOX_GAMES_PRED 0 True Negative False Negative
1 False Positive True Positive
• Batch. Make a prediction for all of the customers at a certain point of time.
Batch mode can be more efficient, as you could also use the results for a
targeted sales campaign. As a negative, batch mode would have to be
regularly scheduled to keep the results up to date.
• Case by case. Make a prediction per customer when it is needed. For
example, when opening the customer details screen.
In this lab you are going to do the batch mode. The method will be
Oracle Solution Center
Version 1.1
54
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1
• Select all customers how have not yet purchased Y Box Games.
• Predict if they are likely to be interested in the purchase and give a
probability to that prediction.
• Store these results in a table.
This batch result table has been created in the MLUSER1 schema, but the APEX
Application schema (WORKSHOPATP) will need to be able to select from this table.
grant select on cust_prediction to workshopatp;
Note: If you cannot find the URL for your APEX login screen then you can
access it by going back to your Autonomous Database Details page ->
Service Console -> Development -> Oracle APEX
Find out what view is being used to show the customer information by selecting
Customers in the Content Body Region. In the properties on the right-hand side
you will see the SQL query used to populate the page.
You can see that the data comes from the CUSTOMER_V view. We are going to
change this view to add a column that contains the recommendation.
You can amend the view from within APEX. Select SQL Workshop on the menu bar
at the top of the page, and then Object Browser.
Browse for the CUSTOMER_V view by changing the drop down to Views and
selecting the view. You can look at the view definition by selecting SQL.
The view currently selects all its values from the SH.CUSTOMERS table. You will
extend the view by adding a "RECOMMENDATION" column to it.
The new view definition is available in the lab script zip file as lab300-view.sql.
CREATE OR REPLACE VIEW "CUSTOMER_V" ("CUST_ID", "CUST_FIRST_NAME",
"CUST_LAST_NAME", "CUST_GENDER", "CUST_YEAR_OF_BIRTH",
"CUST_MARITAL_STATUS", "CUST_STREET_ADDRESS",
"CUST_POSTAL_CODE", "CUST_CITY", "CUST_CITY_ID", "CUST_STATE_PROVINCE",
"CUST_STATE_PROVINCE_ID", "COUNTRY_ID", "CUST_MAIN_PHONE_NUMBER",
"CUST_INCOME_LEVEL",
"CUST_CREDIT_LIMIT", "CUST_EMAIL", "CUST_TOTAL", "CUST_TOTAL_ID",
"CUST_SRC_ID", "CUST_EFF_FROM", "CUST_EFF_TO", "CUST_VALID",
"RECOMMENDATION") AS
select "CUST_ID","CUST_FIRST_NAME","CUST_LAST_NAME","CUST_GENDER",
"CUST_YEAR_OF_BIRTH","CUST_MARITAL_STATUS","CUST_STREET_ADDRESS",
"CUST_POSTAL_CODE","CUST_CITY","CUST_CITY_ID","CUST_STATE_PROVINCE",
"CUST_STATE_PROVINCE_ID","COUNTRY_ID","CUST_MAIN_PHONE_NUMBER",
"CUST_INCOME_LEVEL","CUST_CREDIT_LIMIT","CUST_EMAIL",
"CUST_TOTAL","CUST_TOTAL_ID","CUST_SRC_ID","CUST_EFF_FROM",
"CUST_EFF_TO","CUST_VALID",
(select c.cust_first_name || ' is ' || to_char(p.pred_probability * 100,
'999.99') || '% likely to be interested in Y Box Games'
from mluser1.cust_prediction p
where p.cust_id = c.cust_id
and p.prediction = 1
and p.pred_probability > 0.8
)
from sh.customers c;
This SQL adds the "Recommendation" column, and it will be a text that explains
whether the employee should try to upsell Y Box Games to this customer. In
addition, the recommendation will only be added when the probability of an upsell
is over 80%.
Select SQL Workshop on the menu bar at the top of the page, and then SQL
Commands.
Paste in the SQL for the new view definition and select Run.
In the main screen you see that for most customers, there is not a recommendation
to upsell Y Box Games. It is unlikely that these customers will be interested.
Search for a customer with first name "Connor" and last name "Clark". You can
select which columns to search using the spyglass icon next to the search
box.
Adding one column to an application might not look important, but the value to the
business can be significant. In this case an employee receives very valuable advice
on which customer to try to upsell a product to and he/she can use that to be more
effective.
Tutorials : https://apex.oracle.com/en/learn/tutorials
Community : http://apex.oracle.com/community
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. This document is provided for information purposes only, and
CONNECT WITH US the contents hereof are subject to change without notice. This document is not warranted to be error-free, nor subject to any
other warranties or conditions, whether expressed orally or implied in law, including implied warranties and conditions of
blogs.oracle.com/oracle merchantability or fitness for a particular purpose. We specifically disclaim any liability with respect to this document, and no
contractual obligations are formed either directly or indirectly by this document. This document may not be reproduced or
transmitted in any form or by any means, electronic or mechanical, for any purpose, without our prior written permission.
facebook.com/oracle
twitter.com/oracle Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
oracle.com
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license
and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron
logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.