协调并行事务

在使用 Neo4j 集群时,因果一致性 (causal consistency) 在大多数情况下是默认强制执行的,这保证了查询能够读取到之前查询所做的更改。然而,对于并行运行的多个事务,默认情况下并不会自动实现这一点。在这种情况下,你可以使用书签 (bookmarks),让一个事务在运行自己的工作之前,等待另一个事务的结果在集群中传播完毕。这不是必需的,并且你仅应在需要跨不同事务实现因果一致性时才使用书签,因为等待书签可能会对性能产生负面影响。

使用 .executeQuery() 的书签

使用 .executeQuery() 对数据库进行查询 时,驱动会为您管理书签。在这种情况下,您可以保证后续查询能够读取之前的更改,而无需采取额外操作。

await driver.executeQuery('<QUERY 1>')

// subsequent executeQuery calls will be causally chained

await driver.executeQuery('<QUERY 2>') // can read result of <QUERY 1>
await driver.executeQuery('<QUERY 3>') // can read result of <QUERY 2>

若要禁用书签管理和因果一致性,请在 .executeQuery() 调用中将 bookmarkManager 选项设为 null

await driver.executeQuery(
    '<QUERY>',
    {},
    {
      bookmarkManager: null
    }
)

单个会话内的书签

书签管理对于在单个会话中运行的查询是自动进行的:同一会话内的查询在因果上是链接在一起的。

let session = driver.session({database: '<database-name>'})
try {
  await session.executeWrite(async tx => {
    await tx.run("<QUERY 1>")
  })
  await session.executeWrite(async tx => {
    await tx.run("<QUERY 2>")  // can read result of QUERY 1
  })
  await session.executeWrite(async tx => {
    await tx.run("<QUERY 3>")  // can read result of QUERY 1, 2
  })
} finally {
  await session.close()
}

跨多个会话的书签

如果你的应用程序使用多个会话,你可能需要确保一个会话在另一个会话运行其查询之前已完成其所有事务。

在下面的示例中,允许 sessionAsessionB 并发运行,而 sessionC 会等待直到它们的结果完成传播。这保证了 sessionC 想要操作的 Person 节点确实存在。

使用书签协调多个会话
const neo4j = require('neo4j-driver');

(async () => {
  const URI = '<URI to Neo4j database>'
  const USER = '<username>'
  const PASSWORD = '<password>'
  let driver
  try {
    driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD))
    await driver.verifyConnectivity()
  } catch(err) {
    console.log(`-- Connection error --\n${err}\n-- Cause --\n${err.cause}`)
    return
  }
  await createFriends(driver)
})()

async function createFriends(driver) {
  let savedBookmarks = []  // To collect the sessions' bookmarks

  // Create the first person and employment relationship.
  const sessionA = driver.session({database: '<database-name>'})
  try {
    await createPerson(sessionA, 'Alice')
    await employPerson(sessionA, 'Alice', 'Wayne Enterprises')
    savedBookmarks.concat(sessionA.lastBookmarks())  (1)
  } finally {
    sessionA.close()
  }

  // Create the second person and employment relationship.
  const sessionB = driver.session({database: '<database-name>'})
  try {
    await createPerson(sessionB, 'Bob')
    await employPerson(sessionB, 'Bob', 'LexCorp')
    savedBookmarks.concat(sessionB.lastBookmarks())  (1)
  } finally {
    sessionB.close()
  }

  // Create (and show) a friendship between the two people created above.
  const sessionC = driver.session({
    database: '<database-name>',
    bookmarks: savedBookmarks  (2)
  })
  try {
    await createFriendship(sessionC, 'Alice', 'Bob')
    await printFriendships(sessionC)
  } finally {
    sessionC.close()
  }
}

// Create a person node.
async function createPerson(session, name) {
  await session.executeWrite(async tx => {
    await tx.run('CREATE (:Person {name: $name})', { name: name })
  })
}

