Showing posts with label Oracle Graphs. Show all posts
Showing posts with label Oracle Graphs. Show all posts

Wednesday, April 10, 2024

PGQL Property Graphs and Virtual Private Database (VPD)

Securing your data and controlling its access is and should always be a significant concern. The Oracle Database has plenty of built-in security features that help reduce the risk of data breaches or provide granular access control. Virtual Private Database (VPD) is one such feature for the latter.

Oracle Graph enables you to focus on exploring and analysing connections in your data using a Property Graph Query Language such as PGQL, graph algorithms, or graph machine learning.

The question is how you can combine these two things: Using your Oracle Database as a Graph Database and still securing access to your data used in graphs.

The example I will discuss in my post uses an Oracle Autonomous Database Serverless 19c. If you don´t have access to the Oracle Cloud Infrastructure (OCI) and Autonomous Database yet, don´t mind. Everything I describe works nicely on the Oracle Database wherever you have it installed and running.

The data


Let us start with providing data, we want to control access to and which we also explore later using Oracle Graph. One representing a typical financial services use case, where we have bank accounts money being transferred between the accounts, is provided if you run Lab 1 of the LiveLabs tutorial "Find Circular Payment Chains with Graph Queries in Autonomous Database". The tutorial uses resources on OCI.

I use the LiveLabs tutorial, since it sets up everything I need by applying a Terraform stack. You will find the following resources ready-to-use:

  • An Autonomous Database (ADW or ATP) with a randomized password for the default database user ADMIN (check the end of the "Apply" log displaying the output).
  • A database user named GRAPHUSER with a randomized password (check the end of the "Apply" log displaying the output).
  • Two database tables, BANK_ACCOUNTS and BANK_TXNS with data imported, primary and foreign key constraints properly in place.

Make yourself familiar with the data set. It is stripped to basic information only to demonstrate the use case. See that table BANK_TXNS has a column AMOUNT.

select amount, count(*)
from bank_txns
group by amount
order by 1 desc;

Secure access to your data


There is a regulatory requirement that amounts higher than 5000 are only revealed to a specific user. We will use VPD to ensure that the requirement is met.

VPD is based on two things, a policy function and a policy. We define both as follows using the ADMIN user:

-- Policy function
CREATE OR REPLACE FUNCTION hide_big_txns (
  p_schema IN VARCHAR2,
  p_object IN VARCHAR2
)
RETURN VARCHAR2 AS
  l_predicate VARCHAR2 (200);
  l_user VARCHAR2(100);
BEGIN
  select user into l_user from dual;
  if l_user != 'GRAPHUSER' then
    l_predicate:='amount <= 5000';
  end if;
  RETURN (l_predicate);
END hide_big_txns;
/

-- Policy
BEGIN
  DBMS_RLS.ADD_POLICY (
    object_schema            => 'graphuser',
    object_name              => 'bank_txns',
    policy_name              => 'hide_big_txns_policy',
    function_schema          => 'admin',
    policy_function          => 'hide_big_txns',
    statement_types          => 'select',
    sec_relevant_cols        => 'amount',
    sec_relevant_cols_opt    => DBMS_RLS.ALL_ROWS
  );
END;
/

You can test, if your security requirement defined by VPD is met. Check it first for user GRAPHUSER, who should still be able to see transactions with amounts larger than 5000.

As GRAPHUSER run:

SELECT *
FROM bank_txns
WHERE amount > 5000
ORDER BY amount DESC
FETCH FIRST 5 ROWS ONLY;

Then as ADMIN user we set up a new user granting SELECT privileges to the tables owned by GRAPHUSER.

CREATE USER testuser IDENTIFIED BY <PWD>;
GRANT RESOURCE, CONNECT, CREATE SESSION, CREATE TABLE TO testuser;
ALTER USER testuser QUOTA UNLIMITED ON data;
GRANT SELECT ON graphuser.bank_txns TO testuser;
GRANT SELECT ON graphuser.bank_accounts TO testuser;

Now log in using TESTUSER and run the query again. No transactions should come back as result.

VPD and Graph combined


The next step is to verify that access to the data is also restricted if we use transaction information in a graph and query that graph using PGQL.

For the next steps we use Graph Studio, one of the tools available for Autonomous Databases. Log in to Graph Studio with the user GRAPHUSER.

Define your graph

Log into Graph Studio using GRAPHUSER. Create the following paragraphs and run them once the environment is attached to the Graph Studio session.

%pgql-rdbms
/* Create the graph. Rows in table BANK_ACCOUNTS become vertices, rows in table BANK_TXNS become edges of a graph named BANK_GRAPH_VPD. */
CREATE PROPERTY GRAPH bank_graph_vpd
    VERTEX TABLES (
        graphuser.bank_accounts
        KEY (acct_id)
        LABEL account
        PROPERTIES ( acct_id, name )
    )
    EDGE TABLES (
        graphuser.bank_txns
        KEY (txn_id)
        SOURCE KEY ( src_acct_id ) REFERENCES bank_accounts
        DESTINATION KEY ( dst_acct_id ) REFERENCES bank_accounts
        LABEL transfers
        PROPERTIES ( txn_id, amount, src_acct_id, dst_acct_id, description )
  ) OPTIONS (PG_PGQL)

PGQL Property Graphs and Virtual Private Database (VPD)
Create a graph using PGQL

Load the graph into memory

%python-pgx
# Load the graph into memory
GRAPH_NAME="BANK_GRAPH_VPD"
# try getting the graph from the in-memory graph server
graph = session.get_graph(GRAPH_NAME);
# if it does not exist read it into memory
if (graph == None) :
    session.read_graph_by_name(GRAPH_NAME, "pg_view")
    print("Graph "+ GRAPH_NAME + " successfully loaded")
    graph = session.get_graph(GRAPH_NAME)
else :
    print("Graph '"+ GRAPH_NAME + "' already loaded")

