You are on page 1of 64

Oracle Solution Center

ADB for Apex Developers Hands on Lab Guide – Part 1

Autonomous Database for


APEX Developers
Hands on Lab Guide
Part 1

Oracle Solution Center


Version 1.1
1
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

Oracle Solution Center


Version 1.1
2
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Autonomous Database (ADB) delivers a self-driving, self-securing, self-


repairing database service that can instantly scale to meet demands. The service
supports two workload types:

• Oracle Autonomous Data Warehouse (ADW) provides an autonomous


warehousing environment, associated with fast query performance.
• Oracle Autonomous Transaction Processing (ATP) provides an autonomous
online transaction processing and mixed workload environment.

Oracle Application Express (APEX) is a low-code development platform that


enables you to build scalable, secure enterprise apps, with world-class features,
that can be deployed anywhere.

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.

The lab has been produced based on the labs located at


https://github.com/oracle/cloudtestdrive/tree/master/ATP/APEX

Lab Pre-requisites
This lab requires you to install the following desktop applications so that you can
complete this hands-on lab:

• PDF File reader.


• A web browser. The lab guide was created using Google Chrome.

As you will be registering for services in Oracle Cloud, you will also need

• Access to the email account used to register for the workshop.


• A cell phone to receive an SMS for account verification processes.
Oracle Solution Center
Version 1.1
3
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Getting Started and Lab 100


This section of the lab will take you through all the required preparation steps. You
will

• Download the lab scripts.


• Connect to your Oracle Cloud account.
• Create your Autonomous Database.
• Configure your Autonomous Database.
• Prepare your APEX Workspace.

Download the lab script bundle


All of the sql scripts and large code blocks for this lab are available as a zip file
https://bit.ly/2rdAHCn . Download and unzip this bundle on your laptop.

Create your Oracle Cloud Trial Account


By registering for this workshop, your email address has been whitelisted for an
Oracle Cloud Trial.

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.

For this to work, it is important that you:

• Use the exact URL provided by your lab leader.


• Use the same email address that you used to register for the workshop.

Enter your email address and select "Next".

Oracle Solution Center


Version 1.1
4
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
5
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Complete all other mandatory fields on the form (indicated with a * ) and select
Next: Verify Your Mobile Phone Number.

You will be prompted to enter the code sent to your cellphone.

Oracle Solution Center


Version 1.1
6
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
7
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Lab 100 - Provision your Autonomous Database


Your new cloud tenancy will not have any compartments configured, so by default
you will create objects in the root compartment.

Note: If you want to learn more about administering Oracle Cloud


Infrastructure there are learning resources at
https://www.oracle.com/cloud/iaas/training/foundation.html with
additional hands on labs at https://oracle.github.io/learning-library/oci-
library/

Click on the MENU link at the top left of the page.

This will produce a drop-down menu, where you should select Autonomous
Transaction Processing

Oracle Solution Center


Version 1.1
8
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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:

Oracle Solution Center


Version 1.1
9
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Compartment: Verify that a compartment is selected.

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)

Workload Type: Autonomous Transaction Processing

Deployment Type: Shared Infrastructure

Always Free: Off

CPU Count: 1

Storage Capacity (TB): 1

Auto scaling: off

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

Configure access control rules: off

Choose a License Type: Licence Included.

Oracle Solution Center


Version 1.1
10
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

When you enter the administrator password, note the specific requirements
imposed by Autonomous Database:

Oracle Solution Center


Version 1.1
11
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
12
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

The provisioning process should take under 5 minutes.

Configure Auto-Scaling in the Autonomous Database

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.

Oracle Solution Center


Version 1.1
14
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Accessing the Performance Hub

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.

The Performance Hub page consists of the following regions:

- The time Range field and slider


Oracle Solution Center
Version 1.1
15
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

- Active Session History (ASH) analytics tab

- SQL Monitoring Tab.

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

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.

Active Session History (ASH) Analytics

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.

Oracle Solution Center


Version 1.1
16
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Prepare the APEX Workspace


Login to APEX Administration Services

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 the Service Console in a new browser tab.

In the side menu select Development.

Select Oracle APEX.

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.

Oracle Solution Center


Version 1.1
18
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Create the Lab Workspace

On the Welcome to "Oracle Application Express" page, select Create Workspace.

Oracle Solution Center


Version 1.1
19
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Use the following information to fill out the form:

Database User: WORKSHOPATP

Password: Any password that meets the Oracle Cloud requirements.Use


ATPwelcome-1234 for this lab.

Workspace Name: WORKSHOPATP

Select Create Workspace.

Oracle Solution Center


Version 1.1
20
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
21
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Create an Oracle Analytics Cloud (OAC) instance to


