我通过嵌入式Java API试验Neo4J。 我的构建路径似乎没问题(运行时没有异常)。 当我创建一些节点和关系时,我可以在它成功之后直接查询它。 但是在关闭并重新运行我的程序之后,我只获取了我在新运行时创建的数据,而不是之前的数据。 但是,如果我查看我的目录,我看到,每个运行时的大小都在增长,我执行数据创建。
这是我的代码:
public static void main(String[] args)
{
GraphDatabaseService gdb = new GraphDatabaseFactory().newEmbeddedDatabase( "/mytestdb/" );
create( gdb );
query( gdb );
gdb.shutdown();
}
private static void query( GraphDatabaseService gdb )
{
StringLogger sl = StringLogger.wrap( new Writer()
{
@Override
public void write( char[] arg0, int arg1, int arg2 ) throws IOException
{
for( int i=arg1; i<=arg2; i++ ) System.out.print( arg0[i] );
}
@Override
public void flush() throws IOException
{}
@Override
public void close() throws IOException
{}
} );
ExecutionEngine ee = new ExecutionEngine( gdb, sl );
ExecutionResult result = ee.execute( "MATCH (p:Privilleg) RETURN p" );
System.out.println( result.dumpToString() );
}
private static void create( GraphDatabaseService gdb )
{
Transaction tx = gdb.beginTx();
Node project = gdb.createNode( MyLabels.Project );
Node user = gdb.createNode( MyLabels.User );
Node priv1 = gdb.createNode( MyLabels.Privilleg );
Node priv2 = gdb.createNode( MyLabels.Privilleg );
user.setProperty( "name", "Heinz" );
user.setProperty( "email", "heinz@gmx.net" );
priv1.setProperty( "name", "Allowed to read all" );
priv1.setProperty( "targets", Short.MAX_VALUE );
priv1.setProperty( "read", true );
priv1.setProperty( "write", false );
priv2.setProperty( "name", "Allowed to write all" );
priv2.setProperty( "targets", Short.MAX_VALUE );
priv2.setProperty( "read", false );
priv2.setProperty( "write", true );
project.setProperty( "name", "My first project" );
project.setProperty( "sname", "STARTUP" );
user.createRelationshipTo( priv1, MyRelationships.UserPrivilleg );
user.createRelationshipTo( priv2, MyRelationships.UserPrivilleg );
priv1.createRelationshipTo( project, MyRelationships.ProjectPrivilleg );
priv2.createRelationshipTo( project, MyRelationships.ProjectPrivilleg );
tx.success();
}
答案 0 :(得分:1)
您的代码不会关闭交易。通常,您使用try-with-resources块:
try (Transaction tx=gdb.beginTx()) {
// do stuff in the graph
tx.success();
}
由于Transaction
为AutoClosable
,因此在离开代码块时将隐式调用其close()
方法。如果(出于任何原因)您决定不使用try-with-resources,请务必明确调用close()
。
另有说明:您的代码使用ExecutionEngine
。自Neo4j 2.2起,您可以直接拨打gdb.execute(myCypherString)
。
答案 1 :(得分:0)
谢谢!这有效。 此外,在我关闭事务之前,大约需要20秒才能将数据库缩小。现在这还不到一秒钟。