example_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2012-2015 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic_test
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "log"
  9. "os"
  10. "reflect"
  11. "time"
  12. "github.com/olivere/elastic"
  13. )
  14. type Tweet struct {
  15. User string `json:"user"`
  16. Message string `json:"message"`
  17. Retweets int `json:"retweets"`
  18. Image string `json:"image,omitempty"`
  19. Created time.Time `json:"created,omitempty"`
  20. Tags []string `json:"tags,omitempty"`
  21. Location string `json:"location,omitempty"`
  22. Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
  23. }
  24. func Example() {
  25. errorlog := log.New(os.Stdout, "APP ", log.LstdFlags)
  26. // Obtain a client. You can provide your own HTTP client here.
  27. client, err := elastic.NewClient(elastic.SetErrorLog(errorlog))
  28. if err != nil {
  29. // Handle error
  30. panic(err)
  31. }
  32. // Trace request and response details like this
  33. //client.SetTracer(log.New(os.Stdout, "", 0))
  34. // Ping the Elasticsearch server to get e.g. the version number
  35. info, code, err := client.Ping().Do()
  36. if err != nil {
  37. // Handle error
  38. panic(err)
  39. }
  40. fmt.Printf("Elasticsearch returned with code %d and version %s", code, info.Version.Number)
  41. // Getting the ES version number is quite common, so there's a shortcut
  42. esversion, err := client.ElasticsearchVersion("http://127.0.0.1:9200")
  43. if err != nil {
  44. // Handle error
  45. panic(err)
  46. }
  47. fmt.Printf("Elasticsearch version %s", esversion)
  48. // Use the IndexExists service to check if a specified index exists.
  49. exists, err := client.IndexExists("twitter").Do()
  50. if err != nil {
  51. // Handle error
  52. panic(err)
  53. }
  54. if !exists {
  55. // Create a new index.
  56. createIndex, err := client.CreateIndex("twitter").Do()
  57. if err != nil {
  58. // Handle error
  59. panic(err)
  60. }
  61. if !createIndex.Acknowledged {
  62. // Not acknowledged
  63. }
  64. }
  65. // Index a tweet (using JSON serialization)
  66. tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
  67. put1, err := client.Index().
  68. Index("twitter").
  69. Type("tweet").
  70. Id("1").
  71. BodyJson(tweet1).
  72. Do()
  73. if err != nil {
  74. // Handle error
  75. panic(err)
  76. }
  77. fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
  78. // Index a second tweet (by string)
  79. tweet2 := `{"user" : "olivere", "message" : "It's a Raggy Waltz"}`
  80. put2, err := client.Index().
  81. Index("twitter").
  82. Type("tweet").
  83. Id("2").
  84. BodyString(tweet2).
  85. Do()
  86. if err != nil {
  87. // Handle error
  88. panic(err)
  89. }
  90. fmt.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type)
  91. // Get tweet with specified ID
  92. get1, err := client.Get().
  93. Index("twitter").
  94. Type("tweet").
  95. Id("1").
  96. Do()
  97. if err != nil {
  98. // Handle error
  99. panic(err)
  100. }
  101. if get1.Found {
  102. fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type)
  103. }
  104. // Flush to make sure the documents got written.
  105. _, err = client.Flush().Index("twitter").Do()
  106. if err != nil {
  107. panic(err)
  108. }
  109. // Search with a term query
  110. termQuery := elastic.NewTermQuery("user", "olivere")
  111. searchResult, err := client.Search().
  112. Index("twitter"). // search in index "twitter"
  113. Query(&termQuery). // specify the query
  114. Sort("user", true). // sort by "user" field, ascending
  115. From(0).Size(10). // take documents 0-9
  116. Pretty(true). // pretty print request and response JSON
  117. Do() // execute
  118. if err != nil {
  119. // Handle error
  120. panic(err)
  121. }
  122. // searchResult is of type SearchResult and returns hits, suggestions,
  123. // and all kinds of other information from Elasticsearch.
  124. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
  125. // Each is a convenience function that iterates over hits in a search result.
  126. // It makes sure you don't need to check for nil values in the response.
  127. // However, it ignores errors in serialization. If you want full control
  128. // over iterating the hits, see below.
  129. var ttyp Tweet
  130. for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
  131. t := item.(Tweet)
  132. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  133. }
  134. // TotalHits is another convenience function that works even when something goes wrong.
  135. fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())
  136. // Here's how you iterate through results with full control over each step.
  137. if searchResult.Hits != nil {
  138. fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
  139. // Iterate through results
  140. for _, hit := range searchResult.Hits.Hits {
  141. // hit.Index contains the name of the index
  142. // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
  143. var t Tweet
  144. err := json.Unmarshal(*hit.Source, &t)
  145. if err != nil {
  146. // Deserialization failed
  147. }
  148. // Work with tweet
  149. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  150. }
  151. } else {
  152. // No hits
  153. fmt.Print("Found no tweets\n")
  154. }
  155. // Update a tweet by the update API of Elasticsearch.
  156. // We just increment the number of retweets.
  157. update, err := client.Update().Index("twitter").Type("tweet").Id("1").
  158. Script("ctx._source.retweets += num").
  159. ScriptParams(map[string]interface{}{"num": 1}).
  160. Upsert(map[string]interface{}{"retweets": 0}).
  161. Do()
  162. if err != nil {
  163. // Handle error
  164. panic(err)
  165. }
  166. fmt.Printf("New version of tweet %q is now %d", update.Id, update.Version)
  167. // ...
  168. // Delete an index.
  169. deleteIndex, err := client.DeleteIndex("twitter").Do()
  170. if err != nil {
  171. // Handle error
  172. panic(err)
  173. }
  174. if !deleteIndex.Acknowledged {
  175. // Not acknowledged
  176. }
  177. }
  178. func ExampleClient_NewClient_default() {
  179. // Obtain a client to the Elasticsearch instance on http://localhost:9200.
  180. client, err := elastic.NewClient()
  181. if err != nil {
  182. // Handle error
  183. fmt.Printf("connection failed: %v\n", err)
  184. } else {
  185. fmt.Println("connected")
  186. }
  187. _ = client
  188. // Output:
  189. // connected
  190. }
  191. func ExampleClient_NewClient_cluster() {
  192. // Obtain a client for an Elasticsearch cluster of two nodes,
  193. // running on 10.0.1.1 and 10.0.1.2.
  194. client, err := elastic.NewClient(elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200"))
  195. if err != nil {
  196. // Handle error
  197. panic(err)
  198. }
  199. _ = client
  200. }
  201. func ExampleClient_NewClient_manyOptions() {
  202. // Obtain a client for an Elasticsearch cluster of two nodes,
  203. // running on 10.0.1.1 and 10.0.1.2. Do not run the sniffer.
  204. // Set the healthcheck interval to 10s. When requests fail,
  205. // retry 5 times. Print error messages to os.Stderr and informational
  206. // messages to os.Stdout.
  207. client, err := elastic.NewClient(
  208. elastic.SetURL("http://10.0.1.1:9200", "http://10.0.1.2:9200"),
  209. elastic.SetSniff(false),
  210. elastic.SetHealthcheckInterval(10*time.Second),
  211. elastic.SetMaxRetries(5),
  212. elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
  213. elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)))
  214. if err != nil {
  215. // Handle error
  216. panic(err)
  217. }
  218. _ = client
  219. }
  220. func ExampleIndexExistsService() {
  221. // Get a client to the local Elasticsearch instance.
  222. client, err := elastic.NewClient()
  223. if err != nil {
  224. // Handle error
  225. panic(err)
  226. }
  227. // Use the IndexExists service to check if the index "twitter" exists.
  228. exists, err := client.IndexExists("twitter").Do()
  229. if err != nil {
  230. // Handle error
  231. panic(err)
  232. }
  233. if exists {
  234. // ...
  235. }
  236. }
  237. func ExampleCreateIndexService() {
  238. // Get a client to the local Elasticsearch instance.
  239. client, err := elastic.NewClient()
  240. if err != nil {
  241. // Handle error
  242. panic(err)
  243. }
  244. // Create a new index.
  245. createIndex, err := client.CreateIndex("twitter").Do()
  246. if err != nil {
  247. // Handle error
  248. panic(err)
  249. }
  250. if !createIndex.Acknowledged {
  251. // Not acknowledged
  252. }
  253. }
  254. func ExampleDeleteIndexService() {
  255. // Get a client to the local Elasticsearch instance.
  256. client, err := elastic.NewClient()
  257. if err != nil {
  258. // Handle error
  259. panic(err)
  260. }
  261. // Delete an index.
  262. deleteIndex, err := client.DeleteIndex("twitter").Do()
  263. if err != nil {
  264. // Handle error
  265. panic(err)
  266. }
  267. if !deleteIndex.Acknowledged {
  268. // Not acknowledged
  269. }
  270. }
  271. func ExampleSearchService() {
  272. // Get a client to the local Elasticsearch instance.
  273. client, err := elastic.NewClient()
  274. if err != nil {
  275. // Handle error
  276. panic(err)
  277. }
  278. // Search with a term query
  279. termQuery := elastic.NewTermQuery("user", "olivere")
  280. searchResult, err := client.Search().
  281. Index("twitter"). // search in index "twitter"
  282. Query(&termQuery). // specify the query
  283. Sort("user", true). // sort by "user" field, ascending
  284. From(0).Size(10). // take documents 0-9
  285. Pretty(true). // pretty print request and response JSON
  286. Do() // execute
  287. if err != nil {
  288. // Handle error
  289. panic(err)
  290. }
  291. // searchResult is of type SearchResult and returns hits, suggestions,
  292. // and all kinds of other information from Elasticsearch.
  293. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
  294. // Number of hits
  295. if searchResult.Hits != nil {
  296. fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
  297. // Iterate through results
  298. for _, hit := range searchResult.Hits.Hits {
  299. // hit.Index contains the name of the index
  300. // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
  301. var t Tweet
  302. err := json.Unmarshal(*hit.Source, &t)
  303. if err != nil {
  304. // Deserialization failed
  305. }
  306. // Work with tweet
  307. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  308. }
  309. } else {
  310. // No hits
  311. fmt.Print("Found no tweets\n")
  312. }
  313. }
  314. func ExampleAggregations() {
  315. // Get a client to the local Elasticsearch instance.
  316. client, err := elastic.NewClient()
  317. if err != nil {
  318. // Handle error
  319. panic(err)
  320. }
  321. // Create an aggregation for users and a sub-aggregation for a date histogram of tweets (per year).
  322. timeline := elastic.NewTermsAggregation().Field("user").Size(10).OrderByCountDesc()
  323. histogram := elastic.NewDateHistogramAggregation().Field("created").Interval("year")
  324. timeline = timeline.SubAggregation("history", histogram)
  325. // Search with a term query
  326. searchResult, err := client.Search().
  327. Index("twitter"). // search in index "twitter"
  328. Query(elastic.NewMatchAllQuery()). // return all results, but ...
  329. SearchType("count"). // ... do not return hits, just the count
  330. Aggregation("timeline", timeline). // add our aggregation to the query
  331. Pretty(true). // pretty print request and response JSON
  332. Do() // execute
  333. if err != nil {
  334. // Handle error
  335. panic(err)
  336. }
  337. // Access "timeline" aggregate in search result.
  338. agg, found := searchResult.Aggregations.Terms("timeline")
  339. if !found {
  340. log.Fatalf("we sould have a terms aggregation called %q", "timeline")
  341. }
  342. for _, userBucket := range agg.Buckets {
  343. // Every bucket should have the user field as key.
  344. user := userBucket.Key
  345. // The sub-aggregation history should have the number of tweets per year.
  346. histogram, found := userBucket.DateHistogram("history")
  347. if found {
  348. for _, year := range histogram.Buckets {
  349. fmt.Printf("user %q has %d tweets in %q\n", user, year.DocCount, year.KeyAsString)
  350. }
  351. }
  352. }
  353. }
  354. func ExampleSearchResult() {
  355. client, err := elastic.NewClient()
  356. if err != nil {
  357. panic(err)
  358. }
  359. // Do a search
  360. searchResult, err := client.Search().Index("twitter").Query(elastic.NewMatchAllQuery()).Do()
  361. if err != nil {
  362. panic(err)
  363. }
  364. // searchResult is of type SearchResult and returns hits, suggestions,
  365. // and all kinds of other information from Elasticsearch.
  366. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
  367. // Each is a utility function that iterates over hits in a search result.
  368. // It makes sure you don't need to check for nil values in the response.
  369. // However, it ignores errors in serialization. If you want full control
  370. // over iterating the hits, see below.
  371. var ttyp Tweet
  372. for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
  373. t := item.(Tweet)
  374. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  375. }
  376. fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())
  377. // Here's how you iterate hits with full control.
  378. if searchResult.Hits != nil {
  379. fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)
  380. // Iterate through results
  381. for _, hit := range searchResult.Hits.Hits {
  382. // hit.Index contains the name of the index
  383. // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
  384. var t Tweet
  385. err := json.Unmarshal(*hit.Source, &t)
  386. if err != nil {
  387. // Deserialization failed
  388. }
  389. // Work with tweet
  390. fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
  391. }
  392. } else {
  393. // No hits
  394. fmt.Print("Found no tweets\n")
  395. }
  396. }
  397. func ExamplePutTemplateService() {
  398. client, err := elastic.NewClient()
  399. if err != nil {
  400. panic(err)
  401. }
  402. // Create search template
  403. tmpl := `{"template":{"query":{"match":{"title":"{{query_string}}"}}}}`
  404. // Create template
  405. resp, err := client.PutTemplate().
  406. Id("my-search-template"). // Name of the template
  407. BodyString(tmpl). // Search template itself
  408. Do() // Execute
  409. if err != nil {
  410. panic(err)
  411. }
  412. if resp.Created {
  413. fmt.Println("search template created")
  414. }
  415. }
  416. func ExampleGetTemplateService() {
  417. client, err := elastic.NewClient()
  418. if err != nil {
  419. panic(err)
  420. }
  421. // Get template stored under "my-search-template"
  422. resp, err := client.GetTemplate().Id("my-search-template").Do()
  423. if err != nil {
  424. panic(err)
  425. }
  426. fmt.Printf("search template is: %q\n", resp.Template)
  427. }
  428. func ExampleDeleteTemplateService() {
  429. client, err := elastic.NewClient()
  430. if err != nil {
  431. panic(err)
  432. }
  433. // Delete template
  434. resp, err := client.DeleteTemplate().Id("my-search-template").Do()
  435. if err != nil {
  436. panic(err)
  437. }
  438. if resp != nil && resp.Found {
  439. fmt.Println("template deleted")
  440. }
  441. }
  442. func ExampleClusterHealthService() {
  443. client, err := elastic.NewClient()
  444. if err != nil {
  445. panic(err)
  446. }
  447. // Get cluster health
  448. res, err := client.ClusterHealth().Index("twitter").Do()
  449. if err != nil {
  450. panic(err)
  451. }
  452. if res == nil {
  453. panic(err)
  454. }
  455. fmt.Printf("Cluster status is %q\n", res.Status)
  456. }
  457. func ExampleClusterHealthService_WaitForGreen() {
  458. client, err := elastic.NewClient()
  459. if err != nil {
  460. panic(err)
  461. }
  462. // Wait for status green
  463. res, err := client.ClusterHealth().WaitForStatus("green").Timeout("15s").Do()
  464. if err != nil {
  465. panic(err)
  466. }
  467. if res.TimedOut {
  468. fmt.Printf("time out waiting for cluster status %q\n", "green")
  469. } else {
  470. fmt.Printf("cluster status is %q\n", res.Status)
  471. }
  472. }
  473. func ExampleClusterStateService() {
  474. client, err := elastic.NewClient()
  475. if err != nil {
  476. panic(err)
  477. }
  478. // Get cluster state
  479. res, err := client.ClusterState().Metric("version").Do()
  480. if err != nil {
  481. panic(err)
  482. }
  483. fmt.Printf("Cluster %q has version %d", res.ClusterName, res.Version)
  484. }