2017-11-04 2 views
0

py2neo을 사용하여 cypher 쿼리에서 paths을 반환합니다. 결과를 Pandas DataFrame으로 파싱하고 싶습니다. 이송 할 수 있습니다 - cypher 쿼리는 다음 쿼리팬더로 py2neo 경로를 파싱

query='''MATCH p=allShortestPaths(p1:Type1)-[r*..3]-(p2:Type1) 
WHERE p1.ID =123456 
RETURN distinct(p)'' 
result = graph.run(query) 

결과 객체가 walkable 목적은 유사합니다. NodesRelationships은 동일한 특성을 갖지 않습니다.
개체를 반복 할 때 가장 많이 쓰이는 방법은 무엇입니까 pythonic? 전체 경로를 처리 할 필요가 있거나 객체가 사전이므로 Pandas.from_dict 메서드를 사용할 수 있습니까? 때로는 경로의 길이가 동일하지 않은 문제가 있습니다.
현재 우리는 객체를 열거하고 있으며, 객체가 균등하지 않은 객체 인 경우 Node이고 그렇지 않으면 객체를 relationship으로 처리합니다.

for index, item in enumerate(paths): 
    if index%2 == 0: 
    #process as Node 
    else: 
    #process as Relationship 

우리는 isinstance 방법 즉

if isinstance(item, py2neo.types.Node): 
    #process as Node 

을 사용할 수 있습니다하지만 여전히 별도로 모든 요소를 ​​처리해야합니다. 다음과 같이

답변

0

나는 문제를 해결 :
내가 노드의 속성과 쿼리 경로, 노드와의 관계 우리가 할 수를 반환 가정 관계

def neo4j_graph_to_dict(paths, node_properties, rels_properties): 
    paths_dict=OrderedDict() 
    for (pathID, path) in enumerate(paths): 
     paths_dict[pathID]={} 
     for (i, node_rel) in enumerate(path): 
      n_properties = [node_rel[np] for np in node_properties] 
      r_properties = [node_rel[rp] for rp in rels_properties] 
      if isinstance(node_rel, Node): 
       node_fromat = [np+': {}|'for np in node_properties] 
       paths_dict[pathID]['Node'+str(i)]=('{}: '+' '.join(node_fromat)).format(list(node_rel.labels())[0], *n_properties)     
      elif isinstance(node_rel, Relationship): 
       rel_fromat = [np+': {}|'for np in rels_properties] 
       reltype= 'Rel'+str(i-1) 
       paths_dict[pathID][reltype]= ('{}: '+' '.join(rel_fromat)).format(node_rel.type(), *r_properties) 
    return paths_dict 

와 경로 목록을 수신하는 기능을 썼다 다음 코드를 실행하십시오.

query='''MATCH paths=allShortestPaths(
    (pr1:Type1 {ID:'123456'})-[r*1..9]-(pr2:Type2 {ID:'654321'})) 
    RETURN paths, nodes(paths) as nodes, rels(paths) as rels''' 

df_qf = pd.DataFrame(graph.data(query)) 
node_properties = set([k for series in df_qf.nodes for node in series for k in node.keys() ]) # get unique values for Node properites 
rels_properties = set([k for series in df_qf.rels for rel in series for k in rel.keys() ]) # get unique values for Rels properites 
wg = [(walk(path)) for path in df_qf.paths ] 
paths_dict = neo4j_graph_to_dict(wg, node_properties, rels_properties) 
df = pd.DataFrame(paths_dict).transpose() 
df = pd.DataFrame(df, columns=paths_dict[0].keys()).drop_duplicates()