简介
neography 是一个在 Node.js 中操作 Neo4j 数据库的轻量级驱动程序。它使得开发人员可以使用 JavaScript 轻松地连接,查询和修改 Neo4j 数据库。
本文将介绍如何使用 neography,从安装到基本操作和高级用法。
环境要求
- Node.js v14 或更高版本
- Neo4j 数据库 (v3.5+)
安装 neography
使用 npm 安装最新版本的 neography:
npm install neography
连接到 Neo4j 数据库
在使用 neography 之前,需要连接到 Neo4j 数据库。以下是连接到本地 Neo4j 实例的基本示例代码:
const Neography = require('neography'); const neo4j = new Neography('bolt://localhost:7687'); neo4j.authenticate('neo4j', 'password') .then(() => console.log('Connected to Neo4j!')) .catch(err => console.error(err));
基本操作
创建节点
以下是创建一个节点的示例代码:
neo4j.createNode({ name: 'Alice', age: 30, city: 'New York' }) .then(res => console.log(`Created node with id ${res._id}`)) .catch(err => console.error(err));
查询节点
以下是查询所有节点的示例代码:
neo4j.allNodes() .then(res => console.log(`Found ${res.length} nodes`)) .catch(err => console.error(err));
以下是查询特定节点的示例代码:
neo4j.findNode('Person', 'name', 'Alice') .then(res => console.log(`Found node with id ${res._id}`)) .catch(err => console.error(err));
创建关系
以下是创建一个关系的示例代码:
neo4j.createRelation('KNOWS', 'Person', 'name', 'Alice', 'Person', 'name', 'Bob', { since: 2020 }) .then(res => console.log(`Created relation with id ${res._id}`)) .catch(err => console.error(err));
查询关系
以下是查询所有关系的示例代码:
neo4j.allRelations() .then(res => console.log(`Found ${res.length} relations`)) .catch(err => console.error(err));
以下是查询特定关系的示例代码:
neo4j.getRelation('KNOWS', { since: 2020 }) .then(res => console.log(`Found relation with id ${res._id}`)) .catch(err => console.error(err));
高级用法
自定义 cypher 查询
以下是查询所有拥有至少一个朋友的人的示例代码:
neo4j.cypher(` MATCH (p:Person)-[:KNOWS]->() RETURN p `) .then(res => console.log(`Found ${res.length} people with friends`)) .catch(err => console.error(err));
自定义批量操作
以下是在一个事务中创建多个节点和关系的示例代码:
-- -------------------- ---- ------- ----- ---------- - -- ---------- ------- --------- - ----- -------- ---- --- ----- ---- ----- ---- -- - ---------- ------- --------- - ----- ------ ---- --- ----- ---- ---------- ---- -- - ---------- - ----- --------- - ----- ------- --- --------- - ----- ----- -- ------ ----------------- -- --- ----------------------- --------- -- ---------------- ---------- -------------- ---------- -- --------------------展开代码
总结
本文介绍了如何使用 neography 连接,查询和修改 Neo4j 数据库。在开始使用 neography 之前,必须确保已安装 Node.js 和 Neo4j 数据库。基本操作包括创建节点,查询节点,创建关系和查询关系。高级用法包括自定义 cypher 查询和批量操作。
希望这篇文章能让读者更深入地了解 neography,并在实际项目中得到应用。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60065f72238a385564ab682e