在分析了如何編譯啟動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圖資料庫的一些常見方法。