PGQL Property Graphs and Virtual Private Database (VPD)
Load the graph in memory using the Python API

Query the graph

%pgql-pgx
/* Show transactions querying the in-memory graph using PGQL */
SELECT *
FROM MATCH (s IS ACCOUNT)-[t IS TRANSFERS]->(d IS ACCOUNT) ON bank_graph_vpd

PGQL Property Graphs and Virtual Private Database (VPD)
Query the in-memory representation of the graph using PGQL

%pgql-pgx
/* Show transactions with amount >= 5000 querying the in-memory graph */
SELECT *
FROM MATCH (s IS ACCOUNT)-[t IS TRANSFERS]->(d IS ACCOUNT) ON bank_graph_vpd
WHERE t.amount >= 5000

PGQL Property Graphs and Virtual Private Database (VPD)
Query the graph using PGQL: Find transactions with amount >= 5000

You can see that as GRAPHUSER you are allowed to see all transaction amounts including the larger one.

How does it look like running the same PGQL queries as TESTUSER? According the the VPD policy, the amount > 5000 should be returned as NULL. Let us verify it.

Log out from Graph Studio and log in again, this time as TESTUSER. Create a notebook using with the first two paragraphs that GRAPHUSER used to create and load the graph.

%pgql-pgx
/*
 * Show transactions querying the in-memory graph using PGQL.
 * Order the result by the transaction amount, the highest first.
 * According to the VPD policy, no amount should be higher than 5000.
 */
SELECT *
FROM MATCH (s IS ACCOUNT)-[t IS TRANSFERS]->(d IS ACCOUNT) ON bank_graph_vpd
ORDER BY t.amount DESC
FETCH FIRST 10 ROWS ONLY

PGQL Property Graphs and Virtual Private Database (VPD)
Query the graph with access restricted by VPD

You probably wonder, why the transactions with amounts > 5000 do not appear at all in the graph. The NULL values for the transaction amount are converted to 0.0 by loading the graph into memory. Hence you can reveal them by running the following PGQL query:

%pgql-pgx

/*
 * Show transactions querying the in-memory graph using PGQL.
 * Order the result by the transaction amount, the highest first.
 * According to the VPD policy, no amount should be higher than 5000.
 */
SELECT s.acct_id as src_acct_id, t.amount, d.acct_id AS dst_acct_id
FROM MATCH (s IS ACCOUNT)-[t IS TRANSFERS]->(d IS ACCOUNT) ON bank_graph_vpd
ORDER BY t.amount ASC
FETCH FIRST 10 ROWS ONLY

PGQL Property Graphs and Virtual Private Database (VPD)
Query the graph using PGQL against the in-memory graph with access restricted by VPD

If you would rather see the NULL displayed, you can also execute a PGQL query directly against the database, bypassing the graph loaded into memory. 

%pgql-rdbms
/*
 * Show transactions querying the database directly graph using PGQL.
 * Order the result by the transaction amount, the highest first.
 * According to the VPD policy, no amounts higher than 5000 should be displayed .
 */
SELECT s.acct_id as src_acct_id, t.amount, d.acct_id AS dst_acct_id
FROM MATCH (s IS ACCOUNT)-[t IS TRANSFERS]->(d IS ACCOUNT) ON bank_graph_vpd
ORDER BY t.amount DESC
FETCH FIRST 10 ROWS ONLY

PGQL Property Graphs and Virtual Private Database (VPD)
Query the graph using PGQL against the database graph with access restricted by VPD

How can you distinguish when the PGQL is executed against the in-memory graph and when against the database directly? Look at the interpreter specified in the first line of each paragraph.

  • %pgql-pgx executes a PGQL query against the in-memory graph
  • %pgql-rdbms executes a PGQL query directly against the database

Quod erat demonstrandum


Virtual Private Database policies restrict access to your data. They are also effective when accessing graphs built from the data. Setting up policies once and using them everywhere, including with graphs, is an excellent way to ensure that everybody can see and use what they intend to see and use, regardless of the way, they access the data.

Source: oracle.com

Monday, February 19, 2024

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs

With zero lines of code and just a few clicks you can create a property graph view from an RDF knowledge graph. This enables you to run path analysis on a knowledge graph. And why is that interesting? A knowledge graph captures relationships between data entities, providing a way to capture knowledge (facts that describe a concept or domain) from experts. Path analytics on such a knowledge graph can identify entities in your data that are connected to each other, via the concepts captured in the knowledge graph. Path analytics can explain how to reach a goal – an entity in the graph - and ensures that information is not missed in critical decision-making.

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 1: UI to create a property graph from an RDF knowledge graph.
 
You might be new to graph theory and graph analytics, so let me explain a bit about graphs along with some examples. Let us first understand knowledge graphs.

What is a Knowledge Graph?


Knowledge graphs capture information about a domain. They organize information as connected networks. In a knowledge graph the entities and relationships between them are represented using the formal semantics of the standards defined by the W3C (World Wide Web Consortium), and this enables knowledge (the facts about a concept or domain) to be consumed through APIs. The complex layers of meaning in data can be represented so that they can be disambiguated by applications. Knowledge graphs can be used to provide context to data so application developers can understand the data better and analysts can make more informed decisions.

For example, consider job candidates and their resumes. Representing their attributes as a knowledge graph can help recruiters make more informed decisions, because the graph captures the relationships between the different concepts that make up a candidate’s skillset. A knowledge graph can capture how the different entities – education, skills, experience – can be related to each other. Such a knowledge graph is referred to as an ontology.

Consider an ontology on the topic AL/ML. AI/ML is a general concept and several sub-topics can be attributed to it as you see in Figure 2.

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 2: Ontology of the “AI/ML” topic with sub-topics
 
These topics and sub-topics are related to various tools and programming skills, as shown in Figure 3. As you can see some tools and skills are related to more than one sub-topic.

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 3: Ontology of the “AI/ML” topic with sub-topics and related tools and programming skills
 
