当Cypher查询为MATCH时,我无法解析neo4j-go-driver official 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类型的原因。
答案 0 :(得分:0)
在查询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
}
这可能是一种惯用方式访问节点上的属性值的基准-而不是尝试访问整个节点(驱动程序通过使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
})