4
votes

I would like to return for a given node-id related nodes and their relationships props

For example: -> defines a bi direction relationship with property timestamp

1234->777
777->1234
1234->999
999->1234
1234->888
888->1234

1234,777,888,999 are node-ids

When I execute this:

    final PreparedStatement ps = conn.prepareStatement("start a = node(1234) match (a)-[k:nearby*]->(b) where a<>b return DISTINCT b, k");        
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
         Map result = (Map<String, Object>) rs.getObject("b");     
        System.out.println(result.toString());
    }

} catch (SQLException e) {
    e.printStackTrace();
    logger.error("Error returning userId=" + userIdInput, e);
}
return null;

}

I get:

{userId=777}
{userId=999}
{userId=888}
{userId=888}
{userId=999}
{userId=999}
{userId=777}
{userId=888}
{userId=888}
{userId=777}
{userId=888}
{userId=777}
{userId=999}
{userId=999}
{userId=777}
  1. How I do get distinct results only (777,888,999)
  2. How to retrieve the relationship props of 1234 to the dest node? I expect to get the timestamp prop which defined on each relationship

Thank you, ray.

2

2 Answers

2
votes

I'm not sure what language you're using so I'll focus on the Cypher. Firstly I would replace the START query with a MATCH with a WHERE on ID(a):

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234 AND a<>b
RETURN DISTINCT b, k

Secondly I'm pretty sure you don't need the a<>b because Cypher paths won't loop back on the same nodes:

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN DISTINCT b, k

Lastly, and to your question, I suspect the reason that you're getting duplicates is because you have multiple relationships. If so you can return the result node and an array of the relationships like so:

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN collect(b), k

That should return you node/relationship objects (with properties on both). Depending on your language/library you might get Maps or you might get objects wrapping the data

If your library doesn't return the start/end nodes for relationships for you, you can do something like this:

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN collect({rel: b, startnode: startnode(b), endnode: endnode(b)}), k

Hopefully that helps!

0
votes

You get non distinct results, because you return both b and k

If you only want to get distinct b's use:

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234 AND a<>b
RETURN DISTINCT b

You should also use parameters!

MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = {1} AND a<>b
RETURN DISTINCT b


ps.setInt(1,1234);