登录
首页 >  Golang >  Go问答

解析 Neo4j 官方 Go 驱动程序返回的结果

来源:stackoverflow

时间:2024-02-29 08:15:30 326浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《解析 Neo4j 官方 Go 驱动程序返回的结果》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

当 cypher 查询为 match 时,我在解析 neo4j-go-driver 官方驱动程序的结果时遇到问题。使用 create 查询(如 readme.md 上的示例)可以正常工作,但使用 match 不会对结果 record().getbyindex(0) 进行索引

result, err = session.Run("match(n) where n.id = 1 return n", map[string]interface{}{})
if err != nil {
    panic(err)
}

for result.Next() {
    a := result.Record().GetByIndex(1)         //error: Index out or range
    b := result.Record().GetByIndex(0).(int64) //error: interface {} is *neo4j.nodeValue, not int64
    c := result.Record().GetByIndex(0) //prints corect result: &{14329224 [Item] map[id:1 name:Item 1]}
    fmt.Println(c)

}

由于nodevalue不是导出类型,我不知道断言属性或整个接口是否热到nodevalue类型。


解决方案


您在查询中的 return 之后指定的值是从左到右索引的 0。因此,在您的示例中,由于您仅从 matchqbendczqb 返回一个值(在本例中定义为 n),因此它将在索引 0 处可用。如错误消息所示,索引一超出范围。

//in the following example a node has an id of type int64, name of type string, and value of float32

result, _ := session.run(`
    match(n) where n.id = 1 return n.id, n.name, n.value`, nil)
                         // index 0 ^  idx 1^ . idx 2^

for result.next() {
   a, ok := result.record().getbyindex(0).(int64)  //n.id
   // ok == true
   b, ok := result.record().getbyindex(0).(string) //n.name
   // ok == true
   c, ok := result.record().getbyindex(0).(float64)//n.value
   // ok == true
}

这可能是访问节点上属性值的惯用方法的基线 - 而不是尝试访问整个节点(驱动程序通过将 nodevalue 保留为未导出的结构来隐式阻止)从节点返回单个属性,例如上面的例子。

与驱动程序合作时需要考虑的其他几点。 result 还公开了 get(key string) (interface{}, ok) 方法,用于通过返回值的名称访问结果。这样,如果您需要更改结果的顺序,您的值提取代码将不会因尝试访问错误的索引而中断。因此,对上面的内容进行一些修改:

result, _ := session.run(`
        match(n) where n.id = 1 return n.id as nodeid, n.name as username, n.value as power`, nil)

for result.next() {
    record := result.record()
    nodeid, ok := record.get("nodeid")
    // ok == true and nodeid is an interface that can be asserted to int
    username, ok := record.get("username")
    // ok == true and username is an interface that can be asserted to string

}

最后要指出的是 map[string] 接口{} 可用于将值作为参数传递给查询。

session.Run("match(n) where n.id = $id return n", 
    map[string]interface{}{
      "id": 1237892
    })

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>