How to return node neighbours in Neo4j using java plugin?

434 views Asked by At

In Cypher returning neighbours would look like this:

START n=node({nodeId}) MATCH n--m RETURN m;

I struggle to create a Java-plugin that does the same. Afterwards i want to see the properties of the returned neighbours and so on. This is my code where I try to get the Relationships and their EndNodes. What am I doing wrong? I only get returned the node itself but nothing from the "while-Loop".

import java.util.Iterator;
import java.util.stream.Stream;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.logging.Log;
import org.neo4j.procedure.*;
import org.neo4j.procedure.Description;
import org.neo4j.procedure.Name;

public class Correlation {

@Context
public GraphDatabaseService db;

@Context
public Log log;


@UserFunction(value = "boris.getNeighbours")
@Description("boris.getNeighbours- finds Nodes one step away")
public Node passName2(@Name("nodeId") long nodeId)

{

    Node node = db.getNodeById( nodeId );
    Iterable<Relationship> rels = node.getRelationships();
    Iterator<Relationship> I_rel =  rels.iterator();

    while (I_rel.hasNext()) {
        Relationship rel = I_rel.next();
        Node endNode = rel.getEndNode();
        return endNode;
    }
return node;
}
}
1

There are 1 answers

0
Grapheneer On BEST ANSWER

This works:

public class NodeFinder {

@Context
public GraphDatabaseService db;

@Context
public Log log;

@Procedure 
@Description("finds Nodes one step away")
public Stream<NodeResult> passName2(@Name("nodeId") long nodeId)

{

    Node node = db.getNodeById(nodeId);
    Iterable<Relationship> rels = node.getRelationships();
    Stream<Relationship> relsStream = StreamSupport.stream(rels.spliterator(), false);
    Stream<NodeResult> myNodes = relsStream.map(r -> new NodeResult(r));  

    return myNodes;

}


public class NodeResult 
{
    //What i return
    public Node node;

     //Constructor
     public NodeResult(Relationship item) 
     {            
        this.node = item.getEndNode();
     }

}
}