Neo4j的Java API操作
0. 写在前面
- Linux版本:Ubuntu Kylin 16.04
- Neo4j版本:Neo4j-3.2.7 Community
- Project Build Tool:Maven
1、前置芝士
Neo4j的核心概念
- Label:标签
- Node:节点,节点可以包含多个标签
- Relationship:节点与节点之间的关系。关系有始有终,有进有出,从from到to定义节点的关系
- Properties:属性。每个节点都拥有一个或多个属性
常见的增删改查操作
- 创建新节点
- 增加节点间的关系
- 修改指定属性的值
- 删除节点
- 删除节点间的指定关系
2. 准备工作
2.1 为项目引入Neo4j依赖
Maven:引入适合自己的artifactId版本。
<project>
...
<dependencies>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>3.2.7</version>
</dependency>
...
</dependencies>
...
</project>
Eclipse and Maven:
对于此种模式,建议安装m2e插件,让Maven来管理项目的构建classpath。这也为通过Maven的命令行
构建项目提供了可能,同时也为开发提供了一个有效的Eclipse setup 。
2.2 启动和停止
Start
为了启动嵌入式DBMS,需要实例化一个DatabaseManagementService
,并获得GraphDatabaseService
,如下所示:
managementService = new DatabaseManagementServiceBuilder(databaseDirectory).build();
graphDb = managementService.database(DEFAULT_DATABASE_NAME);
registerShutdownHook(managementService);
如果你打算操作嵌入式集群
,那么你应该使用com.neo4j.dbms.api.ClusterDatabaseManagementServiceBuilder
来进行适当的配置。出于可维护性的考虑,你可以在neo4j.conf
文件中定义你的嵌入式DBMS配置,如下所示。
dbms.mode=CORE
dbms.default_advertised_address=core01.example.com
dbms.default_listen_address=0.0.0.0
causal_clustering.discovery_type=LIST
causal_clustering.initial_discovery_members=core01.example.com,core02.example.com,core03.example.com
dbms.connector.bolt.enabled=true
dbms.connector.http.enabled=true
var managementService = new ClusterDatabaseManagementServiceBuilder( homeDirectory )
.loadPropertiesFromFile( "/path/to/neo4j.conf" )
.build();
Stop
为了确保Neo4j能够正常关闭Neo4j,需要申请一个hook,调用shutdown()方法。
public static void registerShutdownHook(final DatabaseManagementService managementService) {
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
managementService.shutdown();
}
});
}
3、Java操作Neo4j
代码
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class Demo {
public static void main( String[] args ) {
Driver driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "neo4j_123456" ) );
Session session = driver.session();
session.run( "CREATE (a:Person {name: {name}, title: {title}})",
parameters( "name", "Arthur001", "title", "King001" ) );
StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = {name} " +
"RETURN a.name AS name, a.title AS title",
parameters( "name", "Arthur001" ) );
while ( result.hasNext() )
{
Record record = result.next();
System.out.println( record.get( "title" ).asString() + " " + record.get( "name" ).asString() );
}
session.close();
driver.close();
}
}
4、参考资料
结束!
本文来自博客园,作者:{WHYBIGDATA},转载请注明原文链接:https://www.cnblogs.com/shadowlim/p/17051730.html