Then there are companies that have products related to these topics, as show in Figure 4.

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 4: Ontology of the “AI/ML” topic with added information on companies that have AI/ML products
 
This type of information (an ontology) is curated by experts and represented as a knowledge graph in many organizations as a way to store descriptions of entities and how they are related to each other.

Finally we include the candidates you may be considering to hire for the role that requires AI/ML expertise, and the connections they have to various entities in the ontology.

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 5: How candidates are connected to the AI/ML ontology
 
This network of concepts (the ontology) and how the candidates fit in this network provide a more complete picture of our candidate pool. How a candidate is connected to a required skill or topic can determine how strongly they satisfy the requirements.For example, Jane has worked for company Y, which develops products for data analytics (Data Science). John has experience in Python, has participated in Hackathons and has GitHub repositories with code related to NLP. So we can see that John has more connections to the AI/ML topic, but Jane has the work experience that almost perfectly matches the AI/ML developer role that you are looking to fill.

How can we programmatically determine the different paths that connect a candidate to the goal of being an AI/ML developer with a relevant set of skills? This brings us to property graphs.

What is a Property Graph?


Like knowledge graphs a property graph also connects entities by the relationships between them. In addition, each entity (also known as a ‘node’) and relationship (also known as an ‘edge’) can have attributes (also known as ‘properties’). Property graphs can be queried based on how nodes are connected to each other by a path and the length of each path, filtered based on properties of the node and the edge. Graph algorithms such as PageRank, Dijkstra’s shortest path and clustering can be run on property graphs.Property graphs are particularly well suited for path analysis that explores how entities are connected.

In our example, the goal would be to find candidates connected to the AI/ML node in the graph and then determine which connection is the strongest. This might be by looking at the number of hops in a path (fewer hops might imply a stronger connection), or weights assigned as a property to each edge. Or you can just determine the number of paths – the more the number of paths, the stronger the connection. Additionally, knowing and identifying the intermediate nodes in every path, rather than having a black box that identifies paths for each candidate is important. For example, that information is relevant for the candidate’s future skills development plan once they are hired. This feature, the explainability of an outcome or prediction, is enabled by graphs. Every piece of information in the graph can be traced to where it comes from and what it connects to.

What Does a Property Graph View on a Knowledge Graph Do?


The formal semantics and syntax of the knowledge graph standards provide a simple way to capture information about a domain, but do not enable flexibility in traversing paths in that graph. Property graphs are more flexible, and have evolved to enable developers to find paths, clusters, spanning trees, and other structures in a graph. Most vendors focus on one of these two graph models, whereas Oracle provides the ability to use both property graphs and RDF knowledge graphs, as well as create a property graph view from an RDF knowledge graph, all in the same database.

Let us go back to our example and see what insights we can discover from such a property graph view. Jane has worked for company Y, which develops products for data analytics (Data Science). John has experience in Python, a necessary skill for Data Scientists, and has participated in Hackathons and has GitHub repositories with code related to NLP. He worked for company X, but there is no known connection between that company and the skills we are looking for. Kavitha has taken courses in Data Science, while Yi-Ching has taken courses in Statistics, and also published papers at conferences.  Katia has experience in Cohere, which is related to LLMs. These are all different paths each candidate has to the skills the position requires. 

Consider candidate Jane

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 6: Ontology of the “AI/ML” topic and Jane’s path to the AI/ML topic
 
Jane – works for -> Company Y – which develops products in -> Data Science –which is a subtopic of-> AI/ML.

This is a strong path as she has actual experience working for a product company in an area related to the AI/ML topic.

Consider candidate John

Accelerate your Informed Decision-Making: Enable Path Analytics on Knowledge Graphs
Figure 7: Ontology of the “AI/ML” topic and John’s paths to the AI/ML topic
 
John – works for –> Company X

John – has experience -> Python – skill needed for -> Data Science – which is a subtopic of -> AI/ML

John – has experience -> Python – skill needed for -> NLP – which is a subtopic of -> AI/ML

John – has participated in -> Hackathons – related to -> Spark NLP – API/tool for -> NLP - which is a subtopic of -> AI/ML

John – has created -> GitHub repos – related to -> Spark NLP – API/tool for -> NLP - which is a subtopic of -> AI/ML

John has four paths to the node AI/ML, but the company he worked for, Company X, does not appear to have a connection to the AI/ML topic.

The property graph view on a knowledge graph for the AI/ML topic gives you a deeper and more complete view of applicants to help you decide which candidates to hire.

More Informed Decision Making


“Is there a connection between two entities Y and Z?” or “how do you reach an entity B from entity A?” are important questions in many applications. In this example, we can have a more complete picture of how a candidate is related to the required skills by asking such property graph path analytics questions. The good news is that you can run such analytics using a property graph view on knowledge graphs, created through a new “no-code” Graph Studio interface. I am sure you are very excited about the new possibilities this may give you – I will follow up with another blog with an example of how you may go about creating a property graph view on an RDF knowledge graph to run graph analytics. Stay tuned.

Source: oracle.com

Monday, November 20, 2023

SQL Property Graphs and SQL/PGQ in Oracle Database 23c

Oracle have had a Graph Server and Client product for some time, but in Oracle database 23c some of the property graph functionality has been built directly into the database.

This article focuses on new SQL property graph feature and ignores the previous Graph Server product and PGQL.

Setup


We create a new test user. We add a couple of extra privileges that allow us to do some tracing and display execution plans, but these are not necessary when using SQL property graphs.

conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdba

drop user if exists testuser1 cascade;

create user testuser1 identified by testuser1 quota unlimited on users;
grant db_developer_role to testuser1;

-- Only used for tracing and execution plan examples.
grant alter session to testuser1;
grant select_catalog_role to testuser1;

We need to make sure our test user has the ability to create property graphs.

grant create property graph to testuser1;

