introduction
Neo4j is a graph database that organizes and stores data through nodes and relationships. Using Neo4j, graph data can be easily represented and operated, such as social networks, recommendation systems, knowledge graphs, etc.
py2neo is a library in Python that interacts with Neo4j databases. It provides Neo4j with a Pythonic interface, which supports direct query, data insertion and update in Python.
1. Install py2neo
First, we need to install the py2neo library. Run the following command on the command line:
pip install py2neo
Make sure you have Neo4j installed and running locally, or use a remote Neo4j instance.
2. Connect to Neo4j
To connect to Neo4j via py2neo, you need to provide the URI, username and password of the Neo4j database. Usually, the default URI of Neo4j is bolt://localhost:7687, and the username and password are neo4j and the password you set respectively.
Code example:
from py2neo import Graph # Connect to the local Neo4j databasegraph = Graph("bolt://localhost:7687", auth=("neo4j", "your_password")) # Check if the connection is successfulprint(("RETURN 'Hello, Neo4j!'").data())
This code first passesGraph
The class connects to the Neo4j database and then executes a simple Cypher query to verify that the connection is successful. If the connection is successful, the returned result should be['Hello, Neo4j!']
。
3. Create nodes and relationships
Once the connection is successful, you can usepy2neo
The data is operated through Python. The following example shows how to create nodes and relationships.
1. Create a node
from py2neo import Node # Create node: Person nodeperson = Node("Person", name="John", age=30) # Save nodes to graph database(person) # Check whether the node is created successfullyprint(person)
In the above code, we created a tag asPerson
The node withname
andage
Attributes.()
Methods add this node to the graph database.
2. Create a node with relationship
# Create two nodesjohn = Node("Person", name="John", age=30) jane = Node("Person", name="Jane", age=28) # Create a relationship: John -> Jane, the relationship type is "FRIEND"john_knows_jane = john.create_relationship_to(jane, "FRIEND") # Save nodes and relationships(john) (jane) # View relationshipsprint(john_knows_jane)
In this example, we create two nodes, John and Jane, and create a FRIEND type relationship to connect them. Use the create_relationship_to method to create a relationship and save it to the database.
4. Query data
In Neo4j, we can use the Cypher query language to perform data queries. py2neo provides good support for Cypher queries, and these queries can be executed directly in Python.
1. Query node
# Use Cypher query to get all Person nodesquery = "MATCH (p:Person) RETURN , " result = (query) # Output query resultsfor record in result: print(record[""], record[""])
In this example, we useMATCH
Statement query all tags arePerson
node and return itname
andage
Attributes.()
The method will execute a Cypher query and return the result.
2. Query the nodes with relationships
# Query all John-related FRIEND relationshipsquery = "MATCH (p:Person)-[:FRIEND]->(f:Person) WHERE = 'John' RETURN " result = (query) # Output query resultsfor record in result: print(record[""])
This query statement passesMATCH
Find all withJohn
RelatedFRIEND
Relationship and return the name of the friend who has established the relationship with it.
3. Query nodes and relationships
# Query all nodes and their relationshipsquery = "MATCH (a)-[r]->(b) RETURN , type(r), " result = (query) # Output query resultsfor record in result: print(f"{record['']} is {record['type(r)']} {record['']}")
This code querys all nodes and their relationships, returning the name of the node and the type of the relationship.
5. Update and delete data
You can passpy2neo
Update the properties of a node or delete nodes and relationships.
1. Update the node's properties
# Find nodes and update their propertiesquery = "MATCH (p:Person {name: 'John'}) SET = 31" (query)
This code is found through Cypher query as the nameJohn
ofPerson
node and put itage
The attribute is updated to 31.
2. Delete nodes and relationships
# Delete a nodequery = "MATCH (p:Person {name: 'John'}) DELETE p" (query) # Delete the relationship between nodesquery = "MATCH (a)-[r:FRIEND]->(b) DELETE r" (query)
This code deletes the name asJohn
Nodes and allFRIEND
relation.
VI. Batch operation
If you need to batch insert nodes or relationships, you can use transactions to improve performance.
from py2neo import Transaction # Insert data in batches using transactionstx = () # Create multiple nodes and relationshipsfor i in range(1, 6): person = Node("Person", name=f"Person_{i}", age=20 + i) (person) if i > 1: prev_person = ("Person", name=f"Person_{i-1}").first() person.create_relationship_to(prev_person, "KNOWS") # Submit transaction()
In the above code, we insert multiple nodes at once through a transaction and create relationships between them. This method has higher performance than inserting nodes one by one.
7. Error handling and debugging
In usepy2neo
When, if an error occurs, it can be handled by catching the exception. Common errors include connection problems, Cypher query syntax errors, etc.
try: # Try to connect to the Neo4j database graph = Graph("bolt://localhost:7687", auth=("neo4j", "wrong_password")) # Execute query result = ("MATCH (p:Person) RETURN ") for record in result: print(record[""]) except Exception as e: print(f"An error occurred: {e}")
This method can help you catch possible errors and make appropriate handling.
8. Summary
With py2neo, you can easily connect and operate Neo4j databases in Python. We can use py2neo to create nodes, establish relationships, query data, update attributes, delete nodes, etc., and we can also batch process data through transactions. Whether it is simple database interaction or complex graph data analysis, py2neo can provide powerful support.
py2neo provides a very concise, Pythonic interface that allows you to easily implement graph database-related applications.
The above is the detailed content of the operation guide for Python connecting to Neo4j database. For more information about Python connecting to Neo4j, please follow my other related articles!