prepare for Lab 500
Your cloud trial account will consume credits while this instance is provisioned, so if
you wish to do Lab 500 on a later date, you can defer this step until you are ready
to run Lab 500.

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.

Navigate to Platform Service and then Analytics.

Note: You must be connected as an idcs user to see this menu item. Local OCI
users are not able to do this.

Oracle Solution Center


Version 1.1
22
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

This will open a new browser tab/window. Select Create Instance.

Complete the form using the following information:

Instance Name: WORKSHOPATP

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

Edition: Oracle Analytics Cloud - Professional (important)

Feature Set: Professional Edition Feature Set (important)

Number of OCPUs: 1 - Non Production

Select Next.

On the Confirmation screen select Create.

You can now proceed onto running the labs.

Oracle Solution Center


Version 1.1
23
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Lab 200: Adding Spatial to an


APEX Application
In this lab you will extend an existing APEX application, adding geospatial
functionality.

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

• Demonstrate how to geocode an address with APEX.


• Demonstrate how to perform geospatial calculations by using Spatial SQL
functions from within APEX.

Import the Application

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.

Login to APEX using:

Workspace name: WORKSHOPATP

User name: WORKSHOPATP

Password: Password you selected when creating the workspace.

Oracle Solution Center


Version 1.1
24
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.

Oracle Solution Center


Version 1.1
25
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
26
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

On the "Install Application – Supporting Objects" screen no changes are required,


select Next.

On the "Install Application – Confirmation" select Install.

On the final screen of the wizard, select Edit Application.


Oracle Solution Center
Version 1.1
27
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Review the APEX application before Spatial


functionality

On the App Builder page for your new application, select Run Application

This will open the Application in a new browser tab.

If prompted, login to the application as WORKSHOPATP with the password you set
for the user.

Click the Open Report button.

You will now see the "Drone Requests Interactive Report" page.

Open one of the Drone Flight requests.

Notice how we only have a textual address here at the moment, without
coordinates.

Improve the application by adding Geocoding


Oracle Solution Center
Version 1.1
28
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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 street, postal code and city, concatenated with commas.


• The country.

The output of the plugin is an APEX collection, of which the following columns are
most important for us:

• "N002": The geocoded address's longitude


• "N003": The geocoded address's latitude

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.

Oracle Solution Center


Version 1.1
29
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

Oracle Solution Center


Version 1.1
30
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

Label: 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

In your new Dynamic Action, select the Show action.

On the right hand side change the properties of your new Dynamic
Action as follows:

Identification

Action: Set Value

Settings

Set Type: JavaScript Expression

JavaScript Expression:
$v("P6_ADDRESS").replace(",", " ") + ", " +
$v("P6_POSTAL_CODE").replace(",", " ") + ", " +
$v("P6_CITY").replace(",", " ")

Affected Elements

Selection Type: Items

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.

Oracle Solution Center


Version 1.1
32
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Set the properties on the right-hand side as follows:

Identification

Action: Oracle Elocation Geocoder [Plugin-In]

Settings

Geocoding type: Geocoding

Collection Name: GEOCODER_RESULTS

Item containing Country Code: P6_COUNTRY

Item containing address lines: P6_CONCATENATED ADDRESS

Separator for address elements: , (Comma symbol)

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.

Oracle Solution Center


Version 1.1
33
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Update your new Dynamic Action (by default named "New_1")


and set the properties as follows:

When

Event: elocation_geocoder_success

Selection Type: JavaScript Expression

JavaScript Expression: document

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

Action: Execute PL/SQL Code

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;

Oracle Solution Center


Version 1.1
34
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

Save and double-check that everything is correct by going to the "Dynamic


Actions" tab. It should look similar to this:

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.

Test your application changes by running the application.

Go to the "Drone Flight Requests - Interactive Report" page.

Oracle Solution Center


Version 1.1
35
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Edit any request on the report by selecting the pencil icon to open the "Drone
Flight Request – Details" page.

Click the Obtain Fly Zone Info button.

The Permitted? Box should be populated with either "Address Found" with the
latitude/logitude combination or "Address Not Found".

Add verification that the flight will not take place in


an urban zone
To do this, we need access to a list of polygons for all the urban areas. Such a data
set could be prepared using the Spatial Studio tool, which can be used in
conjunction with the autonomous database or in any situation where there is a
license for the Spatial database option.

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.

Oracle Solution Center


Version 1.1
36
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

The Oracle Autonomous Database comes preconfigured with Oracle Spatial.


