Har
Har

Reputation: 31

Can we create a node in Neo4j having properties as dictionary using Python package py2neo?

I want to create a node having properties in dictionary using py2neo.

query = CREATE (movie:Movie {'a': 'b', 'c': 'd'}) RETURN movie

graph_db.cypher.execute(query)

Then it given an error.

So I need to change the properties of my node to {a: 'b', c: 'd'}.

Is there a way I can do it using py2neo? Or any alternate way?

Thanks

Upvotes: 3

Views: 4117

Answers (3)

HyperActive
HyperActive

Reputation: 1316

This will work in the py2neo package (current version 2021.0.1)

from py2neo import Graph
graph_db = Graph()

query = "CREATE (movie:Movie $props) RETURN movie"
graph_db.run(query, props={'a': 'b', 'c': 'd'})

as well as the official neo4j package

from neo4j import GraphDatabase
driver = GraphDatabase.driver()
graph_db = driver.session()

query = "CREATE (movie:Movie $props) RETURN movie"
graph_db.run(query, props={'a': 'b', 'c': 'd'})

Upvotes: 0

Portable
Portable

Reputation: 323

The following is py2neo v3 code to create a movie node with 'a' and 'b' properites using a dictionary

    import py2neo

    from py2neo import Graph, Node

    def authenticateAndConnect():
        # Authenticate
        py2neo.authenticate('localhost:7474', '<yourUserName>', '<yourPassword>')

        # Connect (your folder names may be different)
        return Graph('http://localhost:7474/default.graphdb/data/')

    def foo():
        graph = authenticateAndConnect()

        # Define a list of labels
        labels = [ 'Movie' ]

        # Define a dictionary
        properties = {'a': 'b', 'c':'d'}

        node = Node(*labels, **properties)
        graph.create(node)


    if __name__ == '__main__':
        foo()

Upvotes: 3

Martin Preusse
Martin Preusse

Reputation: 9369

You can use query parameters to create a node as described here: http://neo4j.com/docs/stable/cypher-parameters.html

parameter_dict = {'params': {'a': 'b', 'c': 'd'}}

query = "CREATE (movie:Movie {params}) RETURN movie"

graph.cypher.execute(query, parameters=parameter_dict)

Upvotes: 3

Related Questions