How to avoid duplications return distinct nodes and the relation ship using neo4j

て烟熏妆下的殇ゞ 提交于 2019-12-10 16:44:26

问题


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.


回答1:


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!




回答2:


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);


来源:https://stackoverflow.com/questions/32677104/how-to-avoid-duplications-return-distinct-nodes-and-the-relation-ship-using-neo4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!