python查詢neo4j的數據以字典的方式返回數據


在使用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM