使用Neo4j Java Driver操作Neo4j

时间:2022-09-03 18:00:10

本文是neo4j的官方文档https://neo4j.com/developer/java/#_the_example_project的翻译和整理。 
Neo4j Java driver是Neo4j官方支持的操作Neo4j数据库的driver,基于二进制协议(英文是binary protocol,但是并不太明白这个二进制协议是什么)。该driver方便简洁,还是挺好用的。 
要使用这个driver,首先需要在maven项目中的pom.xml中引入

    <dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.1.2</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

java代码则如下:

import org.neo4j.driver.v1.*;

import static org.neo4j.driver.v1.Values.parameters;

Driver driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "neo4j" ) );
Session session = driver.session();

session.run( "CREATE (a:Person {name: {name}, title: {title}})",
parameters( "name", "Arthur", "title", "King" ) );

StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = {name} " +
"RETURN a.name AS name, a.title AS title",
parameters( "name", "Arthur" ) );
while ( result.hasNext() )
{
Record record = result.next();
System.out.println( record.get( "title" ).asString() + " " + record.get( "name" ).asString() );
}

session.close();
driver.close();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

然后运行Neo4j,运行java程序。 
刚开始在配置GraphDatabase.driver的时候,把端口设置成了7474,出现错误:

Exception in thread "main" org.neo4j.driver.v1.exceptions.ClientException: Unable to process request: Unrecognized SSL message, plaintext connection?
  • 1

然后在http://*.com/questions/39722278/how-can-i-get-java-and-neo4j-to-work-in-eclipse上面找到解答,原来是7474是http端口,而bolt端口是8687。其实也不用像这篇回答说的修改conf文件,不过猜想也许修改conf文件是为了别的ip访问。直接运行程序发现出现错误,大概意思是说:“如果你是第一次运行Neo4j,请先初始化密码”等等,我才想起来第一次登陆的时候需要初始化,只需登陆localhost:7474然后初始化密码即可。最后,运行后的数据库多了一个节点: 
使用Neo4j Java Driver操作Neo4j