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 。
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();
}
});
}
代码
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();
}
}
neo4j
结束!