I want to query a subgraph from a large graph data base with a given source. Say I want the top 25 neighbors of a given node, along with all the relations among this set of nodes, how should my query be?
At the moment I have:
MATCH (source {label:'source'}) -[:relation]-> (neighbors)
RETURN source,neighbors
LIMIT 25
This works in the neo4j browser, returning the 26 nodes as well as all the existing relations among those nodes. However, when I try execute the same query via py2neo:
py2neo.cypher.execute(query)
it only returns 26 nodes along with the 25 direct edge connections between the source and the 25 neighbors, which makes sense. But I wonder why there is a difference between the browser result versus the py2neo result. And how I can achieve the same result with all the edge connections returned.
In general, I would like to know the following smaller questions:
how to append a single node to a list of nodes in neo4j? e.g. nlist = neighbors + node
how to return all the relationships between two sets of nodes? e.g. return (a in nlist) -[:relation]-> (b in nlist)
Edits:
To visualize, I want the resulting graph to be something like this
rather than a star graph like this
Thanks for any comments.
About the difference between Neo4j Browser and py2neo result: probably you are using the graph visualization mode with the option "Connect result nodes" enable. Try disabling (below image) it or change the visualization mode to "Text", for example.
About the Cypher query, you can use collect()
to merge source
and neighbors
:
MATCH (source {label:'source'})-[:relation]->(neighbors)
WITH collect(source) + collect(neighbors) as all
UNWIND all AS nodes
RETURN nodes
In order to return the all the edges between two sets of nodes (in this case from set to itself), refer to this post:Neo4j, get all relationships between a set of nodes
Then the subgraph is returned with the Cypher query
MATCH (source {label:'source'})-[:relation]->(neighbors)
WITH collect(distinct source) + collect(neighbors) as all
UNWIND all AS nodes
MATCH (nodes)-[:relation]->(nei)
WHERE nei in nodes
RETURN nodes,nei