neo4jrediscyphergraph-databasesredisgraph

cypher aggregating common node type between two distinct node types


Graph View

Now I want to get the list of all workload-pairs and the ID of the API nodes in between them, if any. The cypher query that I tried is:

MATCH (w1)
MATCH (w1)-[awe:ACCESSES_WORKLOAD]->(w2 {deleted_time: -1})
OPTIONAL MATCH (w2)-[:CONTAINS_API]->(a:API)
OPTIONAL MATCH (w1)-[:ACCESSES_API]->(a)
OPTIONAL MATCH (w1)-[cae:CAUSES_ATTACK]->(a)
WHERE ID(w1) IN %s
RETURN DISTINCT awe, w1, w2, collect(ID(a)), collect(distinct cae.name)

An output that I was expecting was table like below:

w1             | w2          | API IDs List           | Attack Name
======================================================================
front-end-node | user-node   | [6 elements in a list] | null
orders-node    | user-node   | [2 elements in a list] | null
front-end-node | orders-node | [3 elements in a list] | null
front-end-node | some-node   | [1 element in a list]  | attack-name

But what I am getting is:

w1             | w2          | API IDs List           | Attack Name
======================================================================
front-end-node | user-node   | [8 elements in a list] | null
orders-node    | user-node   | [8 elements in a list] | null
front-end-node | orders-node | [3 elements in a list] | null
front-end-node | some-node   | [1 element in a list]  | attack-name

In the first two rows, for the user node, I am getting the list of all the APIs contained by the user workload and not just the APIs accessed by the front-end and orders. The collect(ID(a)) is aggregating all the API nodes with a CONTAINS_API edge/relationship with the w2 WORKLOAD in the query instead of the APIs with only ACCESSES_API with w1 workload.

If I were to map my expectation to JSON for brevity, the output I require will be like:

{
  sourceWorkloadID: <ID(front-end)>
  targetWorkloadID: <ID(user)>
  apis: [ ID(/cards), ID(/register), ID(/addresses), ID(/customers/...)]  // len here is six
  attack: null
},
{
  sourceWorkloadID: <ID(orders)>
  targetWorkloadID: <ID(user)>
  apis: [ ID(/cards/{cardsId), ID(/addresses/{addressesId})] // len here is two
  attack: null
}, {3rd row}, {4th row}

Can someone help fix the cypher query ? I am doing this in redisgraph via cypher. I cannot use neo4j-only query options/utils/helpers. Thanks.


Solution

  • The way to do this is to do the edge matching into the same line as the API MATCH:

    MATCH (w1)
    MATCH (w1)-[awe:ACCESSES_WORKLOAD]->(w2 {deleted_time: -1})
    OPTIONAL MATCH (w2)-[:CONTAINS_API]->(a:API)<-[:ACCESSES_API]-(w1)
    OPTIONAL MATCH (w1)-[cae:CAUSES_ATTACK]->(a)
    WHERE ID(w1) IN %s
    RETURN DISTINCT awe, w1, w2, collect(ID(a)), collect(distinct cae.name)