golang 源碼分析:cayley-2-
在分析瞭如何編譯啓動 cayley 圖數據庫,並使用它自帶的 Gizmo 工具來進行查詢後,我們來看看使用客戶端如何進行查詢。
首先使用官方的 github.com/cayleygraph/go-client,但是它聲明的 go.mod 文件有問題,修改調整後,使用如下:
package main
import (
"context"
"fmt"
//client "github.com/cayleygraph/go-client"
"learn/test/cayley/go-client/client"
)
func main() {
c := client.NewAPIClient(client.NewConfiguration())
result, _, _ := c.QueriesApi.Query(context.TODO(), "gizmo", "g.V().getLimit(10)")
fmt.Printf("%v", result.Result)
}
運行後,我們可以看到結果
% go run ./test/cayley/exp1/main.go
&[map[id:_:100000] map[id:</film/performance/actor>] map[id:</en/larry_fine_1902>] map[id:_:100001] map[id:</en/samuel_howard>] map[id:_:100002] map[id:</en/joe_palma>] map[id:_:100003] map[id:</en/symona_boniface>] map[id:_:100004]]
圖數據是由一條條四元組構成,其中第一個叫 subject(主語),第二個叫 predicate(謂語),第三個叫 object(賓語),第四個叫 Label(可選),以. 結尾。subject 和 object 會轉換成有向圖的頂點,predicate 就是邊。label 的用法是,你可以在一個數據庫裏,存多個圖,用 label 來區分不同的圖。我們可以使用四元祖操作數據庫
package main
import (
"fmt"
"log"
"github.com/cayleygraph/cayley"
"github.com/cayleygraph/quad"
)
func main() {
// Create a brand new graph
store, err := cayley.NewMemoryGraph()
if err != nil {
log.Fatalln(err)
}
store.AddQuad(quad.Make("phrase of the day", "is of course", "Hello World!", nil))
// Now we create the path, to get to our data
p := cayley.StartPath(store, quad.String("phrase of the day")).Out(quad.String("is of course"))
// Now we iterate over results. Arguments:
// 1. Optional context used for cancellation.
// 2. Flag to optimize query before execution.
// 3. Quad store, but we can omit it because we have already built path with it.
err = p.Iterate(nil).EachValue(nil, func(value quad.Value) {
nativeValue := quad.NativeOf(value) // this converts RDF values to normal Go types
fmt.Println(nativeValue)
})
if err != nil {
log.Fatalln(err)
}
}
運行結果如下
% go run ./test/cayley/exp2/main.go
Hello World!
當然,我們也可以把後端存儲轉換爲 boltdb
package main
import (
_ "github.com/cayleygraph/cayley/graph/kv/bolt"
"github.com/cayleygraph/cayley"
"github.com/cayleygraph/cayley/graph"
)
func open() {
path := "./"
// Initialize the database
graph.InitQuadStore("bolt", path, nil)
// Open and use the database
cayley.NewGraph("bolt", path, nil)
}
func main() {
open()
}
以上就是通過 golang 客戶端來操作 cayley 圖數據庫的一些常見方法。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/m25QZ5rxdUOyLPW4rsscBg