-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathsession_pool_example.go
217 lines (195 loc) · 5.7 KB
/
session_pool_example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
*
* Copyright (c) 2022 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*
*/
package main
import (
"fmt"
"strings"
"sync"
"time"
nebula "github.com/vesoft-inc/nebula-go/v3"
)
const (
address = "127.0.0.1"
// The default port of NebulaGraph 2.x is 9669.
// 3699 is only for testing.
port = 3699
username = "root"
password = "nebula"
useHTTP2 = false
)
// Initialize logger
var log = nebula.DefaultLogger{}
type Person struct {
Name string `nebula:"name"`
Age int `nebula:"age"`
Likeness float64 `nebula:"likeness"`
}
func main() {
prepareSpace()
hostAddress := nebula.HostAddress{Host: address, Port: port}
// Create configs for session pool
config, err := nebula.NewSessionPoolConf(
"root",
"nebula",
[]nebula.HostAddress{hostAddress},
"example_space",
nebula.WithHTTP2(useHTTP2),
)
if err != nil {
log.Fatal(fmt.Sprintf("failed to create session pool config, %s", err.Error()))
}
// create session pool
sessionPool, err := nebula.NewSessionPool(*config, nebula.DefaultLogger{})
if err != nil {
log.Fatal(fmt.Sprintf("failed to initialize session pool, %s", err.Error()))
}
defer sessionPool.Close()
checkResultSet := func(prefix string, res *nebula.ResultSet) {
if !res.IsSucceed() {
log.Fatal(fmt.Sprintf("%s, ErrorCode: %v, ErrorMsg: %s", prefix, res.GetErrorCode(), res.GetErrorMsg()))
}
}
// execute query
{
insertVertexes := "INSERT VERTEX person(name, age) VALUES " +
"'Bob':('Bob', 10), " +
"'Lily':('Lily', 9), " +
"'Tom':('Tom', 10), " +
"'Jerry':('Jerry', 13), " +
"'John':('John', 11);"
// Insert multiple vertexes
resultSet, err := sessionPool.Execute(insertVertexes)
if err != nil {
fmt.Print(err.Error())
return
}
checkResultSet(insertVertexes, resultSet)
}
{
// Insert multiple edges
insertEdges := "INSERT EDGE like(likeness) VALUES " +
"'Bob'->'Lily':(80.0), " +
"'Bob'->'Tom':(70.0), " +
"'Lily'->'Jerry':(84.0), " +
"'Tom'->'Jerry':(68.3), " +
"'Bob'->'John':(97.2);"
resultSet, err := sessionPool.Execute(insertEdges)
if err != nil {
fmt.Print(err.Error())
return
}
checkResultSet(insertEdges, resultSet)
}
// Extract data from the resultSet
{
query := "GO FROM 'Bob' OVER like YIELD $^.person.name AS name, $^.person.age AS age, like.likeness AS likeness"
// Send query in goroutine
wg := sync.WaitGroup{}
wg.Add(1)
var resultSet *nebula.ResultSet
go func(wg *sync.WaitGroup) {
defer wg.Done()
resultSet, err = sessionPool.Execute(query)
if err != nil {
fmt.Print(err.Error())
return
}
checkResultSet(query, resultSet)
var personList []Person
resultSet.Scan(&personList)
fmt.Printf("personList: %v\n", personList)
// personList: [{Bob 10 97.2} {Bob 10 80} {Bob 10 70}]
}(&wg)
wg.Wait()
// Get all column names from the resultSet
colNames := resultSet.GetColNames()
fmt.Printf("column names: %s\n", strings.Join(colNames, ", "))
// Get a row from resultSet
record, err := resultSet.GetRowValuesByIndex(0)
if err != nil {
log.Error(err.Error())
}
// Print whole row
fmt.Printf("row elements: %s\n", record.String())
// Get a value in the row by column index
valueWrapper, err := record.GetValueByIndex(0)
if err != nil {
log.Error(err.Error())
}
// Get type of the value
fmt.Printf("valueWrapper type: %s \n", valueWrapper.GetType())
// Check if valueWrapper is a string type
if valueWrapper.IsString() {
// Convert valueWrapper to a string value
v1Str, err := valueWrapper.AsString()
if err != nil {
log.Error(err.Error())
}
fmt.Printf("Result of ValueWrapper.AsString(): %s\n", v1Str)
}
// Print ValueWrapper using String()
fmt.Printf("Print using ValueWrapper.String(): %s", valueWrapper.String())
}
// Drop space
{
query := "DROP SPACE IF EXISTS example_space"
// Send query
resultSet, err := sessionPool.Execute(query)
if err != nil {
fmt.Print(err.Error())
return
}
checkResultSet(query, resultSet)
}
fmt.Print("\n")
log.Info("Nebula Go Client Session Pool Example Finished")
}
// Just a helper function to create a space for this example to run.
func prepareSpace() {
hostAddress := nebula.HostAddress{Host: address, Port: port}
hostList := []nebula.HostAddress{hostAddress}
// Create configs for connection pool using default values
testPoolConfig := nebula.GetDefaultConf()
testPoolConfig.UseHTTP2 = useHTTP2
// Initialize connection pool
pool, err := nebula.NewConnectionPool(hostList, testPoolConfig, log)
if err != nil {
log.Fatal(fmt.Sprintf("Fail to initialize the connection pool, host: %s, port: %d, %s", address, port, err.Error()))
}
// Close all connections in the pool
defer pool.Close()
// Create session
session, err := pool.GetSession(username, password)
if err != nil {
log.Fatal(fmt.Sprintf("Fail to create a new session from connection pool, username: %s, password: %s, %s",
username, password, err.Error()))
}
// Release session and return connection back to connection pool
defer session.Release()
checkResultSet := func(prefix string, res *nebula.ResultSet) {
if !res.IsSucceed() {
log.Fatal(fmt.Sprintf("%s, ErrorCode: %v, ErrorMsg: %s", prefix, res.GetErrorCode(), res.GetErrorMsg()))
}
}
{
// Prepare the query
createSchema := "CREATE SPACE IF NOT EXISTS example_space(vid_type=FIXED_STRING(20)); " +
"USE example_space;" +
"CREATE TAG IF NOT EXISTS person(name string, age int);" +
"CREATE EDGE IF NOT EXISTS like(likeness double)"
// Execute a query
resultSet, err := session.Execute(createSchema)
if err != nil {
fmt.Print(err.Error())
return
}
checkResultSet(createSchema, resultSet)
}
time.Sleep(5 * time.Second)
log.Info("Space example_space was created")
}