python to neo4j
时间: 2023-08-23 11:15:50 浏览: 115
To interact with Neo4j graph database using Python, you can use the official driver provided by Neo4j called "neo4j" or popular libraries like "py2neo" or "neobolt". Here is a basic example using the "neo4j" driver:
First, you need to install the driver by running `pip install neo4j`.
Then, establish a connection to your Neo4j database with the following code:
```pythonfrom neo4j import GraphDatabase# Connect to the Neo4j databaseuri = "bolt://localhost:7687" # Update with your Neo4j server detailsusername = "your_username"
password = "your_password"
driver = GraphDatabase.driver(uri, auth=(username, password))
```
Once the connection is established, you can run queries and transactions on the database. Here's an example of creating a node and a relationship:
```python# Create a nodewith driver.session() as session:
session.run("CREATE (n:Person {name: 'John Doe'})")
# Create a relationshipwith driver.session() as session:
session.run("MATCH (a:Person {name: 'John Doe'}) "
"CREATE (a)-[:FRIEND]->(b:Person {name: 'Jane Smith'})")
```
You can also retrieve data from the database using Cypher queries:
```python# Retrieve all nodeswith driver.session() as session:
result = session.run("MATCH (n) RETURN n")
for record in result:
print(record["n"])
```
Remember to close the driver when you're done:
```pythondriver.close()
```
This is just a basic example to get you started. You can explore more advanced features like parameterized queries, handling transactions, and working with larger datasets in the Neo4j documentation.
阅读全文