golang Neo4j图数据库客户端插件库neoism的使用
golang Neo4j图数据库客户端插件库neoism的使用
neoism
是一个Go语言的客户端库,提供通过REST API访问Neo4j图数据库的功能。
状态
这个驱动已经相当完整,可能适合一般使用。代码有大量的集成测试,但缺乏实际生产环境测试。在生产环境中使用需自行承担风险。
要求
需要Go 1.1或更高版本。
已在Neo4j 2.2.4和Go 1.4.1上测试通过。
安装
开发版本
go get -v github.com/jmcvetta/neoism
稳定版本
当前稳定版本是v1
:
go get gopkg.in/jmcvetta/neoism.v1
使用示例
连接到Neo4j数据库
db, err := neoism.Connect("http://localhost:7474/db/data")
if err != nil {
// 处理错误
}
创建节点
n, err := db.CreateNode(neoism.Props{"name": "Captain Kirk"})
if err != nil {
// 处理错误
}
执行Cypher查询
// res将填充查询结果,必须是一个结构体切片
res := []struct {
// `json:`标签匹配查询中的列名
A string `json:"a.name"`
Rel string `json:"type(r)"`
B string `json:"b.name"`
}{}
// cq包含Cypher查询本身(必需),可能有参数(可选),以及指向结果对象的指针(可选)
cq := neoism.CypherQuery{
// 对于长语句使用反引号 - Cypher对空格不敏感
Statement: `
MATCH (a:Person)-[r]->(b)
WHERE a.name = {name}
RETURN a.name, type(r), b.name
`,
Parameters: neoism.Props{"name": "Dr McCoy"},
Result: &res,
}
// 执行查询
err := db.Cypher(&cq)
if err != nil {
// 处理错误
}
// 获取第一个结果
r := res[0]
使用事务执行Cypher查询
tx, err := db.Begin(qs)
if err != nil {
// 处理错误
}
cq0 := neoism.CypherQuery{
Statement: `MATCH (a:Account) WHERE a.uuid = {account_id} SET balance = balance + {amount}`,
Parameters: neoism.Props{"uuid": "abc123", amount: 20},
}
err = db.Cypher(&cq0)
if err != nil {
// 处理错误
}
cq1 := neoism.CypherQuery{
Statement: `MATCH (a:Account) WHERE a.uuid = {account_id} SET balance = balance + {amount}`,
Parameters: neoism.Props{"uuid": "def456", amount: -20},
}
err = db.Cypher(&cq1)
if err != nil {
// 处理错误
}
err := tx.Commit()
if err != nil {
// 处理错误
}
测试
Neoism的测试套件尊重但不要求NEO4J_URL
环境变量。默认假设Neo4j运行在localhost:7474
,用户名为neo4j
,密码为foobar
。
export NEO4J_URL=http://your_user:your_password@neo4j.yourdomain.com/db/data/
go test -v .
如果使用全新的Neo4j实例,可以使用包含的set_neo4j_password.sh
脚本将密码设置为Neoism测试期望的值:
sh set_neo4j_password.sh
许可证
这是自由软件,根据GPL v3条款发布。
更多关于golang Neo4j图数据库客户端插件库neoism的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang Neo4j图数据库客户端插件库neoism的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Neoism - Golang Neo4j客户端库使用指南
neoism是一个用于Go语言的Neo4j图数据库客户端库,它提供了简单易用的API来与Neo4j数据库交互。下面我将详细介绍如何使用neoism库。
安装
首先安装neoism库:
go get github.com/jmcvetta/neoism
基本使用
1. 连接数据库
package main
import (
"fmt"
"github.com/jmcvetta/neoism"
)
func main() {
// 连接到Neo4j数据库
db, err := neoism.Connect("http://localhost:7474/db/data")
if err != nil {
panic(err)
}
defer db.Session.Close()
fmt.Println("Connected to Neo4j!")
}
2. 创建节点
// 创建单个节点
func createNode(db *neoism.Database) {
node, err := db.CreateNode(neoism.Props{
"name": "Alice",
"age": 30,
})
if err != nil {
panic(err)
}
// 添加标签
node.AddLabel("Person")
fmt.Printf("Created node with ID: %d\n", node.Id())
}
3. 创建关系
// 创建两个节点并建立关系
func createRelationship(db *neoism.Database) {
// 创建两个节点
alice, _ := db.CreateNode(neoism.Props{"name": "Alice"})
bob, _ := db.CreateNode(neoism.Props{"name": "Bob"})
// 添加标签
alice.AddLabel("Person")
bob.AddLabel("Person")
// 创建关系
rel, err := db.Relate(alice.Id(), bob.Id(), "KNOWS", neoism.Props{
"since": "2020-01-01",
})
if err != nil {
panic(err)
}
fmt.Printf("Created relationship with ID: %d\n", rel.Id)
}
4. 执行Cypher查询
// 执行Cypher查询
func cypherQuery(db *neoism.Database) {
// 定义查询结构
query := neoism.CypherQuery{
Statement: `
MATCH (p:Person)
WHERE p.name = {name}
RETURN p.name AS name, p.age AS age
`,
Parameters: neoism.Props{"name": "Alice"},
Result: &[]struct {
Name string `json:"name"`
Age int `json:"age"`
}{},
}
// 执行查询
err := db.Cypher(&query)
if err != nil {
panic(err)
}
// 处理结果
for _, person := range *query.Result.(*[]struct {
Name string `json:"name"`
Age int `json:"age"`
}) {
fmt.Printf("%s is %d years old\n", person.Name, person.Age)
}
}
5. 批量操作
// 批量创建节点
func batchCreateNodes(db *neoism.Database) {
// 准备批量操作
ops := []neoism.BatchOperation{
{
Method: "POST",
To: "/node",
Body: neoism.Props{"name": "Charlie", "age": 25},
},
{
Method: "POST",
To: "/node",
Body: neoism.Props{"name": "David", "age": 35},
},
}
// 执行批量操作
results, err := db.Batch(ops)
if err != nil {
panic(err)
}
// 获取创建的节点ID
for _, res := range results {
fmt.Printf("Created node at: %s\n", res.Location)
}
}
高级功能
1. 事务处理
// 使用事务
func transactionExample(db *neoism.Database) {
// 开始事务
tx, err := db.Begin()
if err != nil {
panic(err)
}
// 在事务中执行操作
node, err := tx.CreateNode(neoism.Props{"name": "Eve"})
if err != nil {
tx.Rollback()
panic(err)
}
err = node.AddLabel("Person")
if err != nil {
tx.Rollback()
panic(err)
}
// 提交事务
err = tx.Commit()
if err != nil {
panic(err)
}
fmt.Printf("Created node in transaction with ID: %d\n", node.Id())
}
2. 索引管理
// 创建索引
func createIndex(db *neoism.Database) {
// 在Person标签的name属性上创建索引
index := neoism.IndexConfig{
Type: "node",
Label: "Person",
Property: "name",
}
err := db.CreateIndex(index)
if err != nil {
panic(err)
}
fmt.Println("Created index on Person(name)")
}
注意事项
- neoism目前不再积极维护,对于新项目建议考虑官方Neo4j Go驱动或其他活跃维护的库
- 确保Neo4j服务器已启动并运行在指定端口
- 对于生产环境,考虑添加连接池和错误重试机制
- 大型查询可能需要分批次处理
替代方案
如果neoism不能满足需求,可以考虑以下替代方案:
- 官方Neo4j Go驱动: https://github.com/neo4j/neo4j-go-driver
- gobolt: https://github.com/mindstand/go-bolt
- gocypher: https://github.com/cleversoap/gocypher
希望这个指南能帮助你开始使用neoism与Neo4j交互!