Cypher查询shortestPath时如何获取关系的起止节点ID及类型
Let's tackle your questions one by one, like we're troubleshooting together:
1. What is relationships(p) exactly?
When you match a path p = shortestPath(...), p is a Cypher path object that holds an ordered list of nodes and the relationships connecting them. The relationships(p) function pulls out all the relationship instances from that path.
The confusing output you're seeing right now is just the raw property key-value pairs of those relationships. By default, if you return a relationship directly (like collect(r)), Neo4j only shows its custom properties—not the critical metadata you need: start/end node IDs and relationship type. That's why it looks like unstructured property bundles instead of usable relationship data.
2. How to get start node ID, end node ID, and relationship type?
You can use Cypher's built-in functions to extract this metadata from each relationship r:
ID(startNode(r)): Grabs the internal ID of the relationship's starting nodeID(endNode(r)): Grabs the internal ID of the relationship's ending nodetype(r): Returns the string name of the relationship type (e.g.,:INTERACTS,:HOMOLOG)
Quick tip: In Neo4j 4.0+, use
elementId()instead ofID().elementId()gives a stable, external identifier for nodes/relationships, whereasID()is an internal ID that can get reused when elements are deleted.
3. Is your proposed solution feasible?
Absolutely! Your revised Cypher query is spot-on—let's tweak it a bit for clarity and completeness:
MATCH (nodeA),(nodeB), p = shortestPath((nodeA)-[*..15]-(nodeB)) WHERE ID(nodeA) = 1332076 AND ID(nodeB) = 1459451 UNWIND nodes(p) as n UNWIND relationships(p) as r RETURN collect(distinct { id : ID(n), labels : labels(n), data: n}) as nodes, collect({ relationshipId : ID(r), startId : ID(startNode(r)), type : type(r), endId: ID(endNode(r)), properties: properties(r) // Optional: include relationship properties if needed }) as edges
Key details about this query:
- I removed
distinctfrom theedgescollection because shortest paths never have duplicate relationships—no need to deduplicate here. - Added an optional
properties: properties(r)field to include the relationship's original properties (like yourTFFamily,BLAST_evaluedata) if you need them for building your Java subgraph. - Swap out
ID()forelementId()if you're on Neo4j 4.0+ for more reliable identifiers.
This query will return exactly the structured data you need:
- A
nodesarray with each node's ID, labels, and properties - An
edgesarray with each relationship's ID, start node ID, end node ID, type, and optional properties—perfect for generating your subgraph in Java.
内容的提问来源于stack exchange,提问作者ErEcTuS

