Sunday, November 26, 2023

Connect and traverse On AWS Neptune using GoLang

 

This is an example for using the gremlingo library to connect to the AWS Neptune graph database.

The documentation for the library is very poor, so I though adding this example might be required.

Notice that to run it, you need to run the GO binary in the same VPC as the AWS Neptune.


In the example we connect to the database, add some nodes, and traverse the added nodes.


package main

import (
"fmt"
gremlingo "github.com/apache/tinkerpop/gremlin-go/v3/driver"
)

func main() {
// Creating the connection to the server.
connection, err := gremlingo.NewDriverRemoteConnection("wss://db-neptune-2.cluster-cby3ysf1nfyw.us-east-1.neptune.amazonaws.com:8182/gremlin",
func(settings *gremlingo.DriverRemoteConnectionSettings) {
settings.TraversalSource = "g"
})
if err != nil {
panic(err)
}
defer connection.Close()

useGraphDb(connection)
}

func useGraphDb(connection *gremlingo.DriverRemoteConnection) {
traversalSource := gremlingo.Traversal_().WithRemote(connection)

alice := addVertex(traversalSource, "buyer", "alice")
bob := addVertex(traversalSource, "buyer", "bob")
charlie := addVertex(traversalSource, "buyer", "charlie")
bread := addVertex(traversalSource, "product", "bread")
butter := addVertex(traversalSource, "product", "butter")

_, err := traversalSource.AddE("buy").From(alice).To(bread).Next()
if err != nil {
panic(err)
}
_, err = traversalSource.AddE("buy").From(bob).To(bread).Next()
if err != nil {
panic(err)
}
_, err = traversalSource.AddE("buy").From(charlie).To(butter).Next()
if err != nil {
panic(err)
}

printList(traversalSource.V())
printList(traversalSource.E())
printList(traversalSource.E().Property("type", "buy").V())
}

func printList(traversalSource *gremlingo.GraphTraversal) {
results, err := traversalSource.Limit(100).ToList()
if err != nil {
panic(err)
}
fmt.Printf("the list has %v items\n", len(results))

for _, r := range results {
fmt.Printf("%+v\n", r.String())
}
}

func addVertex(
traversalSource *gremlingo.GraphTraversalSource,
vertexType string,
vertexName string,
) *gremlingo.Vertex {
result, err := traversalSource.AddV(vertexType).Property("name", vertexName).Next()
if err != nil {
panic(err)
}
vertex, err := result.GetVertex()
if err != nil {
panic(err)
}
return vertex
}



No comments:

Post a Comment