All Products
Search
Document Center

PolarDB:Graph analysis with PolarDB in the financial sector

Last Updated:Jun 21, 2026

This guide uses a public financial transaction dataset to demonstrate how to perform graph analysis with PolarDB. You will learn to run graph queries for fraud detection, discover relationships between fraudulent activities, and calculate the Jaccard similarity between transactions to help prevent fraud.

About the graph engine

PolarDB for PostgreSQL supports storage and querying of graph data through its Apache AGE extension. It lets you run both ANSI SQL and the openCypher graph query language against the same database cluster.

Apache AGE integrates directly with PolarDB for PostgreSQL as an extension — no separate graph database is needed.

image

Key capabilities:

  • Native PostgreSQL compatibility — AGE works with your existing PolarDB database. No reconstruction required. It inherits all PolarDB features: transaction support, concurrency control, and indexing.

  • Unified graph and relational queries — Run SQL and Cypher in a single query. This simplifies handling of complex data models that span relational and graph structures.

  • Cypher query language — AGE supports the Cypher query language, which provides an intuitive syntax for querying and manipulating graph data.

  • High performance — AGE combines PolarDB's query optimization with graph-specific indexes to handle large-scale graph data and complex traversals efficiently.

Use cases

Background

In modern fraud and financial crimes, fraudsters often use methods such as changing identities to evade risk control rules. By building a graph database to track the graph structure of user behavior, you can analyze discrete fraud data in real time and identify fraud rings. This allows you to quickly and effectively prevent and resolve fraudulent activities.

Data and model

This guide uses public datasets from the financial transaction domain. The data consists of transaction records for the e-commerce platform Vesta, including information about the devices, addresses, and email accounts involved in the transactions. You can use this dataset to identify fraudulent transactions and predict risks.

The raw data is in CSV format and contains transaction information (such as transaction ID, address, and email) and identity information (such as device information and device type). This guide abstracts the extensive dataset into the data model shown in the following figure. You can adjust the model based on your specific business requirements.

image
  • Vertices

    • transaction: The transaction.

    • product: The product involved in the transaction.

    • addr1: The primary billing address for the transaction.

    • addr2: The secondary billing address for the transaction.

    • emaildomain: The email domain used for the transaction.

    • deviceinfo: The device information for the transaction.

    • devicetype: The type of device used for the transaction.

  • Edges

    • transaction_product: The relationship between a transaction and a product.

    • transaction_addr1: The relationship between a transaction and the primary address.

    • transaction_addr2: The relationship between a transaction and the secondary address.

    • transaction_emaildomain: The relationship between a transaction and an email domain.

    • transaction_deviceinfo: The relationship between a transaction and device information.

    • transaction_devicetype: The relationship between a transaction and a device type.

This model is centered around transactions, which are linked by their transaction ID (transactionid).

Best practices

Note

This solution uses the AGE project's graph data visualization tool to display query results graphically.

Configurations

For an optimal experience, we recommend the following configurations for your PolarDB cluster:

  • Product: Standard Edition

  • Database engine: PostgreSQL 14

  • Revision version: >=14.12.23.1

  • CPU: >= 4 cores

  • Memory: >= 16 GB

  • Disk: >= 100 GB

Database preparation

  1. Install the AGE extension using a privileged account.

    CREATE EXTENSION age;
  2. Add the extension to the search path and preload library for the required user or database.

    • Load the extension for the current session:

      Note

      Compatibility issues may occur when you use Data Management (DMS) to configure the search_path. In such cases, you can use PolarDB-Tools to execute related statements.

      SET search_path = ag_catalog, "$user", public;
      SELECT * FROM get_cypher_keywords() limit 0;
    • Load the extension permanently:

      ALTER DATABASE <dbname> SET search_path = ag_catalog, "$user", public;
      ALTER DATABASE <dbname> SET session_preload_libraries TO 'age';

