A*

This section describes the A* Shortest Path algorithm in the Neo4j Graph Data Science library.

1. Introduction

The A* (pronounced "A-Star") Shortest Path algorithm computes the shortest path between two nodes. A* is an informed search algorithm as it uses a heuristic function to guide the graph traversal. The algorithm supports weighted graphs with positive relationship weights.

Unlike Dijkstra’s shortest path algorithm, the next node to search from is not solely picked on the already computed distance. Instead, the algorithm combines the already computed distance with the result of a heuristic function. That function takes a node as input and returns a value that corresponds to the cost to reach the target node from that node. In each iteration, the graph traversal is continued from the node with the lowest combined cost.

In GDS, the A* algorithm is based on the Dijkstra’s shortest path algorithm. The heuristic function is the haversine distance, which defines the distance between two points on a sphere. Here, the sphere is the earth and the points are geo-coordinates stored on the nodes in the graph.

The algorithm implementation is executed using a single thread. Altering the concurrency configuration has no effect.

2. Requirements

In GDS, the heuristic function used to guide the search is the haversine formula. The formula computes the distance between two points on a sphere given their longitudes and latitudes. The distance is computed in nautical miles.

In order to guarantee finding the optimal solution, i.e., the shortest path between two points, the heuristic must be admissible. To be admissible, the function must not overestimate the distance to the target, i.e., the lowest possible cost of a path must always be greater or equal to the heuristic.

This leads to a requirement on the relationship weights of the input graph. Relationship weights must represent the distance between two nodes and ideally scaled to nautical miles. Kilometers or miles also work, but the heuristic works best for nautical miles.

3. Syntax

This section covers the syntax used to execute the A* algorithm in each of its execution modes. We are describing the named graph variant of the syntax. To learn more about general syntax variants, see Syntax overview.

Example 1. A* syntax per mode
Run A* in stream mode on a named graph.
CALL gds.beta.shortestPath.astar.stream(
  graphName: String,
  configuration: Map
)
YIELD
  index: Integer,
  sourceNode: Integer,
  targetNode: Integer,
  totalCost: Float,
  nodeIds: List of Integer,
  costs: List of Float,
  path: Path
Table 1. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 2. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

['*']

yes

Filter the named graph using the given node labels.

relationshipTypes

String[]

['*']

yes

Filter the named graph using the given relationship types.

concurrency

Integer

4

yes

The number of concurrent threads used for running the algorithm.

Table 3. Algorithm specific configuration
Name Type Default Optional Description

sourceNode

Integer

n/a

no

The Neo4j node id of the source node.

targetNode

Integer

n/a

no

The Neo4j node id of the source node.

latitudeProperty

Float

n/a

no

The node property that stores the latitude value.

longitudeProperty

Float

n/a

no

The node property that stores the longitude value.

path

Boolean

false

yes

Iff true, the result contains a Cypher Path object.

Table 4. Results
Name Type Description

index

Integer

0-based index of the found path.

sourceNode

Integer

Source node of the path.

targetNode

Integer

Target node of the path.

totalCost

Float

Total cost from source to target.

nodeIds

List of Integer

Node ids on the path in traversal order.

costs

List of Float

Accumulated costs for each node on the path.

path

Path

The path represented as Cypher entity.

The mutate mode creates new relationships in the in-memory graph. Each relationship represents a path from the source node to the target node. The total cost of a path is stored via the totalCost relationship property.

Run A* in mutate mode on a named graph.
CALL gds.beta.shortestPath.astar.mutate(
  graphName: String,
  configuration: Map
)
YIELD
  relationshipsWritten: Integer,
  createMillis: Integer,
  computeMillis: Integer,
  postProcessingMillis: Integer,
  mutateMillis: Integer,
  configuration: Map
Table 5. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 6. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

['*']

yes

Filter the named graph using the given node labels.

relationshipTypes

String[]

['*']

yes

Filter the named graph using the given relationship types.

concurrency

Integer

4

yes

The number of concurrent threads used for running the algorithm.

mutateRelationshipType

String

n/a

no

The relationship type used for the new relationships written to the in-memory graph.