Highlights of the enabled features are; native storage and indexing of
point/line/polygon geometries, spatial analysis and processing, such as proximity,
containment, combining geometries, distance/area calculations, geofencing to
monitor objects entering and exiting areas of interest, and linear referencing to
analyze events and activities located along linear networks such as roads and
utilities.

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.

Select to the Dynamic Actions tab.

Under the elocation_geocoder_success, expand New_1 and then select Execute


PL/SQL code.

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 || ']';

--Added code for urban area check


coordinates := MDSYS.SDO_GEOMETRY(2001, 4326,
MDSYS.SDO_POINT_TYPE(lon, lat, NULL), NULL, NULL);
SELECT COUNT(*) INTO overlap_count
FROM URBAN_AREA_UK "t2"
WHERE SDO_ANYINTERACT("t2"."GEOM", coordinates) = 'TRUE';
if overlap_count = 0 then
result := result || ' - ALLOWED';
else
result := result || ' - NO FLY ZONE';
end if;
--End of added code for urban area check

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.

Oracle Solution Center


Version 1.1
38
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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".

Edit the request for "Maverick Rich".

Click the Obtain Fly Zone Info button.

You see that this address is inside an urban area and, therefore the permit results is
"No Fly Zone".

Oracle Solution Center


Version 1.1
39
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

You have now completed Lab 200.

Oracle Solution Center


Version 1.1
40
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Lab 300: Adding Machine


Learning to an APEX application

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

• Understand the components involved to add machine learning to APEX.


• Become familiar with machine learning algorithms.
• Create a machine learning model to identify customers that are likely to buy
a certain product.

Import the APEX application


Your starting point is an existing CRM application used by our fictional company.
This contains basic information about our company's customers. The application is
used by the sales/service employees of the company to look up details whenever a
customer calls them.

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

Login to APEX using:

Workspace name: WORKSHOPATP

User name: WORKSHOPATP

Password: Password you selected when creating the workspace.

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.

Oracle Solution Center


Version 1.1
42
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
43
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

On the "Install Database Application" screen no changes are required, select Install
Application.

On the "Install Application – Supporting Objects" screen no changes are required,


select Next.

Oracle Solution Center


Version 1.1
44
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

On the "Install Application – Confirmation" select Install.

On the final screen of the wizard, select Edit Application to be placed into the App
Builder screen.

Review the APEX application before Machine


Learning
On the App Builder page for your new application, select Run Application

Oracle Solution Center


Version 1.1
45
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

This will open the Application in a new browser tab.

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.

Oracle Solution Center


Version 1.1
46
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Our goal is to upsell something to these customers. However, relentless upselling


of irrelevant products will make our customers disengage from us. We want to alert
our employee whenever he/she has a customer on the screen that is a good
candidate for a particular product that we are trying to sell.

During this lab you will add a column to this screen that shows whether this
customer is a good candidate for upselling.

Create an Oracle Machine Learning user


We will develop the machine learning model using Zeppelin, which is included in
the Autonomous Database. Zeppelin is a web-based notebook environment that
allows us to analyse and experiment with data. In our case we will be using it to
build a machine learning model. First we will set up a user for Zeppelin.

From your Autonomous Database Details page, select Service Console from the
Action Menu.

This will open the Service Console in a new browser tab.

On the right-hand side select Administration and then Manage ML Users

On the Machine Learning User Administration page select Create to add a new
user.

Oracle Solution Center


Version 1.1
47
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Oracle Solution Center


Version 1.1
48
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Sign in as your new user, MLUSER1 with the password you set at user creation time.

Select Notebooks and Create.

Set the name of your new notebook to Predict Y Box Games and click OK

Oracle Solution Center


Version 1.1
49
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Build the machine learning model using Zeppelin


For this lab, we will build a model by letting it learn from data about our existing
customers.

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;

Oracle Solution Center


Version 1.1
50
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

There is a column "Y_BOX_GAMES", which tells us whether the customer already


owns Y Box Games. There are other customer attributes that may influence
whether a customer is likely to buy Y Box Games. For example, the level of
education might be an influencing factor for Y Box Games ownership, and so may
others such as Occupation and Household Size.

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.

CREATE TABLE N1_TRAIN_DATA AS SELECT * FROM SH.SUPPLEMENTARY_DEMOGRAPHICS


SAMPLE (60) SEED (1);

CREATE TABLE N1_TEST_DATA AS SELECT * FROM SH.SUPPLEMENTARY_DEMOGRAPHICS


MINUS SELECT * FROM N1_TRAIN_DATA;

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.

Enter the following SQL to create the parameters table.


Oracle Solution Center
Version 1.1
51
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

CREATE TABLE N1_BUILD_SETTINGS (SETTING_NAME VARCHAR2(30), SETTING_VALUE


VARCHAR2(4000));