Loading data

  1. Create a graph. Use the create_graph function in the ag_catalog schema to create a graph. In this example, the graph is named fraud_graph.

    SELECT create_graph('fraud_graph');
  2. Insert vertices and edges. The downloaded CSV data cannot be loaded directly as a graph. You must first convert it to a vertex and edge structure. Contact us to obtain the Python script for converting the data into vertices and edges in PolarDB. The following code shows samples of the converted data:

    • Sample vertex data

      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:transaction {transactionid : 2990783, isfraud : 0 } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:product {productid : 158945 } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:addr1 {addr1 : '299.0' } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:addr2 {addr2 : '87.0' } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:emaildomain {emaildomain : 'gmail.com' } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:deviceinfo {deviceinfo : 'SM-G920V Build/NRD90M' } ) RETURN v $$ ) as (n agtype);
      SELECT * FROM cypher('fraud_graph', $$ MERGE (v:devicetype {devicetype : 'mobile' } ) RETURN v $$ ) as (n agtype);
      ...
    • Sample edge data

      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:product) WHERE a.transactionid = 2990783 AND b.productid = 158945 MERGE (a)-[e:transaction_product]->(b) RETURN e$$) as (e agtype);
      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:addr1) WHERE a.transactionid = 2990783 AND b.addr1 = '299.0' MERGE (a)-[e:transaction_addr1]->(b) RETURN e$$) as (e agtype);
      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:addr2) WHERE a.transactionid = 2990783 AND b.addr2 = '87.0' MERGE (a)-[e:transaction_addr2]->(b) RETURN e$$) as (e agtype);
      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:emaildomain) WHERE a.transactionid = 2990783 AND b.emaildomain = 'gmail.com' MERGE (a)-[e:transaction_emaildomain_p]->(b) RETURN e$$) as (e agtype);
      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:deviceinfo) WHERE a.transactionid = 2999403 AND b.deviceinfo = 'SM-G920V Build/NRD90M' MERGE (a)-[e:transaction_deviceinfo]->(b) RETURN e$$) as (e agtype);
      SELECT * FROM cypher('fraud_graph', $$ MATCH (a:transaction), (b:devicetype) WHERE a.transactionid = 2999404 AND b.devicetype = 'mobile' MERGE (a)-[e:transaction_devicetype]->(b) RETURN e$$) as (e agtype);
      ...

    Save the converted results as a SQL file. You can then use a client tool, such as psql, to import the data.

Examples

Simple queries

Statistics

  • Count the total number of nodes.

    SELECT *
    FROM cypher('fraud_graph', $$
        MATCH (n)
        RETURN count(*)
    $$) as (number_of_vertex agtype);

    The command returns the following result:

     number_of_vertex
    ----
     1076004
  • Count the number of transaction nodes.

    SELECT *
    FROM cypher('fraud_graph', $$
        MATCH (n:transaction)
        RETURN count(*)
    $$) as (number_of_transaction agtype);

    The command returns the following result:

    number_of_transaction 
    ----
    545591
  • Count the number of transactions identified as fraudulent.

    SELECT *
    FROM cypher('fraud_graph', $$
        MATCH (n:transaction)
        WHERE n.isfraud = 1
        RETURN count(*)
    $$) as (number_of_fraud_transaction agtype);

    The command returns the following result:

    number_of_fraud_transaction 
    ----
     18919
  • Count the total number of edges.

    SELECT *
    FROM cypher('fraud_graph', $$
        MATCH ()-[r]->()
        RETURN count(*)
    $$) as (number_of_edge agtype);

    The command returns the following result:

    number
    ------
     2131254

Filter and sort queries

Query the transaction with ID 2988706 and all its associated information.

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[r]->(v)
    WHERE n.transactionid = 2988706
    RETURN v
$$) as (e agtype);

The command returns the following result:

    e
---------
 {"id": 2251799813685249, "label": "addr2", "properties": {"addr2": "87.0"}}::vertex
 {"id": 2533274790395906, "label": "emaildomain", "properties": {"emaildomain": "gmail.com"}}::vertex
 {"id": 2533274790395906, "label": "emaildomain", "properties": {"emaildomain": "gmail.com"}}::vertex
 {"id": 1970324836974595, "label": "addr1", "properties": {"addr1": "325.0"}}::vertex
 {"id": 1125899906844295, "label": "product", "properties": {"productid": 137934}}::vertex

The following is a preview of the SQL query result in the age-viewer visualization tool:

The central transaction node connects to four related nodes, addr1, addr2, emaildomain, and product, through five edges: [:transaction_addr1], [:transaction_addr2], [:transaction_emaildomain_p], [:transaction_emaildomain_r], and [:transaction_product].

Common use cases

K-nearest neighbors (KNN)

The k-nearest neighbors (KNN) method identifies potential fraud by evaluating the similarity between data nodes. By finding the K neighbors with features most similar to a given data node, you can determine whether that node is normal. For example, a transaction may be marked as suspicious if it differs significantly from most of its neighboring transaction nodes in features like amount, location, or time.

Query for other transactions (2-hop neighbors) that share the same address as transaction 2988706 to determine if the original transaction is suspicious.

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[:transaction_addr1]->(:addr1)<-[:transaction_addr1]-(t:transaction)
    WHERE n.transactionid = 2988706
    RETURN t
$$) as (e agtype);

The command returns the following result:

  e
-----
 {"id": 844424930131972, "label": "transaction", "properties": {"isfraud": 0, "transactionid": 2987001}}::vertex
 {"id": 844424930131978, "label": "transaction", "properties": {"isfraud": 0, "transactionid": 2987007}}::vertex
 {"id": 844424930132041, "label": "transaction", "properties": {"isfraud": 0, "transactionid": 2987070}}::vertex
 {"id": 844424930132053, "label": "transaction", "properties": {"isfraud": 0, "transactionid": 2987082}}::vertex
