我们可以将图形数据库 neo4j 与 react js 一起使用吗?如果不是这样,是否有任何替代选项可以在 React JS 中包含图形数据库?
很容易,您只需要neo4j-driver
:https : //www.npmjs.com/package/neo4j-driver
这是最简单的用法:
新4j.js
//import { v1 as neo4j } from 'neo4j-driver'
const neo4j = require('neo4j-driver').v1
const driver = neo4j.driver('bolt://localhost', neo4j.auth.basic('username', 'password'))
const session = driver.session()
session
.run(`
MATCH (n:Node)
RETURN n AS someName
`)
.then((results) => {
results.records.forEach((record) => console.log(record.get('someName')))
session.close()
driver.close()
})
Run Code Online (Sandbox Code Playgroud)
最佳做法是始终在获取数据后关闭会话。它价格便宜且重量轻。
最好的做法是在程序完成后才关闭驱动程序会话(如 Mongo DB)。如果您在错误的时间关闭驱动程序,您会看到极端错误,如果您是初学者,这一点非常重要。您将看到诸如“与服务器的连接已关闭”等错误。例如,在异步代码中,如果您在解析结果之前运行查询并关闭驱动程序,您将有一段糟糕的时光。
您可以在我的示例中看到我关闭驱动程序后,但只是为了说明正确的清理。如果在独立的 JS 文件中运行此代码进行测试,您将看到查询后 node.js 挂起,您需要按 CTRL + C 退出。添加driver.close()
修复了这个问题。通常,驱动程序在程序退出/崩溃之前不会关闭,这在后端 API 中永远不会,并且直到用户在前端注销时才会关闭。
现在知道了这一点,你就有了一个良好的开端。
请记住,session.close()
每次都立即,并小心使用driver.close()
.
您可以轻松地将此代码放入 React 组件或动作创建器中并呈现数据。
你会发现它与连接和使用 Axios 没有什么不同。
您也可以在事务中运行语句,这有利于写锁定受影响的节点。你应该先彻底研究一下,但交易流程是这样的:
const session = driver.session()
const tx = session.beginTransaction()
tx
.run(query)
.then(// same as normal)
.catch(// errors)
// the difference is you can chain multiple transactions:
const tx1 = await tx.run().then()
// use results
const tx2 = await tx.run().then()
// then, once you are ready to commit the changes:
if (results.good !== true) {
tx.rollback()
session.close()
throw error
}
await tx.commit()
session.close()
const finalResults = { tx1, tx2 }
return finalResults
// in my experience, you have to await tx.commit
// in async/await syntax conditions, otherwise it may not commit properly
// that operation is not instant
Run Code Online (Sandbox Code Playgroud)
太长;博士;
是的你可以!
您正在将两种不同的技术混合在一起。Neo4j 是图数据库,React.js 是前端框架。
您可以从 JavaScript 连接到 Neo4j - http://neo4j.com/developer/javascript/
归档时间: |
|
查看次数: |
4813 次 |
最近记录: |