gopkg.in/rethinkdb/rethinkdb-go.v6@v6.2.2/internal/integration/tests/example_query_aggregation_test.go (about) 1 package tests 2 3 import ( 4 "fmt" 5 r "gopkg.in/rethinkdb/rethinkdb-go.v6" 6 ) 7 8 // Group games by player. 9 func ExampleTerm_Group() { 10 cur, err := r.DB("examples").Table("games").Group("player").Run(session) 11 if err != nil { 12 fmt.Print(err) 13 return 14 } 15 16 var res []interface{} 17 err = cur.All(&res) 18 if err != nil { 19 fmt.Print(err) 20 return 21 } 22 23 fmt.Print(res) 24 } 25 26 // Group games by the index type. 27 func ExampleTerm_GroupByIndex() { 28 cur, err := r.DB("examples").Table("games").GroupByIndex("type").Run(session) 29 if err != nil { 30 fmt.Print(err) 31 return 32 } 33 34 var res []interface{} 35 err = cur.All(&res) 36 if err != nil { 37 fmt.Print(err) 38 return 39 } 40 41 fmt.Print(res) 42 } 43 44 // Suppose that the table games2 has the following data: 45 // 46 // [ 47 // { id: 1, matches: {'a': [1, 2, 3], 'b': [4, 5, 6]} }, 48 // { id: 2, matches: {'b': [100], 'c': [7, 8, 9]} }, 49 // { id: 3, matches: {'a': [10, 20], 'c': [70, 80]} } 50 // ] 51 // Using MultiGroup we can group data by match A, B or C. 52 func ExampleTerm_MultiGroup() { 53 cur, err := r.DB("examples").Table("games2").MultiGroup(r.Row.Field("matches").Keys()).Run(session) 54 if err != nil { 55 fmt.Print(err) 56 return 57 } 58 59 var res []interface{} 60 err = cur.All(&res) 61 if err != nil { 62 fmt.Print(err) 63 return 64 } 65 66 fmt.Print(res) 67 } 68 69 // Ungrouping grouped data. 70 func ExampleTerm_Ungroup() { 71 cur, err := r.DB("examples").Table("games"). 72 Group("player"). 73 Max("points").Field("points"). 74 Ungroup(). 75 Run(session) 76 if err != nil { 77 fmt.Print(err) 78 return 79 } 80 81 var res []interface{} 82 err = cur.All(&res) 83 if err != nil { 84 fmt.Print(err) 85 return 86 } 87 88 fmt.Print(res) 89 } 90 91 // Return the number of documents in the table posts. 92 func ExampleTerm_Reduce() { 93 cur, err := r.DB("examples").Table("posts"). 94 Map(func(doc r.Term) interface{} { 95 return 1 96 }). 97 Reduce(func(left, right r.Term) interface{} { 98 return left.Add(right) 99 }). 100 Run(session) 101 if err != nil { 102 fmt.Print(err) 103 return 104 } 105 106 var res int 107 err = cur.One(&res) 108 if err != nil { 109 fmt.Print(err) 110 return 111 } 112 113 fmt.Print(res) 114 } 115 116 // Concatenate words from a list. 117 func ExampleTerm_Fold() { 118 cur, err := r.Expr([]string{"a", "b", "c"}).Fold("", func(acc, word r.Term) r.Term { 119 return acc.Add(r.Branch(acc.Eq(""), "", ", ")).Add(word) 120 }).Run(session) 121 if err != nil { 122 fmt.Print(err) 123 return 124 } 125 126 var res string 127 err = cur.One(&res) 128 if err != nil { 129 fmt.Print(err) 130 return 131 } 132 133 fmt.Print(res) 134 // Output: 135 // a, b, c 136 }