....

To preview the results in the age-viewer visualization tool, run the following SQL query:

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[r:transaction_addr1]->(a:addr1)<-[r2:transaction_addr1]-(t:transaction)
    WHERE n.transactionid = 2988706
    RETURN [n,r,a,r2,t]::path
    LIMIT 50
$$) as (e agtype);
Note

Only 50 records are returned. Returning too much data may cause the front-end system to crash.

image

Pathfinding

In fraud detection, pathfinding involves using graph theory and network analysis to identify potential fraudulent activities. In financial networks, a transaction can be viewed as a graph where nodes represent accounts or customers, and edges represent transaction activities. By analyzing the structure of this graph, you can discover abnormal patterns and fraudulent behavior. Calculating paths between transactions helps you quickly identify transaction chains from a suspicious account to others, revealing hidden connections between seemingly unrelated accounts.

Query the path between transaction 2987000 and transaction 2987172 through fraudulent transactions to find all fraud chains that connect them.

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[r]->(v)<-[r1]-(t:transaction)-[r2]->(v2)<-[r3]-(k:transaction)
    WHERE n.transactionid = 2987000 
        and k.transactionid=2987172
        and t.isfraud = 1
    RETURN t 
$$) as (e agtype);

The command returns the following result:

 e
----
 {"id": 844424930618281, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3473312}}::vertex
 {"id": 844424930626886, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3481917}}::vertex
 {"id": 844424930649640, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3504671}}::vertex
 {"id": 844424930631805, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3486836}}::vertex
 {"id": 844424930641980, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3497011}}::vertex
 {"id": 844424930644942, "label": "transaction", "properties": {"isfraud": 1, "transactionid": 3499973}}::vertex

To preview the results in the age-viewer visualization tool, run the following SQL query:

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[r]->(v)<-[r1]-(t:transaction)-[r2]->(v2)<-[r3]-(k:transaction)
    WHERE n.transactionid = 2987000 
        and k.transactionid=2987172
        and t.isfraud = 1
    RETURN [n,r,v,r1,t,r2,v2,r3,k]::path
    LIMIT 50
$$) as (e agtype);
Note

Only 50 records are returned. Returning too much data may cause the front-end system to crash.

image

Common neighbor

In fraud detection, common neighbor analysis is a graph-based technique that identifies possible fraudulent behavior by analyzing social or transactional networks. This method primarily relies on graph theory to analyze the relationship network among transaction participants and find suspicious transaction patterns. If two transactions share multiple common neighbors that exhibit abnormal behavior (such as high-frequency transactions or unusual amounts), the transaction between these two traders may carry a higher risk of fraud.

Query for the common neighbors of transaction records 2987000 and 2987172 to find transactions with the same attributes, such as address or device.

SELECT *
FROM cypher('fraud_graph', $$
    MATCH (n:transaction)-[]->(v)<-[]-(t:transaction)
    WHERE n.transactionid = 2987000 and t.transactionid=2987172
    RETURN v
$$) as (e agtype);

The command returns the following result:

  e
-----
 {"id": 2251799813685249, "label": "addr2", "properties": {"addr2": "87.0"}}::vertex
 {"id": 1970324836974594, "label": "addr1", "properties": {"addr1": "315.0"}}::vertex

The following is a preview of the SQL query result in the age-viewer visualization tool:

image

Jaccard similarity

Jaccard similarity measures the similarity between two sets. The formula is:

Where:

  • J(A,B) is the Jaccard similarity of sets A and B.

  • ∣A∩B∣ is the intersection of sets A and B.

  • ∣A∪B∣ is the union of sets A and B.

In fraud detection, Jaccard similarity has several applications:

  • Pattern recognition: Calculating the Jaccard similarity of user transactions or behaviors helps identify similar patterns, which can indicate potential fraud.

  • Customer group analysis: When analyzing customer behavior, you can use Jaccard similarity to compare similarities between customers. Customers with a higher similarity score may share similar risk profiles.

