我试着按照文档进行操作,最后我得到了Neo4j 1.8的这段代码:
graphDB = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder( BASE_FOLDER + NEO4J_PATH )
.newGraphDatabase();
registerShutdownHook();
//Check if there are any indexes
System.out.println(Arrays.toString(graphDB.index().nodeIndexNames()));
Index<Node> testIndex = graphDB.index().forNodes("test");
Transaction tx = graphDB.beginTx();
try {
String nameKey = "name";
String nameValue = "Gevorg";
//The following 3 lines will be commented out
//when I run the program the second time
Node me = graphDB.createNode();
me.setProperty(nameKey, nameValue);
testIndex.add(me, nameKey, nameValue);
Node meAgain = testIndex.get(nameKey, nameValue).getSingle();
System.out.println(meAgain.getProperty(nameKey));
} finally {
tx.finish();
}
按预期打印以下内容:
[] //There is no index at the very beginning
Gevorg
程序终止后,我评论了节点/索引的创建,然后再次运行程序以达到NullPointerException(meAgain为null)。由于程序首先打印[test]
但是Node meAgain = testIndex.get(nameKey, nameValue).getSingle();
无法检索节点,因此正确检索索引。我在使用和不使用交易的情况下都尝试了。我做错了什么?
答案 0 :(得分:2)
在致电tx.finish
tx.success()
HTH
/彼得