demo.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. package elastic
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "time"
  8. "github.com/olivere/elastic"
  9. )
  10. const mapping = `
  11. {
  12. "settings":{
  13. "number_of_shards": 1,
  14. "number_of_replicas": 0
  15. },
  16. "mappings":{
  17. "tweet":{
  18. "properties":{
  19. "user":{
  20. "type":"keyword"
  21. },
  22. "message":{
  23. "type":"text",
  24. "store": true,
  25. "fielddata": true
  26. },
  27. "image":{
  28. "type":"keyword"
  29. },
  30. "created":{
  31. "type":"date"
  32. },
  33. "tags":{
  34. "type":"keyword"
  35. },
  36. "location":{
  37. "type":"geo_point"
  38. },
  39. "suggest_field":{
  40. "type":"completion"
  41. }
  42. }
  43. }
  44. }
  45. }`
  46. type Tweet struct {
  47. User string `json:"user"`
  48. Message string `json:"message"`
  49. Retweets int `json:"retweets"`
  50. Image string `json:"image,omitempty"`
  51. Created time.Time `json:"created,omitempty"`
  52. Tags []string `json:"tags,omitempty"`
  53. Location string `json:"location,omitempty"`
  54. Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
  55. }
  56. func Demo() {
  57. ctx := context.Background()
  58. client := getElasticClient()
  59. index := "twitter"
  60. indexType := "tweet"
  61. DeleteIndex(index)
  62. CreateIndex(index, mapping)
  63. // Index a tweet (using JSON serialization)
  64. tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
  65. PutBodyJson(index, indexType, "1", tweet1)
  66. // Index a second tweet (by string)
  67. tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}`
  68. PutBodyString(index, indexType, "2", tweet2)
  69. // Get tweet with specified ID
  70. get1, err := GetResult(index, indexType, "1")
  71. if err == nil {
  72. var tweetGet1 Tweet
  73. tweetGetByte1, _ := get1.Source.MarshalJSON()
  74. err := json.Unmarshal(tweetGetByte1, &tweetGet1)
  75. fmt.Printf("Got err %s, tweetGetByte1 %+v \n", err, tweetGet1)
  76. }
  77. // Flush to make sure the documents got written.
  78. //Flush(index)
  79. // Search with a term query
  80. termQuery := elastic.NewTermQuery("user", "olivere")
  81. searchResult, err := client.Search().
  82. Index(index). // search in index "twitter"
  83. Query(termQuery). // specify the query
  84. Sort("user", true). // sort by "user" field, ascending
  85. From(0).Size(10). // take documents 0-9
  86. Pretty(true). // pretty print request and response JSON
  87. Do(ctx) // execute
  88. if err != nil {
  89. panic(err)
  90. }
  91. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
  92. var ttyp Tweet
  93. for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
  94. if t, ok := item.(Tweet); ok {
  95. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  96. }
  97. }
  98. fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())
  99. if searchResult.Hits.TotalHits > 0 {
  100. fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
  101. for _, hit := range searchResult.Hits.Hits {
  102. var t Tweet
  103. err := json.Unmarshal(*hit.Source, &t)
  104. if err != nil {
  105. }
  106. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  107. }
  108. } else {
  109. fmt.Print("Found no tweets\n")
  110. }
  111. update, err := client.Update().Index("twitter").Type("tweet").Id("1").
  112. Script(elastic.NewScriptInline("ctx._source.retweets += params.num").Lang("painless").Param("num", 1)).
  113. Upsert(map[string]interface{}{"retweets": 0}).
  114. Do(ctx)
  115. if err != nil {
  116. panic(err)
  117. }
  118. fmt.Printf("New version of tweet %q is now %d\n", update.Id, update.Version)
  119. // Delete an index.
  120. //DeleteIndex(index)
  121. }