亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在官方 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 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號