Search code examples
javaredisredisgraph

Redisgraph find shortest path between 2 nodes


I am new to using graph tech . Below is one sample data i have , i want to put this in redis graph and find the shortest distance between 2 points .

{"Entry":{"Reception":152},"Reception":{"Corner":176,"Exit":153},"Corner":{"Gate":41,"Reception":176},"Gate":{"LiftLobby":53,"Corner":41},"LiftLobby":{"Gate":53}}

For example in this json object distance between Entry and Reception point is 152 units . What are the redisgraph queries i should use to

  1. Add data to the redisgraph.
  2. To Find shortest distance between 2 points .

Solution

  • If I understand your problem correctly, that's how I would model this data in RedisGraph:

    • Create Loc entities with name property: Entry, Reception, Corner, Exit, Gate, LiftLoby
    • Create Way relationships between pairs of entities with dist property

    To find the shortest path between two places - use RedisGraph 2.10 algo.SPpaths procedure (see "Single-Pair minimal-weight bounded-cost bounded-length paths" here).

    Creating the graph:

    GRAPH.QUERY g "CREATE (e:Loc{name:'Entry'}), (r:Loc{name:'Reception'}), (c:Loc{name:'Corner'}), (x:Loc{name:'Exit'}), (g:Loc{name:'Gate'}), (l:Loc{name:'LiftLobby'}), (e)-[:Way{dist:152}]->(r), (r)-[:Way{dist:176}]->(c), (r)-[:Way{dist:153}]->(x), (c)-[:Way{dist:41}]->(g), (c)-[:Way{dist:176}]->(r), (g)-[:Way{dist:53}]->(l), (g)-[:Way{dist:41}]->(c), (l)-[:Way{dist:53}]->(g)"
    1) 1) "Labels added: 1"
       2) "Nodes created: 6"
       3) "Properties set: 14"
       4) "Relationships created: 8"
       5) "Cached execution: 0"
       6) "Query internal execution time: 0.788600 milliseconds"
    

    Querying for the shortest path between Entry and Gate:

    GRAPH.QUERY g "MATCH (e:Loc{name:'Entry'}), (g:Loc{name:'Gate'}) CALL algo.SPpaths( {sourceNode: e, targetNode: g, relTypes: ['Way'], weightProp: 'dist'} ) YIELD path, pathWeight RETURN pathWeight, [n in nodes(path) | n.name] as pathNodes ORDER BY pathWeight"
    1) 1) "pathWeight"
       2) "pathNodes"
    2) 1) 1) "369"
          2) "[Entry, Reception, Corner, Gate]"
    3) 1) "Cached execution: 0"
       2) "Query internal execution time: 0.540100 milliseconds"