Advertisement
Guest User

Untitled

a guest
Jan 29th, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.63 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "flag"
  6. "fmt"
  7. . "github.com/aerospike/aerospike-client-go"
  8. "math/rand"
  9. "os"
  10. "strings"
  11. "time"
  12. )
  13.  
  14. const APP_VERSION = "1.0"
  15.  
  16. // The flag package provides a default help printer via -h switch
  17. var versionFlag *bool = flag.Bool("v", false, "Print the version number.")
  18.  
  19. func panicOnError(err error) {
  20. if err != nil {
  21. fmt.Printf("Aerospike error: %d", err)
  22. panic(err)
  23. }
  24. }
  25.  
  26. func main() {
  27. var c string
  28. flag.Parse() // Scan the arguments list
  29. client, err := NewClient("54.152.121.210", 3000)
  30.  
  31. defer client.Close()
  32.  
  33. if *versionFlag {
  34. fmt.Println("Version:", APP_VERSION)
  35. }
  36. fmt.Println("***** Welcome to Aerospike Developer Training *****\n")
  37. // try {
  38. fmt.Println("INFO: Connecting to Aerospike cluster...")
  39.  
  40. // Establish connection to Aerospike server
  41. // TODO: Establish a connection to Aerospike cluster
  42. // Exercise 1
  43.  
  44. // TODO: Close Aerospike cluster connection -- HINT: use defer
  45. // Exercise 1
  46.  
  47. // TODO: Check to see if the cluster connection succeeded
  48. // Exercise 1
  49.  
  50. fmt.Println("\nTODO: Check to see if the cluster connection succeeded")
  51.  
  52. if err != nil {
  53. fmt.Println("ERROR: Connection to Aerospike cluster failed! Please check the server settings and try again!")
  54. fmt.Scanf("%s", &c)
  55.  
  56. } else {
  57. fmt.Println("INFO: Connection to Aerospike cluster succeeded!")
  58.  
  59. var feature int
  60. // Present options
  61. fmt.Println("What would you like to do:")
  62. fmt.Println("1> Create A User And A Tweet")
  63. fmt.Println("2> Read A User Record")
  64. fmt.Println("3> Batch Read Tweets For A User")
  65. fmt.Println("4> Scan All Tweets For All Users")
  66. fmt.Println("5> Record UDF -- Update User Password")
  67. fmt.Println("6> Query Tweets By Username And Users By Tweet Count Range")
  68. fmt.Println("7> Stream UDF -- Aggregation Based on Tweet Count By Region")
  69. fmt.Println("0> Exit")
  70. fmt.Println("\nSelect 0-7 and hit enter:")
  71. fmt.Scanf("%d", &feature)
  72.  
  73. if feature != 0 {
  74. switch feature {
  75. case 1:
  76. fmt.Println("\n********** Your Selection: Create User And A Tweet **********\n")
  77. CreateUser(client)
  78. CreateTweet(client)
  79. case 2:
  80. fmt.Println("\n********** Your Selection: Read A User Record **********\n")
  81. GetUser(client)
  82. case 3:
  83. fmt.Println("\n********** Your Selection: Batch Read Tweets For A User **********\n")
  84. BatchGetUserTweets(client)
  85. case 4:
  86. fmt.Println("\n********** Your Selection: Scan All Tweets For All Users **********\n")
  87. ScanAllTweetsForAllUsers(client)
  88. case 5:
  89. fmt.Println("\n********** Your Selection: Record UDF -- Update User Password **********\n")
  90. UpdatePasswordUsingUDF(client)
  91. //UpdatePasswordUsingCAS(client);
  92. case 6:
  93. fmt.Println("\n********** Your Selection: Query Tweets By Username And Users By Tweet Count Range **********\n")
  94. QueryTweets(client)
  95. case 7:
  96. fmt.Println("\n********** Your Selection: Stream UDF -- Aggregation Based on Tweet Count By Region **********\n")
  97. AggregateUsersByTweetCountByRegion(client)
  98. case 12:
  99. fmt.Println("\n********** Create Users **********\n")
  100. CreateUsers(client)
  101. case 23:
  102. fmt.Println("\n********** Create Tweets **********\n")
  103. CreateTweets(client)
  104. default:
  105. }
  106. }
  107. }
  108.  
  109. fmt.Println("\n\nINFO: Press any key to exit...\n")
  110. fmt.Scanf("%s", &c)
  111. }
  112.  
  113. func CreateUsers(client *Client) {
  114. var c string
  115. genders := []string{"m", "f"}
  116. regions := []string{"n", "s", "e", "w"}
  117. randomInterests := []string{"Music", "Football", "Soccer", "Baseball", "Basketball", "Hockey", "Weekend Warrior", "Hiking", "Camping", "Travel", "Photography"}
  118. var userInterests []string
  119. totalInterests := 0
  120. start := 1
  121. end := 100000
  122. totalUsers := end - start
  123.  
  124. wPolicy := NewWritePolicy(0, 0) // generation = 0, expiration = 0
  125. wPolicy.RecordExistsAction = UPDATE
  126.  
  127. fmt.Printf("Create %d users. Press any key to continue...\n", totalUsers)
  128. fmt.Scanf("%s", &c)
  129.  
  130. for j := start; j <= end; j++ {
  131. userInterests = []string{}
  132. // Write user record
  133. username := fmt.Sprintf("user%d", j)
  134. key, _ := NewKey("test", "users", username)
  135. bin1 := NewBin("username", fmt.Sprintf("user%d", j))
  136. bin2 := NewBin("password", fmt.Sprintf("pwd%d", j))
  137. bin3 := NewBin("gender", genders[rand.Intn(2)])
  138. bin4 := NewBin("region", regions[rand.Intn(4)])
  139. bin5 := NewBin("lasttweeted", 0)
  140. bin6 := NewBin("tweetcount", 0)
  141.  
  142. totalInterests = rand.Intn(7)
  143. for i := 0; i < totalInterests; i++ {
  144. userInterests = append(userInterests, randomInterests[rand.Intn(len(randomInterests))])
  145. }
  146. bin7 := NewBin("interests", userInterests)
  147.  
  148. err := client.PutBins(wPolicy, key, bin1, bin2, bin3, bin4, bin5, bin6, bin7)
  149. panicOnError(err)
  150. fmt.Printf("Wrote user record for %s: %v\n", username, userInterests)
  151. }
  152. fmt.Printf("Done creating %d!\n", totalUsers)
  153.  
  154. }
  155.  
  156. func CreateUser(client *Client) {
  157. fmt.Printf("\n********** Create User **********\n")
  158.  
  159. ///*********************///
  160. ///*****Data Model*****///
  161. //Namespace: test
  162. //Set: users
  163. //Key: <username>
  164. //Bins:
  165. //username - String
  166. //password - String (For simplicity password is stored in plain-text)
  167. //gender - String (Valid values are 'm' or 'f')
  168. //region - String (Valid values are: 'n' (North), 's' (South), 'e' (East), 'w' (West) -- to keep data entry to minimal we just store the first letter)
  169. //lasttweeted - int (Stores epoch timestamp of the last/most recent tweet) -- Default to 0
  170. //tweetcount - int (Stores total number of tweets for the user) -- Default to 0
  171. //interests - Array of interests
  172.  
  173. //Sample Key: dash
  174. //Sample Record:
  175. //{ username: 'dash',
  176. // password: 'dash',
  177. // gender: 'm',
  178. // region: 'w',
  179. // lasttweeted: 1408574221,
  180. // tweetcount: 20,
  181. // interests: ['photography', 'technology', 'dancing', 'house music]
  182. //}
  183. ///*********************///
  184.  
  185. // Get username
  186. fmt.Print("Enter username: ")
  187. var username string
  188. fmt.Scanf("%s", &username)
  189.  
  190. if len(username) > 0 {
  191. // Get password
  192. fmt.Printf("Enter password for %s:", username)
  193. var password string
  194. fmt.Scanf("%s", &password)
  195.  
  196. // Get gender
  197. fmt.Printf("Select gender (f or m) for %s:", username)
  198. var gender string
  199. fmt.Scanf("%s", &gender)
  200.  
  201. // Get region
  202. fmt.Printf("Select region (north, south, east or west) for %s:", username)
  203. var region string
  204. fmt.Scanf("%s", &region)
  205.  
  206. // Get interests
  207. fmt.Printf("Enter comma-separated interests for %s:", username)
  208. var interests string
  209. fmt.Scanf("%s", &interests)
  210.  
  211. // TODO: Create WritePolicy instance
  212. // Exercise 2
  213. fmt.Printf("\nTODO: Create WritePolicy instance")
  214. wPolicy := NewWritePolicy(0, 0)
  215. wPolicy.RecordExistsAction = UPDATE
  216.  
  217. // TODO: Create Key and Bin instances for the user record. Remember to convert comma-separated interests into a list before storing it.
  218. // Exercise 2
  219. fmt.Printf("\nTODO: Create Key and Bin instances for the user record. Remember to convert comma-separated interests into a list before storing it.")
  220. key, _ := NewKey("test", "users", username)
  221.  
  222. bin1 := NewBin("username", username)
  223. bin2 := NewBin("password", password)
  224. bin3 := NewBin("gender", gender)
  225. bin4 := NewBin("region", region)
  226. bin5 := NewBin("lasttweeted", 0)
  227. bin6 := NewBin("tweetcount", 0)
  228.  
  229. arr := strings.Split(interests, ",")
  230. bin7 := NewBin("interests", arr)
  231.  
  232. // TODO: Write user record
  233. // Exercise 2
  234. fmt.Printf("\nTODO: Write user record")
  235.  
  236. err := client.PutBins(wPolicy, key, bin1, bin2, bin3, bin4, bin5, bin6, bin7)
  237. panicOnError(err)
  238. }
  239. }
  240.  
  241. func GetUser(client *Client) {
  242.  
  243. // Get username
  244. var username string
  245. fmt.Print("Enter username:")
  246. fmt.Scanf("%s", &username)
  247.  
  248. if len(username) > 0 {
  249. var userREcord Record
  250. // Check if username exists
  251.  
  252. userKey, _ := NewKey("test", "users", username)
  253. userRecord, err := client.Get(nil, userKey)
  254. panicOnError(err)
  255.  
  256. // TODO: Read user record
  257. // Exercise 2
  258. if userRecord != nil {
  259. // TODO: Output user record to the console. Remember to convert comma-separated interests into a list before outputting it.
  260. // Exercise 2
  261. //console.printf("\nTODO: Output user record to the console. Remember to convert comma-separated interests into a list before outputting it")
  262.  
  263. fmt.Printf("\nINFO: User recond read succesfully! Here are the details: \n")
  264. fmt.Printf("username: %s\n", userRecord.Bins["username"].(string))
  265. fmt.Printf("password: %s\n", userRecord.Bins["password"].(string))
  266. fmt.Printf("gender: %s\n", userRecord.Bins["gender"].(string))
  267. fmt.Printf("region: %s\n", userRecord.Bins["region"].(string))
  268. fmt.Printf("tweetcount: %d\n", userRecord.Bins["region"].(int))
  269. fmt.Printf("tweetcount: %v\n", userRecord.Bins["region"])
  270. } else {
  271. fmt.Printf("ERROR: User record not found!\n")
  272. }
  273. } else {
  274. fmt.Printf("ERROR: User record not found!\n")
  275. }
  276. }
  277.  
  278. func UpdatePasswordUsingUDF(client *Client) {
  279.  
  280. // Get username
  281. var username string
  282. fmt.Printf("\nEnter username:")
  283. fmt.Scanf("%s", &username)
  284.  
  285. if len(username) > 0 {
  286. // Check if username exists
  287. userKey, _ := NewKey("test", "users", username)
  288. userRecord, err := client.Get(nil, userKey)
  289. panicOnError(err)
  290. if userRecord != nil {
  291. // Get new password
  292. var password string
  293. fmt.Printf("Enter new password for %s:", username)
  294. fmt.Scanf("%s", &password)
  295.  
  296. // NOTE: UDF registration has been included here for convenience and to demonstrate the syntax. The recommended way of registering UDFs in production env is via AQL
  297.  
  298. regTask, err := client.RegisterUDFFromFile(nil, "udf/updateUserPwd.lua", "updateUserPwd.lua", LUA)
  299. panicOnError(err)
  300.  
  301. // wait until UDF is created
  302. for {
  303. if err := <-regTask.OnComplete(); err == nil {
  304. break
  305. }
  306. }
  307.  
  308. updatedPassword, err := client.Execute(nil, userKey, "updateUserPwd", "updatePassword", NewValue(password))
  309. panicOnError(err)
  310. fmt.Printf("\nINFO: The password has been set to: %s\n", updatedPassword)
  311. } else {
  312. fmt.Printf("ERROR: User record not found!\n")
  313. }
  314. } else {
  315. fmt.Printf("ERROR: User record not found!\n")
  316. }
  317. }
  318.  
  319. func UpdatePasswordUsingCAS(client *Client) {
  320.  
  321. // Get username
  322. var username string
  323. fmt.Print("Enter username:")
  324. fmt.Scanf("%s", &username)
  325.  
  326. if len(username) > 0 {
  327. // Check if username exists
  328. userKey, _ := NewKey("test", "users", username)
  329. userRecord, err := client.Get(nil, userKey)
  330. panicOnError(err)
  331. if err == nil {
  332. // Get new password
  333. var password string
  334. fmt.Print("Enter new password for %s:", username)
  335. fmt.Scanf("%s", &password)
  336.  
  337. // TODO: Update User record with new password only if generation is the same
  338. // Exercise 5
  339. fmt.Printf("\nINFO: The password has been set to: %s", password)
  340. } else {
  341. fmt.Printf("ERROR: User record not found!")
  342. }
  343. } else {
  344. fmt.Printf("ERROR: User record not found!")
  345. }
  346. }
  347.  
  348. func BatchGetUserTweets(client *Client) {
  349.  
  350. // Get username
  351. var username string
  352. fmt.Printf("\nEnter username:")
  353. fmt.Scanf("%s", &username)
  354.  
  355. if len(username) > 0 {
  356. //var userRecord Record
  357. // TODO: Read user record
  358. // Exercise 3
  359. fmt.Printf("\nTODO: Read user record")
  360.  
  361. userKey, _ := NewKey("test", "users", username)
  362. userRecord, err := client.Get(nil, userKey)
  363.  
  364. if userRecord != nil {
  365. // TODO: Get how many tweets the user has
  366. // Exercise 3
  367. //fmt.Println("\nTODO: Get how many tweets the user has")
  368. tweetCount := userRecord.Bins["tweetcount"].(int)
  369.  
  370. // TODO: Create an array of tweet keys -- keys[tweetCount]
  371. // Exercise 3
  372. //fmt.Println("\nTODO: Create an array of Key instances -- keys[tweetCount]")
  373. keys := make([]*Key, tweetCount)
  374.  
  375. for i := 0; i < len(keys); i++ {
  376. keyString, _ := fmt.Scanf("%s:%d", username, i+1)
  377. key, _ := NewKey("test", "tweets", keyString)
  378. keys[i] = key
  379. }
  380.  
  381. fmt.Printf("\nHere's %s tweets\n", username)
  382.  
  383. if len(keys) > 0 {
  384. records, err := client.BatchGet(NewPolicy(), keys)
  385. panicOnError(err)
  386.  
  387. for _, element := range records {
  388. fmt.Println(element.Bins["tweet"])
  389. }
  390. }
  391.  
  392. // TODO: Initiate batch read operation
  393. // Exercise 3
  394. fmt.Println("\nTODO: Initiate batch read operation")
  395.  
  396. // TODO: Output tweets to the console
  397. // Exercise 3
  398. fmt.Println("\nTODO: Output tweets to the console")
  399. }
  400. } else {
  401. fmt.Println("ERROR: User record not found!")
  402. }
  403. }
  404.  
  405. func AggregateUsersByTweetCountByRegion(client *Client) {
  406. var min int64
  407. var max int64
  408. fmt.Printf("\nEnter Min Tweet Count:")
  409. fmt.Scanf("%d", &min)
  410. fmt.Printf("Enter Max Tweet Count:")
  411. fmt.Scanf("%d", max)
  412.  
  413. fmt.Printf("\nAggregating users with %d - %d tweets by region. Hang on...\n", min, max)
  414.  
  415. // NOTE: UDF registration has been included here for convenience and to demonstrate the syntax. The recommended way of registering UDFs in production env is via AQL
  416. regTask, err := client.RegisterUDFFromFile(nil, "udf/aggregationByRegion.lua", "aggregationByRegion.lua", LUA)
  417. panicOnError(err)
  418.  
  419. // wait until UDF is created
  420. for {
  421. if err := <-regTask.OnComplete(); err == nil {
  422. break
  423. }
  424. }
  425.  
  426. stmt := NewStatement("test", "users", "tweetcount", "region")
  427. stmt.Addfilter(NewRangeFilter("tweetcount", min, max))
  428.  
  429. // rs, err := us.Client.Query(nil, stmt, "aggregationByRegion", "sum");
  430. // panicOnError(err)
  431. // L:
  432. // for {
  433. // select {
  434. // case rec, chanOpen := <-rs.Records:
  435. // if !chanOpen {
  436. // break L
  437. // }
  438. // fmt.Printf("\nTotal Users in North: %d\n", result["n"]);
  439. // fmt.Printf("Total Users in South: %d", result["s"]);
  440. // fmt.Printf("Total Users in East: %d", result["e"]);
  441. // fmt.Printf("Total Users in West: %d", result["w"]);
  442. // case err := <-recordset.Errors:
  443. // panicOnError(err)
  444. // }
  445. // }
  446. // rs.Close()
  447. //
  448.  
  449. }
  450.  
  451. //============================================================
  452. // Tweet
  453. //============================================================
  454. func CreateTweets(client *Client) {
  455. var c string
  456. randomTweets := []string{
  457. "For just $1 you get a half price download of half of the song and listen to it just once.",
  458. "People tell me my body looks like a melted candle",
  459. "Come on movie! Make it start!", "Byaaaayy",
  460. "Please, please, win! Meow, meow, meow!",
  461. "Put. A. Bird. On. It.",
  462. "A weekend wasted is a weekend well spent",
  463. "Would you like to super spike your meal?",
  464. "We have a mean no-no-bring-bag up here on aisle two.",
  465. "SEEK: See, Every, EVERY, Kind... of spot",
  466. "We can order that for you. It will take a year to get there.",
  467. "If you are pregnant, have a soda.",
  468. "Hear that snap? Hear that clap?",
  469. "Follow me and I may follow you",
  470. "Which is the best cafe in Portland? Discuss...",
  471. "Portland Coffee is for closers!",
  472. "Lets get this party started!",
  473. "How about them portland blazers!", "You got school'd, yo",
  474. "I love animals", "I love my dog", "What's up Portland",
  475. "Which is the best cafe in Portland? Discuss...",
  476. "I dont always tweet, but when I do it is on Tweetaspike"}
  477.  
  478. totalUsers := 10000
  479. maxTweets := 20
  480. timestamp := 0
  481.  
  482. wPolicy := NewWritePolicy(0, 0) // generation = 0, expiration = 0
  483. wPolicy.RecordExistsAction = UPDATE
  484.  
  485. fmt.Printf("Create up to %d tweets each for %d users. Press any key to continue...\n", maxTweets, totalUsers)
  486. fmt.Scanln("%s", &c)
  487.  
  488. for j := 0; j < totalUsers; j++ {
  489. // Check if user record exists
  490. username := fmt.Sprintf("user%d", rand.Intn(totalUsers))
  491. userKey, _ := NewKey("test", "users", username)
  492. userRecord, err := client.Get(nil, userKey)
  493.  
  494. panicOnError(err)
  495. if userRecord != nil {
  496. // create up to maxTweets random tweets for this user
  497. totalTweets := rand.Intn(maxTweets)
  498. for k := 1; k <= totalTweets; k++ {
  499. // Create timestamp to store along with the tweet so we can
  500. // query, index and report on it
  501. timestamp := getTimeStamp()
  502. tweetKeyString := fmt.Sprintf("%s:%d", username, k)
  503. //fmt.Printf("tweet key %s\n", tweetKeyString)
  504. tweetKey, _ := NewKey("test", "tweets", tweetKeyString)
  505. bin1 := NewBin("tweet", randomTweets[rand.Intn(len(randomTweets))])
  506. bin2 := NewBin("ts", timestamp)
  507. bin3 := NewBin("username", username)
  508.  
  509. err := client.PutBins(wPolicy, tweetKey, bin1, bin2, bin3)
  510. panicOnError(err)
  511. }
  512. fmt.Printf("Wrote %d tweets for %s!\n", totalTweets, username)
  513. if totalTweets > 0 {
  514. // Update tweet count and last tweet'd timestamp in the user
  515. // record
  516. err := client.PutBins(wPolicy, userKey, NewBin("tweetcount", totalTweets), NewBin("lasttweeted", timestamp))
  517. panicOnError(err)
  518. }
  519. }
  520. }
  521. fmt.Printf("\nDone creating up to %d tweets each for %d users!\n", maxTweets, totalUsers)
  522. }
  523.  
  524. func getTimeStamp() int64 {
  525. now := time.Now()
  526. return now.Unix()
  527. }
  528.  
  529. func CreateTweet(client *Client) {
  530. in := bufio.NewReader(os.Stdin)
  531. fmt.Println("\n********** Create Tweet **********")
  532.  
  533. ///*********************///
  534. ///*****Data Model*****///
  535. //Namespace: test
  536. //Set: tweets
  537. //Key: <username:<counter>>
  538. //Bins:
  539. //tweet - string
  540. //ts - int (Stores epoch timestamp of the tweet)
  541. //username - string
  542.  
  543. //Sample Key: dash:1
  544. //Sample Record:
  545. //{ tweet: 'Put. A. Bird. On. It.',
  546. // ts: 1408574221,
  547. // username: 'dash'
  548. //}
  549. ///*********************///
  550.  
  551. // Get username
  552. var username string
  553. fmt.Print("\nEnter username:")
  554. fmt.Scanf("%s", &username)
  555.  
  556. if len(username) > 0 {
  557. // Check if username exists
  558. userKey, _ := NewKey("test", "users", username)
  559. userRecord, err := client.Get(nil, userKey)
  560. panicOnError(err)
  561. if userRecord != nil {
  562. tweetCount := userRecord.Bins["tweetcount"].(int) + 1
  563.  
  564. // Get tweet
  565. fmt.Printf("Enter tweet for %s:", username)
  566. tweet, _ := in.ReadString('\n')
  567.  
  568. // Write record
  569. wPolicy := NewWritePolicy(0, 0) // generation = 0, expiration = 0
  570. wPolicy.RecordExistsAction = UPDATE
  571.  
  572. // Create timestamp to store along with the tweet so we can
  573. // query, index and report on it
  574. timestamp := getTimeStamp()
  575.  
  576. keyString := fmt.Sprintf("%s:%d", username, tweetCount)
  577. tweetKey, _ := NewKey("test", "tweets", keyString)
  578. bin1 := NewBin("tweet", tweet)
  579. bin2 := NewBin("ts", timestamp)
  580. bin3 := NewBin("username", username)
  581.  
  582. err := client.PutBins(wPolicy, tweetKey, bin1, bin2, bin3)
  583. panicOnError(err)
  584. fmt.Printf("\nINFO: Tweet record created! with key: %s, %v, %v, %v\n", keyString, bin1, bin2, bin3)
  585.  
  586. // Update tweet count and last tweet'd timestamp in the user
  587. // record
  588. updateUser(client, userKey, nil, timestamp, tweetCount)
  589. } else {
  590. fmt.Println("ERROR: User record not found!")
  591. }
  592. }
  593. }
  594.  
  595. func updateUser(client *Client, userKey *Key,
  596. policy *WritePolicy, timestamp int64, tweetCount int) {
  597. // TODO: Update tweet count and last tweeted timestamp in the user record
  598. // Exercise 2
  599. fmt.Printf("\nTODO: Update tweet count and last tweeted timestamp in the user record")
  600.  
  601. // TODO: Update tweet count and last tweeted timestamp in the user record using Operate
  602. // Exercise 6
  603. // updateUserUsingOperate(userKey, policy, ts);
  604. }
  605.  
  606. func updateUserUsingOperate(client *Client, userKey *Key,
  607. policy *WritePolicy, timestamp int64) {
  608.  
  609. // TODO: Initiate operate passing in policy, user record key, .add operation incrementing tweet count, .put operation updating timestamp and .get operation to read the user record
  610. // Exercise 6
  611. fmt.Println("\nTODO: Initiate operate passing in policy, user record key, .add operation incrementing tweet count, .put operation updating timestamp and .get operation to read the user record")
  612.  
  613. // TODO: Output most recent tweet count
  614. // Exercise 6
  615. fmt.Println("\nTODO: Output most recent tweet count")
  616.  
  617. }
  618.  
  619. func ScanAllTweetsForAllUsers(client *Client) {
  620. // TODO: Create ScanPolicy instance
  621. // Exercise 4
  622. fmt.Println("\nTODO: Create ScanPolicy instance")
  623. // TODO: Set policy parameters (optional)
  624. // Exercise 4
  625. fmt.Println("\nTODO: Set policy parameters (optional)")
  626. // TODO: Initiate scan operation that invokes callback for outputting tweets on the console
  627. // Exercise 4
  628. fmt.Println("\nTODO: Initiate scan operation that invokes callback for outputting tweets to the console")
  629. }
  630.  
  631. func QueryTweets(client *Client) {
  632. queryTweetsByUsername(client)
  633. queryUsersByTweetCount(client)
  634. }
  635.  
  636. func queryTweetsByUsername(client *Client) {
  637.  
  638. fmt.Printf("\n********** Query Tweets By Username **********\n")
  639.  
  640. // NOTE: Index creation has been included in here for convenience and to demonstrate the syntax.
  641. // NOTE: The recommended way of creating indexes in production env is via AQL.
  642. // IndexTask task = client.createIndex(null, "test", "tweets",
  643. // "username_index", "username", IndexType.STRING);
  644. // task.waitTillComplete(100);
  645.  
  646. // Get username
  647. var username string
  648. fmt.Printf("\nEnter username:")
  649. fmt.Scanln(&username)
  650.  
  651. if len(username) > 0 {
  652. stmt := NewStatement("test", "tweets", "tweet")
  653. stmt.Addfilter(NewEqualFilter("username", username))
  654.  
  655. fmt.Printf("\nHere's " + username + "'s tweet(s):\n")
  656.  
  657. recordset, err := client.Query(nil, stmt)
  658. panicOnError(err)
  659. L:
  660. for {
  661. select {
  662. case rec, chanOpen := <-recordset.Records:
  663. if !chanOpen {
  664. break L
  665. }
  666. fmt.Println(rec.Bins["tweet"])
  667. case err := <-recordset.Errors:
  668. panicOnError(err)
  669. }
  670. }
  671. recordset.Close()
  672.  
  673. } else {
  674. fmt.Printf("ERROR: User record not found!\n")
  675. }
  676. }
  677.  
  678. func queryUsersByTweetCount(client *Client) {
  679.  
  680. fmt.Printf("\n********** Query Users By Tweet Count Range **********\n")
  681.  
  682. // NOTE: Index creation has been included in here for convenience and to demonstrate the syntax.
  683. // NOTE: The recommended way of creating indexes in production env is via AQL.
  684. // IndexTask task = client.createIndex(null, "test", "users",
  685. // "tweetcount_index", "tweetcount", IndexType.NUMERIC);
  686. // task.waitTillComplete(100);
  687.  
  688. // Get min and max tweet counts
  689. var min int64
  690. var max int64
  691. fmt.Printf("\nEnter Min Tweet Count:")
  692. fmt.Scanf("%d", &min)
  693. fmt.Printf("Enter Max Tweet Count:")
  694. fmt.Scanf("%d", &max)
  695.  
  696. fmt.Printf("\nList of users with %d - %d tweets:\n", min, max)
  697.  
  698. stmt := NewStatement("test", "users", "username", "tweetcount", "gender")
  699. stmt.Addfilter(NewRangeFilter("tweetcount", min, max))
  700.  
  701. recordset, err := client.Query(nil, stmt)
  702. panicOnError(err)
  703. L:
  704. for {
  705. select {
  706. case rec, chanOpen := <-recordset.Records:
  707. if !chanOpen {
  708. break L
  709. }
  710. fmt.Printf("%s has %d tweets\n", rec.Bins["username"], rec.Bins["tweetcount"])
  711. case err := <-recordset.Errors:
  712. panicOnError(err)
  713. }
  714. }
  715. recordset.Close()
  716. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement