当 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)
}
Run Code Online (Sandbox Code Playgroud)
由于 nodeValue 不是导出类型,我不知道对断言属性或整个接口返回 nodeValue 类型的热度。
您return在查询中指定的值从左到右索引为 0。因此,在您的示例中,由于您仅从MATCH( 在本例中定义为n)返回一个值,它将在索引 0 处可用。如错误消息所示,索引 1 超出范围。
//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
}
Run Code Online (Sandbox Code Playgroud)
这可能是访问节点上的属性值的惯用方式的基线 - 而不是尝试访问整个节点(驱动程序通过将 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
}
Run Code Online (Sandbox Code Playgroud)
最后要指出的是map[string]interface{}可用于将值作为参数传递给查询。
session.Run("match(n) where n.id = $id return n",
map[string]interface{}{
"id": 1237892
})
Run Code Online (Sandbox Code Playgroud)