Table 7. Algorithm specific configuration
Name Type Default Optional Description

sourceNode

Integer

n/a

no

The Neo4j node id of the source node.

targetNode

Integer

n/a

no

The Neo4j node id of the source node.

latitudeProperty

Float

n/a

no

The node property that stores the latitude value.

longitudeProperty

Float

n/a

no

The node property that stores the longitude value.

Table 8. Results
Name Type Description

createMillis

Integer

Milliseconds for creating the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Unused.

mutateMillis

Integer

Milliseconds for adding relationships to the in-memory graph.

relationshipsWritten

Integer

The number of relationships that were added.

configuration

Map

The configuration used for running the algorithm.

The write mode creates new relationships in the Neo4j database. Each relationship represents a path from the source node to the target node. Additional path information is stored using relationship properties. By default, the write mode stores a totalCost property. Optionally, one can also store nodeIds and costs of intermediate nodes on the path.

Run A* in write mode on a named graph.
CALL gds.beta.shortestPath.astar.write(
  graphName: String,
  configuration: Map
)
YIELD
  relationshipsWritten: Integer,
  createMillis: Integer,
  computeMillis: Integer,
  postProcessingMillis: Integer,
  writeMillis: Integer,
  configuration: Map
Table 9. Parameters
Name Type Default Optional Description

graphName

String

n/a

no

The name of a graph stored in the catalog.

configuration

Map

{}

yes

Configuration for algorithm-specifics and/or graph filtering.

Table 10. General configuration for algorithm execution on a named graph.
Name Type Default Optional Description

nodeLabels

String[]

['*']

yes

Filter the named graph using the given node labels.

relationshipTypes

String[]

['*']

yes

Filter the named graph using the given relationship types.

concurrency

Integer

4

yes

The number of concurrent threads used for running the algorithm. Also provides the default value for 'writeConcurrency'.

writeConcurrency

Integer

value of 'concurrency'

yes

The number of concurrent threads used for writing the result to Neo4j.

writeRelationshipType

String

n/a

no

The relationship type used to persist the computed relationships in the Neo4j database.

Table 11. Algorithm specific configuration
Name Type Default Optional Description

sourceNode

Integer

n/a

no

The Neo4j node id of the source node.

targetNode

Integer

n/a

no

The Neo4j node id of the source node.

latitudeProperty

Float

n/a

no

The node property that stores the latitude value.

longitudeProperty

Float

n/a

no

The node property that stores the longitude value.

writeNodeIds

Boolean

false

yes

If true, the written relationship has a nodeIds list property.

writeCosts

Boolean

false

yes

If true, the written relationship has a costs list property.

Table 12. Results
Name Type Description

createMillis

Integer

Milliseconds for creating the graph.

computeMillis

Integer

Milliseconds for running the algorithm.

postProcessingMillis

Integer

Unused.

writeMillis

Integer

Milliseconds for writing relationships to Neo4j.

relationshipsWritten

Integer

The number of relationships that were written.

configuration

Map

The configuration used for running the algorithm.

3.1. Anonymous graphs

It is also possible to execute the algorithm on a graph that is projected in conjunction with the algorithm execution. In this case, the graph does not have a name, and we call it anonymous. When executing over an anonymous graph the configuration map contains a graph projection configuration as well as an algorithm configuration. All execution modes support execution on anonymous graphs, although we only show syntax and mode-specific configuration for the write mode for brevity.

For more information on syntax variants, see Syntax overview.

Run A* in write mode on an anonymous graph:
CALL gds.beta.shortestPath.astar.write(
  configuration: Map
)
YIELD
  relationshipsWritten: Integer,
  ranIterations: Integer,
  didConverge: Boolean,
  createMillis: Integer,
  computeMillis: Integer,
  writeMillis: Integer,
  configuration: Map
Table 13. General configuration for algorithm execution on an anonymous graph.
Name Type Default Optional Description

nodeProjection

String, String[] or Map

null

yes

The node projection used for anonymous graph creation via a Native projection.

relationshipProjection

String, String[] or Map

null

yes

The relationship projection used for anonymous graph creation a Native projection.

