1

I have the output as a pandas data frame. I am trying to write a cypher query to give this data frame as the input to Neo4j and create a graph with relations extracted from its source and target.

If anyone has any idea on how to proceed further, please guide me in this.

[Pandas Dataframe]

1

eshirvana
  • 23,227
  • 3
  • 22
  • 38
S.Sushmi
  • 13
  • 3
  • paste the dataframe as text/code .remove screenshot and also show us your desired output – eshirvana Sep 21 '22 at 03:26
  • i found a basic implementation about what are u trying to achieve ```python3 query_string = ''' MATCH (c:Category) RETURN c.category_name, SIZE(()-[:IN_CATEGORY]->(c)) AS inDegree ORDER BY inDegree DESC LIMIT 20 ''' top_cat_df = pd.DataFrame([dict(_) for _ in conn.query(query_string)]) top_cat_df.head(20) ``` also see: [Neo4j from Python](https://towardsdatascience.com/neo4j-cypher-python-7a919a372be7) – user11717481 Sep 21 '22 at 04:34
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 21 '22 at 04:34

1 Answers1

0

The key is how you pass the panda dataframe into the query. I used string format to parameterized source, target and relationship type.

from py2neo import Graph

df = pd.DataFrame([['Kimbal','sibling', 'Elon'],
                   ['Boring', 'owned_by', 'Elon']], 
                  columns=['source', 'relation_type', 'target'])

query = """
    MERGE (s:Source {{name: '{source}'}})
    MERGE (t:Target {{name: '{target}'}})
    MERGE (s)-[r:{relation_type}]->(t)
    RETURN s.name,t.name,type(r) as relation_type;"""

graph = Graph("bolt://localhost:7687", auth=("neo4j", "awesome_password"))
for d in df.values:
    result = graph.run(query.format(source=d[0], relation_type=d[1], target=d[2]))
    d = result.data()
    print(d)

Result:

[{'s.name': 'Kimbal', 't.name': 'Elon', 'relation_type': 'sibling'}]
[{'s.name': 'Boring', 't.name': 'Elon', 'relation_type': 'owned_by'}]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38