This privilege is already part of the RESOURCE role, and will probably be added to the DB_DEVELOPER_ROLE role in the future.

We create a table to hold people, and a table to record the connections between those people.

conn testuser1/testuser1@//localhost:1521/freepdb1

drop table if exists sales purge;
drop table if exists products purge;
drop table if exists connections purge;
drop table if exists people purge;

create table people (
  person_id number primary key,
  name      varchar2(15)
);

insert into people (person_id, name)
values (1, 'Wonder Woman'),
       (2, 'Peter Parker'),
       (3, 'Jean Grey'),
       (4, 'Clark Kent'),
       (5, 'Bruce Banner');
commit;

create table connections (
  connection_id  number primary key,
  person_id_1    number,
  person_id_2    number,
  constraint connections_people_1_fk foreign key (person_id_1) references people (person_id),
  constraint connections_people_2_fk foreign key (person_id_2) references people (person_id)
);

create index connections_person_1_idx on connections (person_id_1);
create index connections_person_2_idx on connections (person_id_2);

insert into connections (connection_id, person_id_1, person_id_2)
values (1,  1, 2),
       (2,  1, 3),
       (3,  1, 4),
       (4,  2, 4),
       (5,  3, 1),
       (6,  3, 4),
       (7,  3, 5),
       (8,  4, 1),
       (9,  5, 1),
       (10, 5, 2),
       (11, 5, 3);
commit;

We create a table to hold products, and a table to hold sales, linked back to the people we defined earlier.

create table products (
  product_id  number primary key,
  name        varchar2(10)
);

insert into products (product_id, name)
values (1, 'apple'),
       (2, 'banana'),
       (3, 'lemon'),
       (4, 'lime');
commit;

create table sales (
  sale_id     number primary key,
  person_id   number,
  product_id  number,
  quantity    number,
  constraint sales_people_fk foreign key (person_id) references people (person_id),
  constraint sales_products_fk foreign key (product_id) references products (product_id)
);

create index sales_person_id_idx on sales (person_id);
create index sales_product_idx on sales (product_id);

insert into sales (sale_id, person_id, product_id, quantity)
values (1, 1, 2, 10),
       (2, 1, 3, 5),
       (3, 2, 2, 6),
       (4, 2, 1, 4),
       (5, 3, 2, 3),
       (6, 3, 1, 6),
       (7, 3, 3, 2),
       (8, 4, 3, 8),
       (9, 5, 2, 6),
       (10, 5, 4, 5),
       (11, 5, 3, 3);
commit;

We gather statistics on all the tables.

exec dbms_stats.gather_table_stats(null, 'people');
exec dbms_stats.gather_table_stats(null, 'connections');
exec dbms_stats.gather_table_stats(null, 'products');
exec dbms_stats.gather_table_stats(null, 'sales');

SQL Property Graphs


A property graph is a model that describes nodes (vertices), and the relationships between them (edges). In the case of SQL property graphs introduced in Oracle database 23c, the vertices and edges are schema objects such as tables, external tables, materialized views or synonyms to these objects. The property graph is stored in the database, and can be referenced by SQL/PGQ queries. There is no data materialized by the SQL property graph, it is just metadata. All the actual data comes from the references objects.

We create a property graph where the PEOPLE table represents the vertices (the points) and the CONNECTIONS table represents the edges (the lines between the points).

--drop property graph connections_pg;

create property graph connections_pg
  vertex tables (
    people
      key (person_id)
      label person
      properties all columns
  )
  edge tables (
    connections
      key (connection_id)
      source key (person_id_1) references people (person_id)
      destination key (person_id_2) references people (person_id)
      label connection
      properties all columns
  );

The LABEL keyword allows us to associate a meaningful name, which we can reference in queries. Notice the edge table has a SOURCE KEY and DESTINATION KEY describing the connection between the vertices.

We create a property graph for the sales of products to people. The vertex tables are PEOPLE and PRODUCTS, and the edge table is SALES.

--drop property graph sales_pg;

create property graph sales_pg
  vertex tables (
    people
      key (person_id)
      label person
      properties all columns,
    products
      key (product_id)
      label product
      properties all columns
  )
  edge tables (
    sales
      key (sale_id)
      source key (person_id) references people (person_id)
      destination key (product_id) references products (product_id)
      label sale
      properties all columns
  );

We display the current property graphs using the USER_PROPERTY_GRAPHS view.

column graph_name format a20
column graph_mode format a10
column allows_mixed_types format a17
column inmemory format a8

select * from user_property_graphs;

GRAPH_NAME               GRAPH_MODE ALLOWS_MIXED_TYPE INMEMORY
--------------------                ----------    ----------------- --------
CONNECTIONS_PG      TRUSTED    NO                NO
SALES_PG                       TRUSTED    NO                NO

SQL>

SQL/PGQ (GRAPH_TABLE)

With the property graphs in place we can use the GRAPH_TABLE operator to query the property graphs using SQL/PGQ. We display people who are connected to each other.

select person1, person2
from   graph_table (connections_pg
         match
         (p1 is person) -[c is connection]-> (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2)
       )
order by 1;

PERSON1         PERSON2
--------------- ---------------
Bruce Banner    Wonder Woman
Bruce Banner    Peter Parker
Bruce Banner    Jean Grey
Clark Kent      Wonder Woman
Jean Grey       Clark Kent
Jean Grey       Wonder Woman
Jean Grey       Bruce Banner
Peter Parker    Clark Kent
Wonder Woman    Clark Kent
Wonder Woman    Peter Parker
Wonder Woman    Jean Grey

11 rows selected.

SQL>

Let's break this query down.

  • We call GRAPH_TABLE passing the property graph.
  • We define the graph element pattern in the MATCH clause using the vertex and edge labels to show our relationship.
  • We define the COLUMNS that will be available in our select list.

The MATCH clause elements can include a WHERE clause to limit the rows, and of course we can include a WHERE clause in the main body of the query.