nodeQuery

String

null

yes

The Cypher query used to select the nodes for anonymous graph creation via a Cypher projection.

relationshipQuery

String

null

yes

The Cypher query used to select the relationships for anonymous graph creation via a Cypher projection.

nodeProperties

String, String[] or Map

null

yes

The node properties to project during anonymous graph creation.

relationshipProperties

String, String[] or Map

null

yes

The relationship properties to project during anonymous graph creation.

concurrency

Integer

4

yes

The number of concurrent threads used for running the algorithm. Also provides the default value for 'readConcurrency' and 'writeConcurrency'.

readConcurrency

Integer

value of 'concurrency'

yes

The number of concurrent threads used for creating the graph.

writeConcurrency

Integer

value of 'concurrency'

yes

The number of concurrent threads used for writing the result to Neo4j.

writeRelationshipType

String

n/a

no

The relationship type used to persist the computed relationships in the Neo4j database.

Table 14. Algorithm specific configuration
Name Type Default Optional Description

sourceNode

Integer

n/a

no

The Neo4j node id of the source node.

targetNode

Integer

n/a

no

The Neo4j node id of the target node.

latitudeProperty

Float

n/a

no

The node property that stores the latitude value.

longitudeProperty

Float

n/a

no

The node property that stores the longitude value.

writeNodeIds

Boolean

false

yes

Iff true, the written relationship has a nodeIds list property.

writeCosts

Boolean

false

yes

Iff true, the written relationship has a costs list property.

The results are the same as for running write mode with a named graph, see the write mode syntax above.

4. Examples

In this section we will show examples of running the A* algorithm on a concrete graph. The intention is to illustrate what the results look like and to provide a guide in how to make use of the algorithm in a real setting. We will do this on a small transport network graph of a handful nodes connected in a particular pattern. The example graph looks like this:

astar
The following Cypher statement will create the example graph in the Neo4j database:
CREATE (a:Station {name: 'Kings Cross',         latitude: 51.5308, longitude: -0.1238}),
       (b:Station {name: 'Euston',              latitude: 51.5282, longitude: -0.1337}),
       (c:Station {name: 'Camden Town',         latitude: 51.5392, longitude: -0.1426}),
       (d:Station {name: 'Mornington Crescent', latitude: 51.5342, longitude: -0.1387}),
       (e:Station {name: 'Kentish Town',        latitude: 51.5507, longitude: -0.1402}),
       (a)-[:CONNECTION {distance: 0.7}]->(b),
       (b)-[:CONNECTION {distance: 1.3}]->(c),
       (b)-[:CONNECTION {distance: 0.7}]->(d),
       (d)-[:CONNECTION {distance: 0.6}]->(c),
       (c)-[:CONNECTION {distance: 1.3}]->(e)

The graph represents a transport network of stations. Each station has a geo-coordinate, expressed by latitude and longitude properties. Stations are connected via connections. We use the distance property as relationship weight which represents the distance between stations in kilometers. The algorithm will pick the next node in the search based on the already traveled distance and the distance to the target station.

In the examples below we will use named graphs and native projections as the norm. However, anonymous graphs and/or Cypher projections can also be used.

The following statement will create a graph using a native projection and store it in the graph catalog under the name 'myGraph'.
CALL gds.graph.create(
    'myGraph',
    'Station',
    'CONNECTION',
    {
        nodeProperties: ['latitude', 'longitude'],
        relationshipProperties: 'distance'
    }
)

In the following example we will demonstrate the use of the A* Shortest Path algorithm using this graph.

4.1. Memory Estimation

First off, we will estimate the cost of running the algorithm using the estimate procedure. This can be done with any execution mode. We will use the write mode in this example. Estimating the algorithm is useful to understand the memory impact that running the algorithm on your graph will have. When you later actually run the algorithm in one of the execution modes the system will perform an estimation. If the estimation shows that there is a very high probability of the execution going over its memory limitations, the execution is prohibited. To read more about this, see Automatic estimation and execution blocking.

For more details on estimate in general, see Memory Estimation.

