Elastic-Go Elasticsearch的Go语言客户端开发包

我要开发同款
匿名用户2016年08月11日
38阅读
所属分类Google Go、程序开发、搜索引擎
授权协议MIT

作品详情

Elastic是Elasticsearch的Go语言客户端开发包。

快速入门:

// Create a clientclient, 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 indextweet := 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 querytermQuery := 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()                // executeif err != nil {    // Handle error    panic(err)}// searchResult is of type SearchResult and returns hits, suggestions,// and all kinds of other information 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 Tweetfor _, 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)}
查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论