在使用python操作neo4j的时候,如果查询的数据比较多,结构比较复杂的时候,返回的数据量会比较大,而且信息比较多,并且不唯一。所以写了该方法,用于查询比较复杂的数据。
1 def query_graph(query): 2 graph = get_graph() 3 data = graph.run(query).data() 4 5 node_ids = [] 6 new_nodes = [] 7 new_links = [] 8 9 for a in data: 10 for tk,tv in a.items(): 11 nodes = tv.nodes 12 relations = tv.relationships 13 for n in nodes: 14 if n.identity in node_ids: 15 continue 16 obj = {} 17 obj["id"] = n.identity 18 obj["label"] = [] 19 if n.labels is not None: 20 for la in n.labels: 21 obj["label"].append(la) 22 for k,v in n.items(): 23 obj[k] = v 24 node_ids.append(n.identity) 25 new_nodes.append(obj) 26 for r in relations: 27 if r.identity in node_ids: 28 continue 29 li = {} 30 li["id"] = r.identity 31 if r.types() is not None: 32 li["label"] = [] 33 for la in r.types(): 34 li["label"].append(la) 35 li["source"] = r.start_node.identity 36 li["target"] = r.end_node.identity 37 for k,v in r.items(): 38 li[k] = v 39 node_ids.append(r.identity) 40 new_links.append(li) 41 result = {} 42 result["nodes"] = new_nodes 43 result["links"] = new_links 44 return result