The following will estimate the memory requirements for running the algorithm in write mode:
MATCH (source:Station {name: 'Kings Cross'}), (target:Station {name: 'Kentish Town'})
CALL gds.beta.shortestPath.astar.write.estimate('myGraph', {
    sourceNode: id(source),
    targetNode: id(target),
    latitudeProperty: 'latitude',
    longitudeProperty: 'longitude',
    writeRelationshipType: 'PATH'
})
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
RETURN nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
Table 15. Results
nodeCount relationshipCount bytesMin bytesMax requiredMemory

5

5

984

984

"984 Bytes"

4.2. Stream

In the stream execution mode, the algorithm returns the shortest path for each source-target-pair. This allows us to inspect the results directly or post-process them in Cypher without any side effects.

For more details on the stream mode in general, see Stream.

The following will run the algorithm and stream results:
MATCH (source:Station {name: 'Kings Cross'}), (target:Station {name: 'Kentish Town'})
CALL gds.beta.shortestPath.astar.stream('myGraph', {
    sourceNode: id(source),
    targetNode: id(target),
    latitudeProperty: 'latitude',
    longitudeProperty: 'longitude',
    relationshipWeightProperty: 'distance'
})
YIELD index, sourceNode, targetNode, totalCost, nodeIds, costs
RETURN
    index,
    gds.util.asNode(sourceNode).name AS sourceNodeName,
    gds.util.asNode(targetNode).name AS targetNodeName,
    totalCost,
    [nodeId IN nodeIds | gds.util.asNode(nodeId).name] AS nodeNames,
    costs
ORDER BY index
Table 16. Results
index sourceNodeName targetNodeName totalCost nodeNames costs

0

"Kings Cross"

"Kentish Town"

3.3

[Kings Cross, Euston, Camden Town, Kentish Town]

[0.0, 0.7, 2.0, 3.3]

The result shows the total cost of the shortest path between node King’s Cross and Kentish Town in the graph. It also shows ordered lists of node ids that were traversed to find the shortest paths as well as the accumulated costs of the visited nodes. This can be verified in the example graph.

4.3. Mutate

The mutate execution mode updates the named graph with new relationships. Each new relationship represents a path from source node to target node. The relationship type is configured using the mutateRelationshipType option. The total path cost is stored using the totalCost property.

The mutate mode is especially useful when multiple algorithms are used in conjunction.

For more details on the mutate mode in general, see Mutate.

The following will run the algorithm in mutate mode:
MATCH (source:Station {name: 'Kings Cross'}), (target:Station {name: 'Kentish Town'})
CALL gds.beta.shortestPath.astar.mutate('myGraph', {
    sourceNode: id(source),
    targetNode: id(target),
    latitudeProperty: 'latitude',
    longitudeProperty: 'longitude',
    relationshipWeightProperty: 'distance',
    mutateRelationshipType: 'PATH'
})
YIELD relationshipsWritten
RETURN relationshipsWritten
Table 17. Results
relationshipsWritten

1

After executing the above query, the in-memory graph will be updated with new relationships of type PATH. The new relationships will store a single property totalCost.

4.4. Write

The write execution mode updates the Neo4j database with new relationships. Each new relationship represents a path from source node to target node. The relationship type is configured using the writeRelationshipType option. The total path cost is stored using the totalCost property. The intermediate node ids are stored using the nodeIds property. The accumulated costs to reach an intermediate node are stored using the costs property.

For more details on the write mode in general, see Write.

The following will run the algorithm in write mode:
MATCH (source:Station {name: 'Kings Cross'}), (target:Station {name: 'Kentish Town'})
CALL gds.beta.shortestPath.astar.write('myGraph', {
    sourceNode: id(source),
    targetNode: id(target),
    latitudeProperty: 'latitude',
    longitudeProperty: 'longitude',
    relationshipWeightProperty: 'distance',
    writeRelationshipType: 'PATH',
    writeNodeIds: true,
    writeCosts: true
})
YIELD relationshipsWritten
RETURN relationshipsWritten
Table 18. Results
relationshipsWritten

1

The above query will write one relationship of type PATH back to Neo4j. The relationship stores three properties describing the path: totalCost, nodeIds and costs.