select person1, person2
from   graph_table (connections_pg
         match
         (p1 is person where p1.name = 'Jean Grey') -[c is connection]-> (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2)
       )
order by 1;

PERSON1         PERSON2
--------------- ---------------
Jean Grey       Wonder Woman
Jean Grey       Clark Kent
Jean Grey       Bruce Banner

SQL>

select person1, person2
from   graph_table (connections_pg
         match
         (p1 is person where p1.name = 'Jean Grey') -[c is connection]-> (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2)
       )
where  person2 = 'Clark Kent'
order by 1;

PERSON1               PERSON2
--------------------- ---------------------
Jean Grey             Clark Kent

SQL>

To display the graph using Oracle Graph Visualization we need to include the VERTEX_ID and EDGE_ID functions to identify the IDs of the vertices and edges. These produce a fully qualified description of the element. In the following example we return a single row containing these values.

column id_p1 format a20
column id_c format a20
column id_p2 format a20
set linesize 200 pagesize 100

select person1, person2, id_p1, id_c, id_p2
from   graph_table (connections_pg
         match
         (p1 is person) -[c is connection]-> (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  vertex_id(p1) AS id_p1,
                  edge_id(c) AS id_c,
                  vertex_id(p2) AS id_p2)
       )
where  rownum = 1
order by 1;

PERSON1         PERSON2         ID_P1                ID_C                 ID_P2
--------------- --------------- -------------------- -------------------- --------------------
Wonder Woman    Peter Parker    {"GRAPH_OWNER":"TEST {"GRAPH_OWNER":"TEST {"GRAPH_OWNER":"TEST
                                USER1","GRAPH_NAME": USER1","GRAPH_NAME": USER1","GRAPH_NAME":
                                "CONNECTIONS_PG","EL "CONNECTIONS_PG","EL "CONNECTIONS_PG","EL
                                EM_TABLE":"PEOPLE"," EM_TABLE":"CONNECTIO EM_TABLE":"PEOPLE","
                                KEY_VALUE":{"PERSON_ NS","KEY_VALUE":{"CO KEY_VALUE":{"PERSON_
                                ID":1}}              NNECTION_ID":1}}     ID":2}}


SQL>

This example uses our second property graph, and allows us to see people who are related by purchasing the same items.

select person1, product, person2
from   graph_table (sales_pg
         match
         (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is sale]- (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  pr.name as product)
       )
where  person1 != person2
order by 1;

PERSON1         PRODUCT    PERSON2
--------------- ---------- ---------------
Bruce Banner    lemon      Jean Grey
Bruce Banner    banana     Jean Grey
Bruce Banner    banana     Peter Parker
Bruce Banner    lemon      Clark Kent
Bruce Banner    banana     Wonder Woman
Bruce Banner    lemon      Wonder Woman
Clark Kent      lemon      Bruce Banner
Clark Kent      lemon      Jean Grey
Clark Kent      lemon      Wonder Woman
Jean Grey       banana     Peter Parker
Jean Grey       apple      Peter Parker
Jean Grey       lemon      Wonder Woman
Jean Grey       banana     Wonder Woman
Jean Grey       lemon      Bruce Banner
Jean Grey       banana     Bruce Banner
Jean Grey       lemon      Clark Kent
Peter Parker    banana     Jean Grey
Peter Parker    banana     Wonder Woman
Peter Parker    apple      Jean Grey
Peter Parker    banana     Bruce Banner
Wonder Woman    banana     Jean Grey
Wonder Woman    lemon      Jean Grey
Wonder Woman    lemon      Bruce Banner
Wonder Woman    lemon      Clark Kent
Wonder Woman    banana     Peter Parker
Wonder Woman    banana     Bruce Banner

26 rows selected.

SQL>

As before, we need to include the IDs of the vertices and edges if we want to visualize the graph.

select person1, product, person2, id_p1, id_s1, id_pr, id_s2, id_p2
from   graph_table (sales_pg
         match
         (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is sale]- (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  pr.name as product,
                  vertex_id(p1) AS id_p1,
                  edge_id(s1) AS id_s1,
                  vertex_id(pr) AS id_pr,
                  edge_id(s2) AS id_s2,
                  vertex_id(p2) AS id_p2)
       )
where  person1 != person2
order by 1;

Oracle Graph Visualization


There are several ways to deploy the Oracle Graph Visualization tool. In this case we deployed it using Tomcat.

Click on the "Oracle Graph Client" link here, and select the architecture you require. In this case we downloaded "Oracle Graph Webapps 23.2.0 for (Linux x86-64)". The SQL/PGQ support was added to the visualizer in version 23.1, so make sure you are not using an older version.

On the Tomcat server we did the following.

cd /tmp
unzip -oq V1033696-01-linux-webapps.zip
unzip -oq oracle-graph-webapps-23.1.0.zip
cp graphviz-23.2.0-tomcat.war $CATALINA_BASE/webapps/

We were then able to access the visualizer on the following URL.

https://localhost:8443/graphviz-23.2.0-tomcat

We log in with the following details.

Username: testuser1
Password: testuser1
Advanced > Database: jdbc:oracle:thin:@//localhost:1521/freepdb1

Oracle Graph Visualization creates tables, materialized views and views when you run a query. They all have the prefix "$GRAPHVIZ_TEMP_TABLE_". Make sure the user you are connecting to has the privilege to do that.

We click on the "SQL/PGQ" tab and place the following query into the visualizer. Notice it is missing the trailing ";". This query displays the connections between people.

select id_p1, id_c, id_p2
from   graph_table (connections_pg
         match
         (p1 is person) -[c is connection]-> (p2 is person)
         columns (vertex_id(p1) AS id_p1,
                  edge_id(c) AS id_c,
                  vertex_id(p2) AS id_p2)
       )

When we run it we get the following output.

