暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

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图数据库的一些常见方法。

            文章转载自golang算法架构leetcode技术php,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

            评论