首页 > 解决方案 > 如何在官方 neo4j go 驱动程序中解析结果?

问题描述

当 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 类型的热度。

标签: goneo4j

解决方案


您在查询中指定的值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
    })

推荐阅读