// Create an employment relationship to a pre-existing company node.
// This relies on the person first having been created.
async function employPerson(session, personName, companyName) {
  await session.executeWrite(async tx => {
    await tx.run(`
      MATCH (person:Person {name: $personName})
      MATCH (company:Company {name: $companyName})
      CREATE (person)-[:WORKS_FOR]->(company)`,
      { personName: personName, companyName: companyName }
    )
  })
}

// Create a friendship between two people.
async function createFriendship(session, nameA, nameB) {
  await session.executeWrite(async tx => {
    await tx.run(`
      MATCH (a:Person {name: $nameA})
      MATCH (b:Person {name: $nameB})
      MERGE (a)-[:KNOWS]->(b)
      `, { nameA: nameA, nameB: nameB }
    )
  })
}

// Retrieve and display all friendships.
async function printFriendships(session) {
  const result = await session.executeRead(async tx => {
    return await tx.run('MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name')
  })
  for(record of result.records) {
    console.log(`${record.get('a.name')} knows ${record.get('b.name')}`)
  }
}
1 使用 Session.lastBookmarks() 方法收集并合并来自不同会话的书签。
2 将它们作为 bookmarks 参数传入,以初始化另一个会话。

driver passing bookmarks

使用书签可能会对性能产生负面影响,因为所有查询都必须等待最新更改在集群中传播完成。若可能,请尝试将查询组合在同一事务或同一会话中。

混合使用 .executeQuery() 与会话

为确保部分使用 .executeQuery()、部分使用会话执行的事务之间的因果一致性,请在创建会话时使用 bookmarkManager 选项并将其设为 driver.executeQueryBookmarkManager。由于这正是 .executeQuery() 调用的默认书签管理器,这将确保所有工作在同一书签管理器下执行,从而保持因果一致性。

await driver.executeQuery('<QUERY 1>')

session = driver.session({
    bookmarkManager: driver.executeQueryBookmarkManager
})
try {
  // every query inside this session will be causally chained
  // (i.e., can read what was written by <QUERY 1>)
  await session.executeWrite(async tx => tx.run('<QUERY 2>'))
} finally {
  await session.close()
}

// subsequent executeQuery calls will be causally chained
// (i.e., can read what was written by <QUERY 2>)
await driver.executeQuery('<QUERY 3>')

术语表

LTS (长期支持版)

长期支持 (Long Term Support) 版本是保证在若干年内得到支持的版本。Neo4j 4.4 和 5.26 是 LTS 版本。

Aura

Aura 是 Neo4j 的全托管云服务。它提供免费和付费计划。

Cypher

Cypher 是 Neo4j 的图查询语言,允许您从数据库中检索数据。它就像 SQL,但专用于图数据库。

APOC

Awesome Procedures On Cypher (APOC) 是一个包含(许多)函数的库,这些函数在 Cypher 本身中难以轻松实现。

Bolt

Bolt 是用于 Neo4j 实例和驱动程序之间交互的协议。默认监听 7687 端口。

ACID

原子性 (Atomicity)、一致性 (Consistency)、隔离性 (Isolation)、持久性 (Durability) (ACID) 是保证数据库事务可靠处理的属性。符合 ACID 的 DBMS 确保即使发生故障,数据库中的数据也能保持准确和一致。

最终一致性

如果一个数据库能保证所有集群成员在某个时间点都存储了数据的最新版本,则该数据库具有最终一致性。

因果一致性

如果读写查询被集群中的每个成员以相同的顺序看到,则数据库具有因果一致性。这比最终一致性更强。

NULL

空标记不是一种类型,而是缺失值的占位符。更多信息,请参阅 Cypher → 使用 null

事务

事务是一个工作单元,要么被提交,要么在失败时被回滚。例如银行转账:它涉及多个步骤,但它们必须全部成功或全部撤销,以避免钱从一个账户扣除却未存入另一个账户的情况。

背压

背压是对数据流的抵抗力。它确保客户端不会被过快发送的数据压垮,从而超出其处理能力。

书签

书签是代表数据库某种状态的标记。通过将一个或多个书签与查询一起传递,服务器将确保在所表示的状态建立之前,该查询不会被执行。