Elastic-Go 介绍
Elastic是Elasticsearch的Go语言客户端开发包。
快速入门:
// Create a client client, err := elastic.NewClient() if err != nil { // Handle error } // Create an index _, err = client.CreateIndex("twitter").Do() if err != nil { // Handle error panic(err) } // Add a document to the index tweet := Tweet{User: "olivere", Message: "Take Five"} _, err = client.Index(). Index("twitter"). Type("tweet"). Id("1"). BodyJson(tweet). Refresh(true). Do() if err != nil { // Handle error panic(err) } // Search with a term query termQuery := elastic.NewTermQuery("user", "olivere") searchResult, err := client.Search(). Index("twitter"). // search in index "twitter" Query(termQuery). // specify the query Sort("user", true). // sort by "user" field, ascending From(0).Size(10). // take documents 0-9 Pretty(true). // pretty print request and response JSON Do() // execute if err != nil { // Handle error panic(err) } // searchResult is of type SearchResult and returns hits, suggestions, // and all kinds of other @R_749_4045@ion from Elasticsearch. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis) // Each is a convenience function that iterates over hits in a search result. // It makes sure you don't need to check for nil values in the response. // However, it ignores errors in serialization. If you want full control // over iterating the hits, see below. var ttyp Tweet for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) { if t, ok := item.(Tweet); ok { fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } } // TotalHits is another convenience function that works even when something goes wrong. fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits()) // Here's how you iterate through results with full control over each step. if searchResult.Hits.TotalHits > 0 { fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits) // Iterate through results for _, hit := range searchResult.Hits.Hits { // hit.Index contains the name of the index // Deserialize hit.source into a Tweet (Could also be just a map[string]interface{}). var t Tweet err := json.Unmarshal(*hit.source, &t) if err != nil { // Deserialization Failed } // Work with tweet fmt.Printf("Tweet by %s: %s\n", t.User, t.Message) } } else { // No hits fmt.Print("Found no tweets\n") } // Delete the index again _, err = client.DeleteIndex("twitter").Do() if err != nil { // Handle error panic(err) }
Elastic-Go 官网
https://github.com/olivere/elastic
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。