java 操作neo4j代码
时间: 2023-11-07 08:57:03 浏览: 96
以下是使用Java操作Neo4j数据库的示例代码:
1. 首先,需要引入Neo4j的Java驱动程序,例如:
```
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.7.5</version>
</dependency>
```
2. 然后,连接到Neo4j数据库:
```
import org.neo4j.driver.v1.*;
public class Neo4jExample {
public static void main(String[] args) {
// 连接到Neo4j数据库
Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "password"));
// 执行Cypher查询
try (Session session = driver.session()) {
String query = "MATCH (n) RETURN count(n) as count";
StatementResult result = session.run(query);
// 处理查询结果
while (result.hasNext()) {
Record record = result.next();
long count = record.get("count").asLong();
System.out.println("Node count: " + count);
}
}
// 关闭连接
driver.close();
}
}
```
3. 可以执行各种Cypher查询和更新操作,例如:
```
// 创建节点
String query = "CREATE (p:Person {name: 'Alice'}) RETURN p";
StatementResult result = session.run(query);
Record record = result.single();
Node node = record.get("p").asNode();
// 更新节点属性
String query = "MATCH (p:Person {name: 'Alice'}) SET p.age = 30";
session.run(query);
// 查询节点和关系
String query = "MATCH (p:Person)-[r:FRIEND]->(q:Person) WHERE p.name = 'Alice' RETURN r, q";
StatementResult result = session.run(query);
while (result.hasNext()) {
Record record = result.next();
Relationship relationship = record.get("r").asRelationship();
Node node = record.get("q").asNode();
// 处理查询结果
}
// 删除节点和关系
String query = "MATCH (p:Person)-[r:FRIEND]->() WHERE p.name = 'Alice' DELETE r, p";
session.run(query);
```
以上代码仅供参考,实际操作中需要根据具体需求进行修改和优化。
阅读全文