SQL Property Graphs and SQL/PGQ in Oracle Database 23c

We click the settings (cog) button, click the "Customizations" tab, and set the "Vertex Label" to the NAME column.

SQL Property Graphs and SQL/PGQ in Oracle Database 23c

Once we click "OK" we see the graph with the labels.

SQL Property Graphs and SQL/PGQ in Oracle Database 23c

We use the following query against our second property graph to shows the people who have purchased the same products.

select id_p1, id_s1, id_pr, id_s2, id_p2
from   graph_table (sales_pg
         match
         (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is sale]- (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  vertex_id(p1) AS id_p1,
                  edge_id(s1) AS id_s1,
                  vertex_id(pr) AS id_pr,
                  edge_id(s2) AS id_s2,
                  vertex_id(p2) AS id_p2)
       )
where  person1 != person2

We run the query. In the "Customizations" tab we set the "Vertex Label" to NAME and the "Edge Label" to QUANTITY.

SQL Property Graphs and SQL/PGQ in Oracle Database 23c

Not only can we see the relationship between the people and the products, but we can also see the quantity of the products purchased on the edge labels.

Query Transformation


Let's see what happens behind the scenes when we use SQL/PGQ.

First we flush the shared pool and identify the trace file that will be created for our new session.

conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdba

alter system flush shared_pool;

conn testuser1/testuser1@//localhost:1521/freepdb1

set linesize 100
column value format a65

select value
from   v$diag_info
where  name = 'Default Trace File';

VALUE
-----------------------------------------------------------------
/opt/oracle/diag/rdbms/free/FREE/trace/FREE_ora_14020.trc

SQL>

Now we do a 10053 trace of the statement.

alter session set events '10053 trace name context forever';

select person1, product, person2
from   graph_table (sales_pg
         match
         (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is sale]- (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  pr.name as product)
       )
where  person1 != person2
order by 1;

alter session set events '10053 trace name context off';

We check the resulting trace file, searching for the section beginning with "Final query after transformations", and we see the following statement.

Final query after transformations:******* UNPARSED QUERY IS *******
SELECT "P1"."NAME" "PERSON1",
       "PR"."NAME" "PRODUCT",
       "P2"."NAME" "PERSON2"
FROM   "TESTUSER1"."PEOPLE" "P1",
       "TESTUSER1"."SALES" "S1",
       "TESTUSER1"."PRODUCTS" "PR",
       "TESTUSER1"."SALES" "S2",
       "TESTUSER1"."PEOPLE" "P2"
WHERE  "P1"."NAME"<>"P2"."NAME"
AND    "P1"."PERSON_ID"="S1"."PERSON_ID"
AND    "PR"."PRODUCT_ID"="S1"."PRODUCT_ID"
AND    "P2"."PERSON_ID"="S2"."PERSON_ID"
AND    "PR"."PRODUCT_ID"="S2"."PRODUCT_ID"
ORDER BY "P1"."NAME"

The statement has been transformed to convert the SQL/PGQ into regular joins. In this example there is not a great deal of difference in complexity between the SQL/PGQ and the transformed SQL statement, but in some scenarios the SQL/PGQ can massively simplify the joins and unions necessary to return the data.

Since the SQL/PGQ is converted to regular SQL, it's possible to display the execution plan in the normal way.

select person1, product, person2
from   graph_table (sales_pg
         match
         (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is sale]- (p2 is person)
         columns (p1.name as person1,
                  p2.name as person2,
                  pr.name as product)
       )
where  person1 != person2
order by 1;

select * from table(dbms_xplan.display_cursor(format=>'ALL'));

PLAN_TABLE_OUTPUT
------------------------------------------------------------------------------------------------------------------------
SQL_ID  2j4yv6j0gks9y, child number 0
-------------------------------------
select person1, product, person2 from   graph_table (sales_pg
match          (p1 is person) -[s1 is sale]-> (pr is product) <-[s2 is
sale]- (p2 is person)          columns (p1.name as person1,
      p2.name as person2,                   pr.name as product)
) where  person1 != person2 order by 1

Plan hash value: 3808001794

--------------------------------------------------------------------------------------------------------
| Id  | Operation                        | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                 |                     |       |       |    14 (100)|          |
|   1 |  SORT ORDER BY                   |                     |    24 |  1224 |    14  (15)| 00:00:01 |
|*  2 |   HASH JOIN                      |                     |    24 |  1224 |    13   (8)| 00:00:01 |
|*  3 |    HASH JOIN                     |                     |    30 |  1080 |    10  (10)| 00:00:01 |
|*  4 |     HASH JOIN                    |                     |    11 |   330 |     8  (13)| 00:00:01 |
|   5 |      MERGE JOIN                  |                     |    11 |   165 |     5  (20)| 00:00:01 |
|   6 |       TABLE ACCESS BY INDEX ROWID| PRODUCTS            |     4 |    36 |     2   (0)| 00:00:01 |
|   7 |        INDEX FULL SCAN           | SYS_C0012556        |     4 |       |     1   (0)| 00:00:01 |
|*  8 |       SORT JOIN                  |                     |    11 |    66 |     3  (34)| 00:00:01 |
|   9 |        VIEW                      | index$_join$_003    |    11 |    66 |     2   (0)| 00:00:01 |
|* 10 |         HASH JOIN                |                     |       |       |            |          |
|  11 |          INDEX FAST FULL SCAN    | SALES_PERSON_ID_IDX |    11 |    66 |     1   (0)| 00:00:01 |
|  12 |          INDEX FAST FULL SCAN    | SALES_PRODUCT_IDX   |    11 |    66 |     1   (0)| 00:00:01 |
|  13 |      TABLE ACCESS FULL           | PEOPLE              |     5 |    75 |     3   (0)| 00:00:01 |
|  14 |     VIEW                         | index$_join$_005    |    11 |    66 |     2   (0)| 00:00:01 |
|* 15 |      HASH JOIN                   |                     |       |       |            |          |
|  16 |       INDEX FAST FULL SCAN       | SALES_PERSON_ID_IDX |    11 |    66 |     1   (0)| 00:00:01 |
|  17 |       INDEX FAST FULL SCAN       | SALES_PRODUCT_IDX   |    11 |    66 |     1   (0)| 00:00:01 |
|  18 |    TABLE ACCESS FULL             | PEOPLE              |     5 |    75 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------------------------------------

