### Query Graph Data in PGX using PGQL Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/getting-started-pgql This Java code snippet shows how to retrieve a handle to a PGX graph and execute PGQL queries against it. It includes an example of finding the department name for a specific employee and then demonstrates how to get an overview of vertex and edge types and their frequencies within the graph. ```java /** * To get a handle to the graph, execute: */ PgxGraph g = session.getGraph("HR_SIMPLIFIED"); /** * You can use this handle to run PGQL queries on this graph. * For example, to find the department that “Nandita Sarchand” works for, execute: */ String query = "SELECT dep.department_name " + "FROM MATCH (emp:Employee) -[:works_at]-> (dep:Department) " + "WHERE emp.first_name = 'Nandita' AND emp.last_name = 'Sarchand' " + "ORDER BY 1"; PgqlResultSet resultSet = g.queryPgql(query); resultSet.print(); /** * To get an overview of the types of vertices and their frequencies, execute: */ String query = "SELECT label(n), COUNT(*) " + "FROM MATCH (n) " + "GROUP BY label(n) " + "ORDER BY COUNT(*) DESC"; PgqlResultSet resultSet = g.queryPgql(query); resultSet.print(); /** *To get an overview of the types of edges and their frequencies, execute: */ String query = "SELECT label(n) AS srcLbl, label(e) AS edgeLbl, label(m) AS dstLbl, COUNT(*) " + "FROM MATCH (n) -[e]-> (m) " + "GROUP BY srcLbl, edgeLbl, dstLbl " + "ORDER BY COUNT(*) DESC"; PgqlResultSet resultSet = g.queryPgql(query); resultSet.print(); ``` -------------------------------- ### Run Oracle Graph Quickstart Container with Podman Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/running-oracle-graph-quickstart-container-image Starts the Oracle Graph Quickstart container in detached mode. It maps a host port to the container's port 7007 and sets the database password using an environment variable. Replace `` and `` with your desired values. ```bash podman run -d --name -p :7007 -e ORACLE_PWD= container-registry.oracle.com/database/graph-quickstart:25.2.0 ``` -------------------------------- ### Start HAProxy Service Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-haproxy-pgx-load-balancing-and-high-availability Starts the HAProxy service using systemctl. This command assumes HAProxy has been installed and configured. ```bash sudo systemctl start haproxy ``` -------------------------------- ### Start OPG4J Shell (Bash) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/oracle-graph-java-client Command to start the OPG4J shell after installing the Java client from the Graph Server and Client downloads. It requires the client installation directory, server host, and a username. ```bash cd ./bin/opg4j --base_url https://:7007 --username ``` -------------------------------- ### Start Tomcat Server Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/deploying-oracle-graph-server-web-server These commands navigate to the Tomcat installation directory and execute the startup script to start the Tomcat server. After starting, the graph server will be accessible via 'localhost:8080/pgx'. ```shell cd $CATALINA_HOME ./bin/startup.sh ``` -------------------------------- ### Start Interactive Graph Shell CLI Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/quick-start-working-pgql-property-graphs Launches the Oracle Graph Server interactive command-line interface (CLI). This command is used to start either the Java (opg4j) or Python (opg4py) shell for working with PGQL property graphs. No specific dependencies are required beyond the graph server installation. ```shell cd /opt/oracle/graph ./bin/opg4j --no_connect Oracle Graph Server Shell 26.1.0 ``` ```shell cd /opt/oracle/graph ./bin/opg4py --no_connect Oracle Graph Server Shell 26.1.0 ``` -------------------------------- ### PGQL SIMPLE Path Mode Example Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/supported-pgql-features-and-limitations-graph-server-pgx Showcases the `SIMPLE` path mode in PGQL, which disallows repeated vertices within a path, with the exception that the first and last vertices can be the same. This example finds simple paths, including cyclic ones that start and end at the same vertex. ```sql SELECT CAST(a.number AS STRING) || ' -> ' || LISTAGG(x.number, ' -> ') AS accounts_along_path FROM MATCH ANY SIMPLE PATH (a IS account) (-[IS transaction]-> (x))+ (a) WHERE a.number = 10039 ``` -------------------------------- ### PGQL ACYCLIC Path Mode Example Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/supported-pgql-features-and-limitations-graph-server-pgx Illustrates the `ACYCLIC` path mode in PGQL, which ensures that paths do not contain cycles, meaning no vertex is repeated except potentially the start and end vertex if they are the same. This example finds shortest acyclic paths. ```sql SELECT CAST(a.number AS STRING) || ' -> ' || LISTAGG(x.number, ' -> ') AS accounts_along_path FROM MATCH SHORTEST 10 ACYCLIC PATHS (a IS account) (-[IS transaction]-> (x))+ (b) WHERE a.number = 10039 AND b.number = 1001 ``` -------------------------------- ### Start OPG4Py Shell to Connect to Graph Server Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/oracle-graph-python-client Starts the OPG4Py shell and connects to the Oracle Graph server (PGX) using the provided base URL. Ensure you are in the client installation directory before running this command. ```bash cd ./bin/opg4py --base_url https://:7007 ``` -------------------------------- ### Python: Connect to Remote Server, Create Graph, Run PageRank, and Query Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/quick-start-using-python-client-module Demonstrates connecting to a remote Oracle Property Graph server using the Python client, creating a property graph, running the PageRank algorithm, and querying the results. Requires the Python client to be installed and authentication details for the remote server. ```python import pypgx import opg4py import opg4py.graph_server as graph_server pgql_conn = opg4py.pgql.get_connection("","", "") pgql_statement = pgql_conn.create_statement() pgql = """ CREATE PROPERTY GRAPH bank_graph VERTEX TABLES ( bank_accounts LABEL ACCOUNTS PROPERTIES (ID, NAME) ) EDGE TABLES ( bank_txns SOURCE KEY (SRC_ACCT_ID) REFERENCES bank_accounts (ID) DESTINATION KEY (DST_ACCT_ID) REFERENCES bank_accounts (ID) LABEL TRANSFERS PROPERTIES (SRC_ACCT_ID, DST_ACCT_ID, AMOUNT, DESCRIPTION) ) OPTIONS(PG_PGQL) """ pgql_statement.execute(pgql) instance = graph_server.get_instance("", "", "") session = instance.create_session("my_session") graph = session.read_graph_by_name('BANK_GRAPH', 'pg_pgql') analyst = session.create_analyst() analyst.pagerank(graph) rs = graph.query_pgql("SELECT id(x), x.pagerank FROM MATCH (x) LIMIT 5") rs.print() ``` -------------------------------- ### Create PGQL Property Graph using Java API Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs This Java example shows how to create a PGQL property graph. It requires Oracle JDBC drivers and PGQL libraries. The code establishes a JDBC connection, gets a PGQL connection, creates a PGQL statement, and executes the `CREATE PROPERTY GRAPH` command. Input parameters include JDBC URL, username, password, and the graph name. ```Java import java.sql.Connection; import java.sql.Statement; import java.sql.DriverManager; import oracle.pg.rdbms.pgql.PgqlConnection; import oracle.pg.rdbms.pgql.PgqlStatement; /* * This example shows how to create a PGQL property graph. */ public class PgqlCreate { public static void main(String[] args) throws Exception { int idx=0; String jdbcUrl = args[idx++]; String username = args[idx++]; String password = args[idx++]; String graph = args[idx++]; Connection conn = null; PgqlStatement pgqlStmt = null; try { //Get a jdbc connection conn = DriverManager.getConnection(jdbcUrl, username, password); conn.setAutoCommit(false); // Get a PGQL connection PgqlConnection pgqlConn = PgqlConnection.getConnection(conn); // Create a PGQL Statement pgqlStmt = pgqlConn.createStatement(); // Execute PGQL Query String pgql = "CREATE PROPERTY GRAPH " + graph + " " + "VERTEX TABLES ( bank_accounts as Accounts " + "KEY (id) " + "LABEL \"Accounts\"" + "PROPERTIES (id, name)" + ") " + "EDGE TABLES ( bank_transfers as Transfers " + "KEY (txn_id) " + "SOURCE KEY (src_acct_id) REFERENCES Accounts (id) " + "DESTINATION KEY (dst_acct_id) REFERENCES Accounts (id) " + "LABEL \"Transfers\"" + "PROPERTIES (src_acct_id, dst_acct_id, amount, description)" + ") OPTIONS (PG_PGQL) "; // Print the results pgqlStmt.execute(pgql); } finally { // close the statement if (pgqlStmt != null) { pgqlStmt.close(); } // close the connection if (conn != null) { conn.close(); } } } } ``` -------------------------------- ### Configure Oracle Graph Server with Quick Setup Script Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-rpm-installation The `quicksetup.sh` script in `/opt/oracle/graph/scripts` is used to configure the Oracle Graph Server (PGX). It supports options to enable/disable TLS, specify JDBC URLs, enable quiet mode, and restart the server. ```bash ./quicksetup.sh -d ``` ```bash ./quicksetup.sh -eq ``` ```bash ./quicksetup.sh -u Enter JDBC URL: jdbc:oracle:thin:@:/ ``` ```bash ./quicksetup.sh -j jdbc:oracle:thin:@:/ ``` ```bash ./quicksetup.sh -j jdbc:oracle:thin:@:/ -d ``` ```bash ./quicksetup.sh -x ``` ```bash ./quicksetup.sh -j jdbc:oracle:thin:@:/ -dx ``` -------------------------------- ### Get PGX Server Instance (Java, Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/get-server-instance Demonstrates how to obtain a PGX `Instance` object. This is a fundamental step for interacting with the Oracle Property Graph server. The Java example uses `Pgx.getInstance()` with an embedded URL, while the Python example uses `pypgx.get_session()` with a base URL. ```java import oracle.pgx.api.*; ServerInstance instance = Pgx.getInstance(Pgx.EMBEDDED_URL); ``` ```python instance = pypgx.get_session(base_url = "url") ``` -------------------------------- ### Start Oracle Property Graph Shell and Import Classes (Java) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/loading-graph-using-unsupervised-graphwise-algorithm This snippet shows how to start the Oracle Property Graph (OPG) JShell and import necessary classes for machine learning functionalities. It assumes you are in the OPG installation directory. ```java cd /opt/oracle/graph/ ./bin/opg4j // starting the shell will create an implicit session and analyst opg4j> import oracle.pgx.config.mllib.ActivationFunction opg4j> import oracle.pgx.config.mllib.WeightInitScheme ``` ```java import oracle.pgx.api.*; import oracle.pgx.api.mllib.UnsupervisedGraphWiseModel; import oracle.pgx.api.frames.*; import oracle.pgx.config.mllib.ActivationFunction; import oracle.pgx.config.mllib.GraphWiseConvLayerConfig; import oracle.pgx.config.mllib.UnsupervisedGraphWiseModelConfig; import oracle.pgx.config.mllib.WeightInitScheme; ``` -------------------------------- ### Configure PGX with Pre-loaded Graphs and Authorization Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/configuration-parameters-graph-server-pgx-engine This example demonstrates a more comprehensive PGX configuration, including setting thread pools for analysis and fast-track analysis, memory management thresholds, and specifying multiple graphs to be pre-loaded into memory upon server startup. It also includes an authorization block to define read permissions for pre-loaded graphs. ```json { "enterprise_scheduler_config": { "analysis_task_config": { "max_threads": 32 }, "fast_analysis_task_config": { "max_threads": 32 } }, "memory_cleanup_interval": 600, "max_active_sessions": 1, "release_memory_threshold": 0.2, "preload_graphs": [ { "path": "graph-configs/my-graph.bin.json", "name": "my-graph" }, { "path": "graph-configs/my-other-graph.adj.json", "name": "my-other-graph", "publish": false } ], "authorization": [ { "pgx_role": "GRAPH_DEVELOPER", "pgx_permissions": [ { "preloaded_graph": "my-graph", "grant": "read" }, { "preloaded_graph": "my-other-graph", "grant": "read" } ] }, .... ] } ``` -------------------------------- ### Basic Property Graph Creation using BASE GRAPHS Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/creating-property-graph-using-pgql A simple example demonstrating the creation of a new property graph by basing it on an existing graph. The new graph is a duplicate of the old one with a different name. ```sql CREATE PROPERTY GRAPH BASE GRAPHS () OPTIONS ( PG_PGQL ) ``` -------------------------------- ### Create and Explain Graph with SupervisedGnnExplainer (Java) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/explaining-prediction Demonstrates creating a simple graph, configuring the SupervisedGnnExplainer, and inferring explanations for a vertex's prediction using Java. It shows how to retrieve feature importances. ```Java PgxGraph simpleGraph = session.createGraphBuilder() .addVertex(0).setProperty("label_feature", 0.5).setProperty("const_feature", 0.5) .setProperty("label", true) .addVertex(1).setProperty("label_feature", -0.5).setProperty("const_feature", 0.5) .setProperty("label", false) .addEdge(0, 1).build(); // build and train a Supervised GraphWise model as explained in Advanced Hyperparameter Customization // obtain and configure the explainer SupervisedGnnExplainerexplainer=model.gnnExplainer().learningRate(0.05); explainer.numOptimizationSteps(200); // explain prediction of vertex 0 SupervisedGnnExplanation explanation = explainer.inferAndExplain(simpleGraph, simpleGraph.getVertex(0)); // if we used the devNet loss, we can add the decision threshold as an extra parameter: // SupervisedGnnExplanation explanation = explainer.inferAndExplain(simpleGraph, simpleGraph.getVertex(0), 6f); VertexProperty constProperty = simpleGraph.getVertexProperty("const_feature"); VertexProperty labelProperty = simpleGraph.getVertexProperty("label_feature"); // retrieve feature importances Map, Float> featureImportances = explanation.getVertexFeatureImportance(); float importanceConstProp = featureImportances.get(constProperty); // small as unimportant ``` -------------------------------- ### Find All Paths with Quantifiers in PGQL Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs Demonstrates finding all paths between two vertices using the `ALL` path finding goal in PGQL. It supports specific quantifiers to control path length and avoid cycles. The example shows finding transaction paths between accounts. ```sql SELECT LISTAGG(e.amount, ' + ') || ' = ' AS "sum_expression", SUM(e.amount) AS total_amount FROM MATCH ALL (a:Accounts) -[e:Transfers]->{1,4}(b:Accounts) WHERE a.id = 284 AND b.id = 616 ORDER BY total_amount ``` -------------------------------- ### Full Example: Querying Graphs with PGX JDBC Driver and AdbGraphClient Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-autonomous-ai-database-graph-client A comprehensive Java example demonstrating how to connect to an Autonomous AI Database using the PGX JDBC driver, attach to the graph environment, load a graph, and execute a PGQL query. It includes error handling and prints the query results. Dependencies include oracle.pgx.jdbc, oracle.pg.rdbms, and oracle.pgx.api. ```java import java.sql.*; import oracle.pgx.jdbc.*; import oracle.pg.rdbms.*; import oracle.pgx.api.*; public class AdbPgxJdbc { public static void main(String[] args) throws Exception { DriverManager.registerDriver(new PgxJdbcDriver()); try (Connection conn = DriverManager.getConnection("jdbc:oracle:pgx:@?TNS_ADMIN=","ADB_username","")) { AdbGraphClient client = conn.unwrap(AdbGraphClient.class); if (!client.isAttached()) { var job = client.startEnvironment(10); job.get(); System.out.println("job details: name=" + job.getName() + "type= " + job.getType() +"created_by= " + job.getCreatedBy()); } PgxSession session = conn.unwrap(PgxSession.class); PgxGraph graph = session.readGraphByName("BANK_PGQL_GRAPH", GraphSource.PG_PGQL); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * "+ "FROM GRAPH_TABLE ( BANK_PGQL_GRAPH "+ "MATCH (a IS ACCOUNTS) -[e IS TRANSFERS]-> (b IS ACCOUNTS) "+ "WHERE a.ID = 179 AND b.ID = 688 "+ "COLUMNS (e.AMOUNT AS AMOUNT ))"); while(rs.next()){ System.out.println("AMOUNT = " + rs.getLong("AMOUNT")); } } } } ``` -------------------------------- ### Start PGX Server Environment (Java) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-autonomous-ai-database-graph-client Starts the PGX server environment with a specified memory allocation in Java. It checks if the environment is already attached, starts it if not, and prints job details upon completion. ```java if (!client.isAttached()) { var job = client.startEnvironment(10); job.get(); System.out.println("job details: name=" + job.getName() + "type= " + job.getType() +"created_by= " + job.getCreatedBy()); } job details: name=Environment Creation - 16 GBstype= ENVIRONMENT_CREATIONcreated_by= ADBDEV ``` -------------------------------- ### Retrieve Queued Tasks - Oracle Property Graph Admin API Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/get-tasks This function retrieves the last 100 queued tasks from the Oracle Property Graph. Each task object contains details such as type, execution pool, status (Queued, Started, Done), and session ID if applicable. This is part of the Admin API for managing graph operations. ```javascript serverState.get("tasks") ``` -------------------------------- ### Download Oracle Graph Quickstart Image with Podman Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/running-oracle-graph-quickstart-container-image Pulls the latest `graph-quickstart` image from the Oracle Container Registry. This step can be skipped as the image will be automatically pulled when running the container. ```bash podman pull container-registry.oracle.com/database/graph-quickstart:25.2.0 ``` -------------------------------- ### Specify Keystore for PGX Server Startup Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-oracle-graph-autonomous-ai-database This code demonstrates how to modify the ExecStart command in the PGX systemd service file to include the location of the keystore file. This keystore contains the database password, allowing the PGX server to start and connect to the database securely. ```shell ExecStart=/bin/bash start-server --secret-store /etc/keystore.p12 ``` -------------------------------- ### Get Published Graphs Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/get-published-graphs Retrieves a list of all published graphs. The response includes details for each graph, mirroring the structure of cached graph information. ```APIDOC ## GET /published_graphs ### Description Retrieves a list of published graphs. Each entry contains information about a published graph, similar to the details found in `cached_graphs`. ### Method GET ### Endpoint `/published_graphs` ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **published_graphs** (list) - A list of objects, where each object represents a published graph and contains its details. #### Response Example ```json { "published_graphs": [ { "graph_name": "string", "creation_date": "string", "last_modified": "string", "status": "string" } ] } ``` ``` -------------------------------- ### Start PGX Server Environment (Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-autonomous-ai-database-graph-client Starts the PGX server environment with a specified memory allocation in Python. It checks if the environment is already attached, starts it if not, and retrieves job details upon completion. ```python >>> client.is_attached() False >>> job = client.start_environment(10) >>> job.get() >>> job.get_name() 'Environment Creation - 16 GBs' >>> job.get_created_by() 'ADBDEV' >>> client.is_attached() True ``` -------------------------------- ### Log in to Oracle Container Registry with Podman Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/running-oracle-graph-quickstart-container-image Authenticates your host system with the Oracle Container Registry. Ensure proxy environment variables are configured if behind a firewall. You will be prompted for your Oracle account username and an authentication token for the password. ```bash podman login container-registry.oracle.com ``` -------------------------------- ### Examples of PGQL Queries Triggering Lazy Loading (JShell, Java, Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/reading-graphs-database-graph-server-pgx Provides examples of various PGQL queries that will initiate the lazy loading of a graph named 'MY_GRAPH' into the PGX server. These examples cover `queryPgql`, `preparePgql`, `executePgql`, and `explainPgql` across JShell, Java, and Python. ```jshell opg4j> session.queryPgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH") opg4j> session.preparePgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH WHERE x.age = ?") opg4j> session.executePgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH") opg4j> session.explainPgql("SELECT x.name, x.* FROM MATCH (x) ON MY_GRAPH") ``` ```java session.queryPgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH"); session.preparePgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH WHERE x.age = ?"); session.executePgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH"); session.explainPgql("SELECT x.name, x.* FROM MATCH (x) ON MY_GRAPH"); ``` ```python session.query_pgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH") session.prepare_pgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH WHERE x.age = ?") session.execute_pgql("SELECT x.name FROM MATCH (x) ON MY_GRAPH") session.explain_pgql("SELECT x.name, x.* FROM MATCH (x) ON MY_GRAPH") ``` -------------------------------- ### Start OPG4J Shell and Import Libraries (JShell) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/loading-graph-using-unsupervised-anomaly-detection-graphwise-algorithm Starts the Oracle Property Graph (OPG4J) shell and imports necessary Java classes for machine learning configurations. This is the initial step before interacting with the graph database. ```java cd /opt/oracle/graph/ ./bin/opg4j // starting the shell will create an implicit session and analyst opg4j> import oracle.pg.config.mllib.ActivationFunction opg4j> import oracle.pgx.config.mllib.WeightInitScheme ``` -------------------------------- ### Start PGX Server Environment (Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-autonomous-ai-database-graph-client-oci-data-science-notebooks This Python code starts a PGX server environment with a specified memory allocation. It submits a job to Graph Studio and waits for the environment to become available. The `client.isAttached()` method can be used to check the status. ```python memory_gb = 8 job = client.start_environment(memory_gb) job.get() ``` -------------------------------- ### Get Edge Label Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/syntax Returns the label of an edge. This function is used to identify or filter edges based on their labels. ```Java string .label() ``` -------------------------------- ### Get Vertex Degree Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/syntax Retrieves the number of incoming or outgoing edges for a given vertex. `degree()` is an alias for `outDegree()`. ```Java int .degree() int .outDegree() int .inDegree() ``` -------------------------------- ### Navigate to Graph Directory Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-self-signed-server-keystore Changes the current directory to the Oracle Graph installation path. This is a prerequisite for generating keystores. ```shell cd /etc/oracle/graph ``` -------------------------------- ### Get Published Graphs using serverState Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/get-published-graphs Retrieves a list of published graphs from the Oracle Property Graph server. The returned graph entries contain details analogous to those found in cached graphs. This functionality is part of the Admin API. ```text serverState.get("published_graphs") ``` -------------------------------- ### CREATE PROPERTY GRAPH Statement Example Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs An example of a `CREATE PROPERTY GRAPH` statement defining a graph named 'people'. It specifies vertex tables ('person') with a key on 'id' and edge tables ('knows') with composite keys referencing the 'person' vertices. This setup is used to illustrate performance considerations for recursive queries. ```sql CREATE PROPERTY GRAPH people VERTEX TABLES( person KEY ( id ) LABEL person PROPERTIES( name, age ) ) EDGE TABLES( knows key (person1, person2) SOURCE KEY ( person1 ) REFERENCES person (id) DESTINATION KEY ( person2 ) REFERENCES person (id) NO PROPERTIES ) OPTIONS ( PG_PGQL ) ``` -------------------------------- ### PGQL Recursive Query for AVG Aggregation Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs Demonstrates the AVG aggregation function for recursive PGQL queries. This example computes the average age of destination persons in paths starting from a specified person. ```sql SELECT AVG(dst.age) FROM MATCH TOP 2 SHORTEST ( (n:Person) (-[e:knows]->(dst))* (m:Person) ) WHERE n.id = 1234 ``` -------------------------------- ### OPG4J Shell Prompt Example Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/interactive-graph-shell-clis Displays the command-line prompt that appears after successfully starting the OPG4J shell. It indicates the available variables and provides a help command. ```shell For an introduction type: /help intro Oracle Graph Server Shell 26.1.0 Variables instance, session, and analyst ready to use. opg4j> ``` -------------------------------- ### PGX Server Configuration Example (JSON) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/starting-graph-server-pgx An example JSON configuration for the Oracle Graph Server (PGX). This snippet demonstrates how to set parameters such as port, TLS enablement, and keystore details for secure server operation. ```json { "port": 7007, "enable_tls": true, "server_keystore": "/pgx/cert/server_keystore.rsa", "server_keystore_alias": "pgx", "server_keystore_provider": "JsafeJCE", "server_keystore_type": "PKCS12" } ``` -------------------------------- ### Setting JAVA_HOME for OPG4j Shell Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/interactive-graph-shell-clis Demonstrates how to set the JAVA_HOME environment variable to switch between Java installations before starting the OPG4j shell. This is crucial for managing multiple Java versions. ```bash export JAVA_HOME=/usr/lib/jvm/java-11-oracle ``` -------------------------------- ### Build and Explain Graph with Supervised GraphWise (Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/explaining-prediction This Python snippet demonstrates building a simple graph, training a Supervised GraphWise model, and then explaining the prediction for a specific vertex. It covers graph construction, model explainer setup, and retrieving feature importances and vertex importances from the explanation. ```python simple_graph = session.create_graph_builder() .add_vertex(0).set_property("label_feature", 0.5).set_property("const_feature", 0.5) .set_property("label", True) .add_vertex(1).set_property("label_feature", -0.5).set_property("const_feature", 0.5) .set_property("label", False) .add_edge(0, 1).build() # build and train a Supervised GraphWise model as explained in Advanced Hyperparameter Customization # obtain the explainer explainer = model.gnn_explainer(learning_rate=0.05) explainer.num_optimization_steps=200 # explain prediction of vertex 0 explanation = explainer.inferAndExplain(simple_graph,simple_graph.get_vertex(0)) # if we used the devNet loss, we can add the decision threshold as an extra parameter: # explanation = explainer.inferAndExplain(simple_graph, simple_graph.get_vertex(0), 6) const_property = simple_graph.get_vertex_property("const_feature") label_property = simple_graph.get_vertex_property("label_feature") # retrieve feature importances feature_importances = explanation.get_vertex_feature_importance() importance_const_prop = feature_importances[const_property] importance_label_prop = feature_importances[label_property] # retrieve computation graph with importances importance_graph = explanation.get_importance_graph() # retrieve importance of vertices importance_property = explanation.get_vertex_importance_property() importance_vertex_0 = importance_property[0] importance_vertex_1 = importance_property[1] ``` -------------------------------- ### Example Query Result Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-autonomous-ai-database-graph-client The expected output when running the PGQL query in the provided Java example. It shows the retrieved 'AMOUNT' value from the graph data. ```text AMOUNT = 7562 ``` -------------------------------- ### SQL Query: Cyclic Path Patterns Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/examples-sql-property-graph-queries Illustrates a SQL query using GRAPH_TABLE to find cyclic path patterns. This specific query looks for cycles of three 'friends' edges that start and end at the same 'person' node. ```sql SELECT * FROM GRAPH_TABLE (students_graph MATCH (a IS person) -[IS friends]-> (b IS person) -[IS friends]-> (c IS person) -[IS friends]-> (a) COLUMNS (a.name AS person_a, b.name AS person_b, c.name AS person_c) ); ``` -------------------------------- ### Get Training Loss for Unsupervised Anomaly Detection Model (JShell, Java, Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/getting-loss-value-unsupervised-anomaly-detection-graphwise-model This snippet demonstrates how to fetch the training loss value for an Unsupervised Anomaly Detection GraphWise model. It provides examples for JShell, Java, and Python, utilizing the `getTrainingLoss()` or `get_training_loss()` method. No external dependencies are required beyond the Oracle Property Graph environment. ```jshell opg4j> var loss = model.getTrainingLoss() ``` ```java double loss = model.getTrainingLoss(); ``` ```python loss = model.get_training_loss() ``` -------------------------------- ### Explain PGQL Query Plan and Print - Java Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/best-practices-tuning-pgql-queries Demonstrates how to use the `explainPgql` method to retrieve and print the query plan for a given Pgql query. The `print()` method displays the operation tree, including details like cardinality, cost, and accumulated cost for each operation. This helps in understanding the query execution strategy. ```Java g.explainPgql("SELECT COUNT(*) FROM MATCH (n) -[e1]-> (m) -[e2]-> (o)").print() ``` -------------------------------- ### Create DBMS_GVT Package and APEX_SQLGRAPH_JSON Function Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/getting-started-apex-graph-visualization-plug This section details the process of creating necessary PL/SQL components, specifically the `DBMS_GVT` package and the `APEX_SQLGRAPH_JSON` function, which are required for the Graph Visualization plug-in to process graph data. ```sql -- Upload and run the required-for-26ai/gvt_sqlgraph_to_json.sql script -- Upload and run the required-for-26ai/required_helper_functions.sql script ``` -------------------------------- ### Start PGX with Custom Configuration (Bash) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/using-graph-server-pgx-library This command starts a local Oracle Property Graph Server (PGX) instance using a custom configuration file. The `--pgx_conf` option specifies the path to the desired configuration file, overriding the default location. ```bash # start local PGX instance with custom config ./bin/opg4j --pgx_conf ``` -------------------------------- ### Define Edge Collection Filter using Python Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/defining-collection-filters Provides a Python example for defining an edge collection filter using the pypgx library. It requires importing EdgeFilter and using the from_collection method with an edge collection. ```Python from pypgx.api.filters import EdgeFilter # Obtain an edge collection from an algorithm, query execution or any other way edge_collection = ... # Define a filter from the collection edge_filter = EdgeFilter.from_collection(edge_collection) ``` -------------------------------- ### Execute PGQL SELECT Query using PgqlStatement and PgqlResultSet (Java) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs This Java example demonstrates executing a PGQL SELECT query on an Oracle property graph. It establishes a JDBC connection, obtains a PgqlConnection, sets the graph, creates a PgqlStatement, executes the query, and prints the results using PgqlResultSet. Ensure Oracle JDBC and property graph libraries are included. ```Java import java.sql.Connection; import java.sql.Statement; import java.sql.DriverManager; import oracle.pg.rdbms.pgql.PgqlConnection; import oracle.pg.rdbms.pgql.PgqlResultSet; import oracle.pg.rdbms.pgql.PgqlStatement; /* * This example shows how to execute a SELECT query on a PGQL property graph. */ public class PgqlExample1 { public static void main(String[] args) throws Exception { int idx=0; String jdbcUrl = args[idx++]; String username = args[idx++]; String password = args[idx++]; String graph = args[idx++]; Connection conn = null; PgqlStatement pgqlStmt = null; PgqlResultSet rs = null; try { //Get a jdbc connection conn = DriverManager.getConnection(jdbcUrl, username, password); conn.setAutoCommit(false); // Get a PGQL connection PgqlConnection pgqlConn = PgqlConnection.getConnection(conn); pgqlConn.setGraph(graph); // Create a PGQL Statement pgqlStmt = pgqlConn.createStatement(); // Execute PGQL Query String query = "SELECT n.* FROM MATCH (n:Accounts) LIMIT 5"; rs = pgqlStmt.executeQuery(query); // Print the results rs.print(); } finally { // close the result set if (rs != null) { rs.close(); } // close the statement if (pgqlStmt != null) { pgqlStmt.close(); } // close the connection if (conn != null) { conn.close(); } } } } ``` -------------------------------- ### Run SELECT Query with Prepared Statement using Java Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs This Java code demonstrates executing a PGQL SELECT query with a LIMIT clause using PgqlPreparedStatement. It requires standard JDBC drivers and the Oracle Property Graph client library. The program takes connection details and graph name as arguments, establishes a connection, prepares and executes the query, and prints the results. Error handling for resource closure is included. ```Java import java.sql.Statement; import java.sql.DriverManager; import oracle.pg.rdbms.pgql.*; public class PgqlExample2 { public static void main(String[] args) throws Exception { int idx=0; String jdbcUrl = args[idx++]; String username = args[idx++]; String password = args[idx++]; String graph = args[idx++]; Connection conn = null; PgqlStatement pgqlStmt = null; PgqlResultSet rs = null; try { //Get a jdbc connection conn = DriverManager.getConnection(jdbcUrl, username, password); conn.setAutoCommit(false); // Get a PGQL connection PgqlConnection pgqlConn = PgqlConnection.getConnection(conn); pgqlConn.setGraph(graph); // Execute PGQL Query String s = "SELECT n.* FROM MATCH (n:Accounts) LIMIT ?"; PgqlPreparedStatement pStmt = pgqlConn.prepareStatement(s, 0, 4 , 2 , -1 , null , null); pStmt.setInt(1,3); rs = pStmt.executeQuery(); // Print the results rs.print(); } finally { // close the result set if (rs != null) { rs.close(); } // close the statement if (pgqlStmt != null) { pgqlStmt.close(); } // close the connection if (conn != null) { conn.close(); } } } } ``` -------------------------------- ### Example Session Information in Server State JSON Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/get-inspection-data Provides a detailed view of the session information within the server state JSON. It shows individual session details, including session ID, source, and user information. ```JSON { "session_id": "530b5f9a-75c4-4838-9cc3-44df44b035c5", "source": "testServerState", "user": "user1", // session user information ... } ``` -------------------------------- ### Create Edge-to-Vertex Map using Graph-Bound Maps (Python) Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/graph-bound-maps Shows the Python syntax for creating a graph-bound map where edges are keys and vertices are values. This example uses the `create_map` function and accesses edge source properties. ```Python e0 = graph.get_edge(100) e1 = graph.get_edge(101) e2 = graph.get_edge(102) e3 = graph.get_edge(103) edge_to_long_map = graph.create_map("edge", "long", "edge_to_long_map") edge_to_long_map.put(e0, e0.source) edge_to_long_map.put(e1, e1.source) edge_to_long_map.put(e2, e2.source) edge_to_long_map.put(e3, e3.source) ``` -------------------------------- ### Start and Stop PGX Engine with Java Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/connecting-graph-server-pgx Provides methods to start and stop the PGX engine. `startEngine()` requires a JSON object for configuration. Stopping the engine can be done immediately, if running, or with a timeout, affecting new session creation and current tasks. ```java instance.shutdownEngineNow(); // cancels pending tasks, throws exception if engine is not running instance.shutdownEngineNowIfRunning(); // cancels pending tasks, only tries to shut down if engine is running if (instance.shutdownEngine(30, TimeUnit.SECONDS) == false) { // doesn't accept new tasks but finishes up remaining tasks // pending tasks didn't finish after 30 seconds } ``` -------------------------------- ### SQL Query for Graph Visualization Plug-in Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/getting-started-apex-graph-visualization-plug This SQL query is used within the APEX Graph Visualization plug-in to retrieve graph data when the 'SQL Query' type is selected. It defines vertices, edges, and filters for the graph traversal. ```sql SELECT * FROM GRAPH_TABLE ( BANK_SQL_PG MATCH (a IS accounts) -[e IS transfers]-> (b IS accounts) WHERE a.id = 816 COLUMNS(vertex_id(a) AS id_a, edge_id(e) AS id_e, vertex_id(b) AS id_b) ) ``` -------------------------------- ### Run SELECT Query with Grouping and Aggregation using Java Source: https://docs.oracle.com/en/database/oracle/property-graph/26.1/spgdg/executing-pgql-queries-pgql-property-graphs This Java example demonstrates executing a PGQL SELECT query with grouping and aggregation. It requires JDBC and Oracle Property Graph libraries. The code takes connection details as arguments, establishes a connection, retrieves a PGQL connection, creates a statement, executes a query that groups by vertex and counts edges, and prints the results. Resource management is handled in a finally block. ```Java import java.sql.Connection; import java.sql.Statement; import java.sql.DriverManager; import oracle.pg.rdbms.pgql.PgqlConnection; import oracle.pg.rdbms.pgql.PgqlResultSet; import oracle.pg.rdbms.pgql.PgqlStatement; /* * This example shows how to execute a SELECT query with aggregation .*/ public class PgqlExample3 { public static void main(String[] args) throws Exception { int idx=0; String jdbcUrl = args[idx++]; String username = args[idx++]; String password = args[idx++]; String graph = args[idx++]; Connection conn = null; PgqlStatement pgqlStmt = null; PgqlResultSet rs = null; try { //Get a jdbc connection conn = DriverManager.getConnection(jdbcUrl, username, password); conn.setAutoCommit(false); // Get a PGQL connection ```