INSERT INTO N1_BUILD_SETTINGS (SETTING_NAME, SETTING_VALUE) VALUES


('ALGO_NAME', 'ALGO_DECISION_TREE');

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');

The parameters you are supplying to the DBMS_DATA_MINING.CREATE_MODEL


procedure are as follows.

• N1_CLASS_MODEL: The name of the model, which is stored in the database


as a special type of object.
• CLASSIFICATION : The algorithm type, which can be a classification or a
regression algorithm. In this case it is a classification algorithm, predicting a
class (ownership yes/no) rather than a continuous value.
• N1_TRAIN_DATA : The name of the table to use for training. We created this
earlier when we split the dataset.
• CUST_ID : The name of the column that uniquely identifies each row in the
training data. In this case you are using the Customer ID number.
• Y_BOX_GAMES : The name of the target column for which we want to find
the driving factors.
• N1_BUILD_SETTINGS : The name of the hyperparameters table to use.

Validate the results and the quality of the model


You need to know how correct the model results are. As you have a test set of data,
with customers who already own Y Box Games, you can run the prediction on this
data set and see if the model correctly predicts Y Box Games ownership.
Oracle Solution Center
Version 1.1
52
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

View the result of the update.


SELECT CUST_ID, Y_BOX_GAMES, Y_BOX_GAMES_PRED FROM N1_TEST_DATA;

Now calculate the percentage of the cases where the prediction is correct.

SELECT TO_CHAR(((SELECT COUNT(*) FROM N1_TEST_DATA WHERE Y_BOX_GAMES =


Y_BOX_GAMES_PRED) / (SELECT COUNT(*) FROM N1_TEST_DATA)) * 100, '999.99')
CORRECT_PRED_PERCENTAGE FROM DUAL;

The result is an accuracy of approximately 90%.

Oracle Solution Center


Version 1.1
53
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

SELECT Y_BOX_GAMES, Y_BOX_GAMES_PRED, COUNT(*) FROM N1_TEST_DATA GROUP BY


Y_BOX_GAMES, Y_BOX_GAMES_PRED ORDER BY 1, 2;

The result table shows from top to bottom:

1. The true negatives

2. The false positives

3. The false negatives

4. The true positives

Create the prediction output


You have now built and validated your model. There are two possible ways to run
the prediction:

• 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.

CREATE TABLE CUST_PREDICTION AS


SELECT CUST_ID, PREDICTION(N1_CLASS_MODEL USING *) PREDICTION,
PREDICTION_PROBABILITY(N1_CLASS_MODEL USING *) PRED_PROBABILITY
FROM SH.SUPPLEMENTARY_DEMOGRAPHICS WHERE Y_BOX_GAMES = 0;

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;

Integrate the result into the APEX application


The goal is to show a recommendation to the customer service employee when the
customer they are speaking to is a likely candidate to buy Y Box Games.

Login to APEX using:

Workspace name: WORKSHOPATP

User name: WORKSHOPATP

Password: Password you selected when creating the workspace.

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

Oracle Solution Center


Version 1.1
55
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Open the "Customer Service App" application for editing.

Oracle Solution Center


Version 1.1
56
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Edit the Customers page.

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.

Oracle Solution Center


Version 1.1
57
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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

Oracle Solution Center


Version 1.1
58
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

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.

Open the "Customer Service App" application for editing.

Oracle Solution Center


Version 1.1
59
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Edit the Customers page.

You need to amend this page so that the "RECOMMENDATION" column is


displayed. Select 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.

Add the "RECOMMENDATION" column in the select statement (this code is


available in lab zip file as the text file lab300-new-select.sql).

Oracle Solution Center


Version 1.1
60
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Then Save the page.

Review the ML-enabled APEX application


Run the APEX application

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.

Oracle Solution Center


Version 1.1
61
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

For this customer ID 100111 there is a recommendation to try to upsell Y Box


Games, because the customer is very likely to be interested in this offer.

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.

You have now completed Lab 300.

Oracle Solution Center


Version 1.1
62
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Want to learn more about APEX?


APEX Collateral http://apex.oracle.com

Tutorials : https://apex.oracle.com/en/learn/tutorials

Community : http://apex.oracle.com/community

External Site + Slack: http://apex.world

Oracle Solution Center


Version 1.1
63
Oracle Solution Center
ADB for Apex Developers Hands on Lab Guide – Part 1

Oracle Corporation, World Headquarters Worldwide Inquiries


500 Oracle Parkway Phone: +1.650.506.7000
Redwood Shores, CA 94065, USA Fax: +1.650.506.7200

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.

Oracle Solution Center


Version 1.1
64

You might also like