Neo4j中如何分配节点ID?

时间:2018-11-05 13:50:50

标签: neo4j

在为简单关系编写基本Neo4j测试用例时,我的一个测试用例在更改CREATE语句后失败了。结果的唯一区别是结束节点ID从1更改为20。

为了理解我为什么要问:

在Neo4j中如何分配节点ID?


我知道:(GitHub

 * A node's id is unique, but note the following: Neo4j reuses its internal ids
 * when nodes and relationships are deleted, which means it's bad practice to
 * refer to them this way. Instead, use application generated ids.

这些语句导致关系的结束节点ID为20

CREATE (n:Person { name:'John' }) RETURN COUNT(*)
CREATE (n:Person { name:'Mary' }) RETURN COUNT(*)
MATCH (a:Person),(b:Person) 
    WHERE a.name = 'John' 
    AND b.name = 'Mary' 
    CREATE (a)-[r:relationship_type]->(b) 
    RETURN COUNT(*)

此语句导致关系的结束节点ID为1

CREATE (a:Person { name:'John' })-[r:relationship_type]->(b:Person { name:'Mary' }) RETURN COUNT(*)

编辑

在此record_id_batch_size上搜索answer并搜索相关的test之后,我尝试了此测试,我认为将id增加2而不是1,因为存在三个不同的交易我希望每笔交易都可以基于record_id_batch_size开始一批新的ID。

@Test
public void idBatchSize02MultipleTransactions() throws Throwable {

    try (ServerControls server = TestServerBuilders.newInProcessBuilder()
            .withConfig(GraphDatabaseSettings.record_id_batch_size, "2")
            .newServer()) {

        GraphDatabaseService graph = server.graph();

        Node node_001;
        Node node_002;
        Node node_003;

        try (Transaction tx = graph.beginTx()) {
            node_001 = graph.createNode();
            tx.success();
        }

        try (Transaction tx = graph.beginTx()) {
            node_002 = graph.createNode();
            tx.success();
        }

        try (Transaction tx = graph.beginTx()) {
            node_003 = graph.createNode();
            tx.success();
        }

        assertEquals(0L,node_001.getId());
        assertEquals(2L,node_002.getId());
        assertEquals(4L,node_003.getId());
    }
}

但是测试失败,因为id确实是0L1L2L而不是0L2L4L。将需要做更多的阅读。

1 个答案:

答案 0 :(得分:2)

节点id取决于您先前在数据库中创建的内容。 除某些情况(例如:当我们重用id,cluster等时)外,主要是自动递增

那么您如何运行测试? 您是否有一套测试,并且在每次测试之间都启动了一个新的数据库实例,或者删除了该数据库?

此外,对于每笔交易,Neo4j都会保留一批免费的id: https://github.com/neo4j/neo4j/blob/da3a460a7e4481534a8e19b73b0c2c6ede973ae8/community/kernel/src/main/java/org/neo4j/graphdb/factory/GraphDatabaseSettings.java#L794-L803