In this example, you can calculate the Jaccard similarity between two transactions based on their associated addresses, emails, and other information. A high degree of overlap in this information indicates a high similarity between the transactions.

  1. Create the required functions.

    • Create a function that gets all nodes associated with a specific transaction and returns an array of their IDs.

      CREATE OR REPLACE FUNCTION find_ids(transactionid integer)
      RETURNS bigint[]
      LANGUAGE plpgsql
      AS $function$
      DECLARE 
          sql VARCHAR;
          ids bigint[];
      BEGIN
        sql := 'SELECT array_agg(cast(e as bigint)) FROM (
      SELECT *
      FROM cypher(''fraud_graph'', $$
      MATCH (n:transaction)-[]->(v)
          WHERE n.transactionid = ' || text($1) || 
      'RETURN id(v) 
      $$) as (e agtype)) as t;';
          EXECUTE sql INTO ids;
          return ids;
      END
      $function$;
    • Create two functions to perform Union and Intersection operations on arrays.

      CREATE OR REPLACE FUNCTION array_union(anyarray, anyarray)
      RETURNS anyarray 
      LANGUAGE sql immutable 
      AS $$
      SELECT array_agg(a ORDER BY a)
      FROM (
          SELECT DISTINCT unnest($1 || $2) AS a
      ) s;
      $$;
      CREATE OR REPLACE FUNCTION array_intersection(anyarray, anyarray)
      RETURNS anyarray 
      LANGUAGE sql immutable 
      AS $$
      SELECT array_agg(e)
      FROM (
          SELECT unnest($1)
          INTERSECT
          SELECT unnest($2)
      ) AS dt(e)
      $$;
    • Create a function to calculate the Jaccard similarity between two transactions.

      CREATE OR REPLACE FUNCTION jaccardSimilarity(tid1 integer, tid2 integer)
      RETURNS float8
      LANGUAGE plpgsql
      AS $function$
      DECLARE 
          sql VARCHAR;
          ids1 bigint[];
          ids2 bigint[];
          union_list bigint[];
          intersection_list bigint[];
      BEGIN
        ids1 = find_ids($1);
        ids2 = find_ids($2);
        union_list = array_union(ids1, ids2); -- union
        intersection_list = array_intersection(ids1, ids2); -- intersection
        RETURN 
          CASE 
              WHEN array_length(union_list,1) = 0 THEN 0
              ELSE array_length(intersection_list,1) * 1.0/ array_length(union_list,1) 
          END AS jaccardSimilarity;
      END
      $function$;
  2. Run the function to calculate the Jaccard similarity.

    • Compare the similarity between two specific transaction IDs:

      SELECT jaccardSimilarity(2987000, 2987172);

      The command returns the following result:

      jaccardsimilarity 
      ----
       0.4
  3. To compare the similarity across all transactions, you can use the stored procedure capabilities of PolarDB to perform more complex calculations.

    For example, you can use the following SQL statement to find all transactions that share the same primary address, secondary address, and email domain as transaction 2987002. The results are then sorted by Jaccard similarity to identify the 50 most similar transactions:

    WITH tmp AS
    (SELECT cast(e as integer) as transactionid
    FROM cypher('fraud_graph', $$
        MATCH (n:transaction)-[:transaction_addr2]->(:addr2)<-[:transaction_addr2]-(t:transaction)
        WHERE n.transactionid = 2987002
        MATCH (n:transaction)-[:transaction_addr1]->(:addr1)<-[:transaction_addr1]-(t:transaction)
        WHERE n.transactionid = 2987002 
        MATCH (n:transaction)-[:transaction_emaildomain_p]->(:emaildomain)<-[:transaction_emaildomain_p]-(t:transaction)
        WHERE n.transactionid = 2987002 
        RETURN t.transactionid
    $$) as (e agtype) )
    SELECT transactionid, jaccardSimilarity(2987002, transactionid) as jaccardSimilarity
    FROM tmp
    ORDER by jaccardSimilarity DESC
    LIMIT 50;

    The command returns the following result:

     transactionid | jaccardsimilarity 
    ---------------+-------------------
           3323911 |               0.6
           3328911 |               0.6
           3009043 |               0.6
           3039416 |               0.6
           3039425 |               0.6
           2993652 |               0.6
           3045027 |               0.6
           3037644 |               0.6
           3045041 |               0.6
    ...

    To preview the results in the age-viewer visualization tool, run the following SQL query. The transaction IDs in the query are the top 10 results from the previous calculation. You can adjust this list as needed.

    SELECT * 
    FROM cypher('fraud_graph', $$
        MATCH (n:transaction)-[r]->(v)<-[r2]-(t:transaction)
        WHERE n.transactionid = 2987002
            AND t.transactionid IN [3323911, 3328911,3009043,3039416,3039425,2993652,3045027,3037644,3045041,3045049,3045279]
        RETURN [n,r,v,r2,t]::path
    $$) as (e agtype);

Summary

This guide demonstrated how to analyze graph data using the graph analysis capabilities of PolarDB for PostgreSQL and . By combining the AGE extension, PolarDB provides powerful features for graph data computation and analysis, including the use of the Cypher query language to efficiently process graph queries. This capability provides robust support for unified data management and analysis in your enterprise.

Free trial

Visit the PolarDB Free Trial page, and select PolarDB for PostgreSQL to experience the graph computing capabilities of GanosBase.