Query Block Name / Object Alias (identified by operation id):
-------------------------------------------------------------

   1 - SEL$E6D2A9F4
   6 - SEL$E6D2A9F4 / "PR"@"SEL$88741CE7"
   7 - SEL$E6D2A9F4 / "PR"@"SEL$88741CE7"
   9 - SEL$2237A74B / "S1"@"SEL$88741CE7"
  10 - SEL$2237A74B
  11 - SEL$2237A74B / "indexjoin$_alias$_001"@"SEL$2237A74B"
  12 - SEL$2237A74B / "indexjoin$_alias$_002"@"SEL$2237A74B"
  13 - SEL$E6D2A9F4 / "P1"@"SEL$88741CE7"
  14 - SEL$37BF1F62 / "S2"@"SEL$88741CE7"
  15 - SEL$37BF1F62
  16 - SEL$37BF1F62 / "indexjoin$_alias$_001"@"SEL$37BF1F62"
  17 - SEL$37BF1F62 / "indexjoin$_alias$_002"@"SEL$37BF1F62"
  18 - SEL$E6D2A9F4 / "P2"@"SEL$88741CE7"

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("P2"."PERSON_ID"="S2"."PERSON_ID")
       filter("P1"."NAME"<>"P2"."NAME")
   3 - access("PR"."PRODUCT_ID"="S2"."PRODUCT_ID")
   4 - access("P1"."PERSON_ID"="S1"."PERSON_ID")
   8 - access("PR"."PRODUCT_ID"="S1"."PRODUCT_ID")
       filter("PR"."PRODUCT_ID"="S1"."PRODUCT_ID")
  10 - access(ROWID=ROWID)
  15 - access(ROWID=ROWID)

