为了账号安全,请及时绑定邮箱和手机立即绑定

如何在官方 neo4j go 驱动程序中解析结果?

如何在官方 neo4j go 驱动程序中解析结果?

Go
哔哔one 2023-05-15 14:41:45
当 Cypher 查询为 MATCH 时,我在解析neo4j-go-driver 官方驱动程序的结果时遇到问题。使用 README.md 示例中的 CREATE 查询可以正常工作,但使用 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 类型。
查看完整描述

1 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

您在查询中指定的值return是从左到右索引的 0。因此,在您的示例中,由于您仅从MATCH(在本例中定义为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]interface{}可用于将值作为参数传递给查询。


session.Run("match(n) where n.id = $id return n", 

    map[string]interface{}{

      "id": 1237892

    })


查看完整回答
反对 回复 2023-05-15
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信