Column Projection Information (identified by operation id):
-----------------------------------------------------------

   1 - (#keys=1) "P1"."NAME"[VARCHAR2,15], "PR"."NAME"[VARCHAR2,10], "P2"."NAME"[VARCHAR2,15]
   2 - (#keys=1) "P1"."NAME"[VARCHAR2,15], "PR"."NAME"[VARCHAR2,10], "P1"."NAME"[VARCHAR2,15],
       "P2"."NAME"[VARCHAR2,15], "P2"."NAME"[VARCHAR2,15]
   3 - (#keys=1) "P1"."NAME"[VARCHAR2,15], "PR"."NAME"[VARCHAR2,10], "P1"."NAME"[VARCHAR2,15],
       "S2"."PERSON_ID"[NUMBER,22]
   4 - (#keys=1) "PR"."PRODUCT_ID"[NUMBER,22], "PR"."NAME"[VARCHAR2,10],
       "P1"."NAME"[VARCHAR2,15], "P1"."NAME"[VARCHAR2,15]
   5 - "PR"."PRODUCT_ID"[NUMBER,22], "PR"."NAME"[VARCHAR2,10], "S1"."PERSON_ID"[NUMBER,22]
   6 - "PR"."PRODUCT_ID"[NUMBER,22], "PR"."NAME"[VARCHAR2,10]
   7 - "PR".ROWID[ROWID,10], "PR"."PRODUCT_ID"[NUMBER,22]
   8 - (#keys=1) "S1"."PRODUCT_ID"[NUMBER,22], "S1"."PERSON_ID"[NUMBER,22]
   9 - "S1"."PRODUCT_ID"[NUMBER,22], "S1"."PERSON_ID"[NUMBER,22]
  10 - (#keys=1) "S1"."PERSON_ID"[NUMBER,22], "S1"."PRODUCT_ID"[NUMBER,22]
  11 - ROWID[ROWID,10], "S1"."PERSON_ID"[NUMBER,22]
  12 - ROWID[ROWID,10], "S1"."PRODUCT_ID"[NUMBER,22]
  13 - "P1"."PERSON_ID"[NUMBER,22], "P1"."NAME"[VARCHAR2,15]
  14 - "S2"."PRODUCT_ID"[NUMBER,22], "S2"."PERSON_ID"[NUMBER,22]
  15 - (#keys=1) "S2"."PERSON_ID"[NUMBER,22], "S2"."PRODUCT_ID"[NUMBER,22]
  16 - ROWID[ROWID,10], "S2"."PERSON_ID"[NUMBER,22]
  17 - ROWID[ROWID,10], "S2"."PRODUCT_ID"[NUMBER,22]
  18 - "P2"."PERSON_ID"[NUMBER,22], "P2"."NAME"[VARCHAR2,15]

Note
-----
   - this is an adaptive plan

92 rows selected.

SQL>

JSON Support


In the previous examples we used PROPERTIES ALL COLUMNS to keep things simple. We could have limited the properties to specific table columns using a comma-separated list, as shown below.

--drop property graph connections_pg;

create property graph connections_pg
  vertex tables (
    people
      key (person_id)
      label person
      properties (name)
  )
  edge tables (
    connections
      key (connection_id)
      source key (person_id_1) references people (person_id)
      destination key (person_id_2) references people (person_id)
      label connection
      properties (person_id_1, person_id_2)
  );

Where we have columns containing JSON data, we can drill down into the JSON data using dot notation, or SQL/JSON function calls to define properties.

We add a JSON column to the PEOPLE table and populate it with some JSON data.

alter table people add (json_data json);

update people
set    json_data = json('{"gender":"female", "universe":"DC"}')
where  person_id = 1;

update people
set    json_data = json('{"gender":"male", "universe":"Marvel"}')
where  person_id = 2;

update people
set    json_data = json('{"gender":"female", "universe":"DC"}')
where  person_id = 3;

update people
set    json_data = json('{"gender":"male", "universe":"Marvel"}')
where  person_id = 4;

update people
set    json_data = json('{"gender":"male", "universe":"Marvel"}')
where  person_id = 5;

commit;

We recreate the property graph including the two new properties using an example of dot notation and a JSON_VALUE call.

drop property graph connections_pg;

create property graph connections_pg
  vertex tables (
    people
      key (person_id)
      label person
      properties (name,
                  people.json_data.gender.string() as gender,
                  json_value(people.json_data, '$.universe') as universe)
  )
  edge tables (
    connections
      key (connection_id)
      source key (person_id_1) references people (person_id)
      destination key (person_id_2) references people (person_id)
      label connection
      properties (person_id_1, person_id_2)
  );

We project the new properties as columns and add them into our select list.

column gender1 format a10
column gender2 format a10
column universe1 format a10
column universe2 format a10

select person1, gender1, universe1, person2, gender2, universe2
from   graph_table (connections_pg
         match
         (p1 is person) -[c is connection]-> (p2 is person)
         columns (p1.name as person1,
                  p1.gender as gender1,
                  p1.universe as universe1,
                  p2.name as person2,
                  p2.gender as gender2,
                  p2.universe as universe2)
       )
order by 1;

PERSON1         GENDER1    UNIVERSE1  PERSON2         GENDER2    UNIVERSE2
--------------- ---------- ---------- --------------- ---------- ----------
Bruce Banner    male       Marvel     Peter Parker    male       Marvel
Bruce Banner    male       Marvel     Wonder Woman    female     DC
Bruce Banner    male       Marvel     Jean Grey       female     DC
Clark Kent      male       Marvel     Wonder Woman    female     DC
Jean Grey       female     DC         Wonder Woman    female     DC
Jean Grey       female     DC         Clark Kent      male       Marvel
Jean Grey       female     DC         Bruce Banner    male       Marvel
Peter Parker    male       Marvel     Clark Kent      male       Marvel
Wonder Woman    female     DC         Clark Kent      male       Marvel
Wonder Woman    female     DC         Jean Grey       female     DC
Wonder Woman    female     DC         Peter Parker    male       Marvel

11 rows selected.

SQL>

Friday, November 17, 2023

Powering Network Topology Planning and Administration with Oracle Graph

The modern telecom provider platform requires integrating multi-vendor solutions, supporting multiple domains, and managing multiple network layers for physical, logical, service and customer topology views. A unified topology view is required for supporting technologies like SDN, NFV, and 5G with complex end to end (e2e) network slicing and supporting unified services to B2B, B2C and B2B2X customers.

In addition, the growing size of communications networks, with both physical and virtual components, need to work in unison to deliver the guaranteed network experiences that the world has come to expect.

Oracle Communications Unified Topology for Inventory and Automation (UTIA) is an open, standards-based cloud-native application that provides these powerful network topology management capabilities. It is part of Oracle’s Unified Inventory and Topology solution, and is built on Spatial and Graph technology in Oracle Database.

UTIA delivers unified service, network, and resource visibility across diverse network technologies, enabling real-time views of networks for automated and accurate management of network operations. Network engineers and designers can quickly get a view of how networks are interconnected, aiding automated orchestration and trouble resolution. In addition, UTIA provides sophisticated high-definition visualization capabilities so that a network engineer can effectively visualize and gain insights from the topology of networks.

Powering Network Topology Planning and Administration with Oracle Graph

Use of Oracle Graph


Modeling networks and interconnections between networks as a graph enables a variety of queries. Finding devices that are n hops away (or by distance), finding neighboring network nodes, finding the shortest path between nodes, finding the cheapest path between nodes are just some of the graph operations used by UTIA. When computing the cheapest path the cost function captures transmission costs such as latency, jitter, distance, and packet loss, giving network engineers and designers the tools to effectively make decisions. 

Not only is this helpful for network engineers and designers, the path analysis API provides additional automation capabilities to bypass alarms and systematically support trouble resolution without human intervention. “Telecom data is a natural fit for modeling as a graph,” says Lee Latham, architect for this solution at Oracle Communications.

The graph database architecture includes a deployment of Oracle Graph Server (PGX) for high speed path analysis. The graph size used in our simulations is 40 million nodes and 15 million edges, which represents the estimated network size for a large service provider. Oracle Graph Server (PGX) can handle severe spikes of 25k to 30k per minute with no impact on resource usage. New data is added to Oracle Database and loaded into Oracle Graph Server (PGX) via the synchronization API, which syncs about 350k changes per hour. 

The scalability of Oracle Graph Server (PGX) enables UTIA to deliver an orders of magnitude performance advantage over an earlier implementation of their solution when rendering network views. This advantage increases as the number of network nodes increases. Rendering of 10,000 nodes that took over 10 minutes now takes seconds. 

The solution scales in other ways as well. The number of transactions per second remains the same when the dataset is doubled. The same hardware can process the increased number of transactions as the number of users increase.

Powering Network Topology Planning and Administration with Oracle Graph

UTIA Property Graph Model


The path analysis done by UTIA runs the gamut – ANY PATH, ANY SHORTEST PATH, ALL SHORTEST, TOP K SHORTEST, ANY CHEAPEST, TOP K CHEAPEST, ACYCLIC paths, and more. With the capabilities of Oracle’s converged database UTIA also leverages Oracle Spatial to plot network nodes on a map and to find the closest network resource to support a specific service.

Powering Network Topology Planning and Administration with Oracle Graph

Oracle Communications plans future enhancements such as using sub-graphs to segregate a company’s network by city, state, region, and domain, using graph machine learning to support service impact analysis and closed loop resolution, and implementing automated detection and persistence of network rings.

Source: oracle.com