Elasticsearch的一個Google Go客戶端:Elastic

jopen 11年前發布 | 92K 次閱讀 Elastic Google Go/Golang開發

Elastic是分布式搜索引擎Elasticsearch的一個Google Go客戶端。Elastic 在生產環境中測試支持的Elasticsearch版本: 0.90, 1.0, 1.1, 1.2, 和 1.3。

// Import Elastic
import (
  "github.com/olivere/elastic"
)

// Obtain a client. You can provide your own HTTP client here. client, err := elastic.NewClient(http.DefaultClient) if err != nil { // Handle error panic(err) }

// Use the IndexExists service to check if a specified index exists. exists, err := client.IndexExists("推ter").Do() if err != nil { // Handle error panic(err) } if !exists { // Create a new index. createIndex, err := client.CreateIndex("推ter").Do() if err != nil { // Handle error panic(err) } if !createIndex.Acknowledged { // Not acknowledged } }

// Index a tweet (using JSON serialization) tweet1 := Tweet{User: "olivere", Message: "Take Five"} put1, err := client.Index(). Index("推ter"). Type("tweet"). Id("1"). BodyJson(tweet1). Do() if err != nil { // Handle error panic(err) } fmt.Printf("Indexed tweet %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)

// Index a second tweet (by string) tweet2 := {"user" : "olivere", "message" : "It's a Raggy Waltz"} put2, err := client.Index(). Index("推ter"). Type("tweet"). Id("2"). BodyString(tweet2). Do() if err != nil { // Handle error panic(err) } fmt.Printf("Indexed tweet %s to index %s, type %s\n", put2.Id, put2.Index, put2.Type)

// Get tweet with specified ID get1, err := client.Get(). Index("推ter"). Type("tweet"). Id("1"). Do() if err != nil { // Handle error panic(err) } if get1.Found { fmt.Printf("Got document %s in version %d from index %s, type %s\n", get1.Id, get1.Version, get1.Index, get1.Type) }

// Flush to make sure the documents got written. _, err = client.Flush().Index("推ter").Do() if err != nil { panic(err) }

// Search with a term query termQuery := elastic.NewTermQuery("user", "olivere") searchResult, err := client.Search(). Index("推ter"). // search in index "推ter" Query(&termQuery). // specify the query Sort("user", true). // sort by "user" field, ascending From(0).Size(10). // take documents 0-9 Debug(true). // print request and response to stdout 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 information from Elasticsearch. fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)

// Number of hits if searchResult.Hits != nil { 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 an index. deleteIndex, err := client.DeleteIndex("推ter").Do() if err != nil { // Handle error panic(err) } if !deleteIndex.Acknowledged { // Not acknowledged }</pre>

API Status

Here's the current API status.

APIs

  • Search (most queries, filters, facets, aggregations etc. are implemented: see below)
  • Index
  • Get
  • Delete
  • Update
  • Multi Get
  • Bulk
  • Bulk UDP
  • Term vectors
  • Multi term vectors
  • Count
  • Validate
  • Explain
  • Search
  • Search shards
  • Search template
  • Facets (most are implemented, see below)
  • Aggregates (most are implemented, see below)
  • Multi Search
  • Percolate
  • Delete By Query
  • More like this
  • Benchmark

Indices

  • Create index
  • Delete index
  • Indices exists
  • Open/close index
  • Put mapping
  • Get mapping
  • Get field mapping
  • Types exist
  • Delete mapping
  • Index aliases
  • Update indices settings
  • Get settings
  • Analyze
  • Index templates
  • Warmers
  • Status
  • Indices stats
  • Indices segments
  • Indices recovery
  • Clear cache
  • Flush
  • Refresh
  • Optimize

Snapshot and Restore

  • Snapshot
  • Restore
  • Snapshot status
  • Monitoring snapshot/restore progress
  • Partial restore

Cat APIs

Not implemented. Those are better suited for operating with Elasticsearch on the command line.

Cluster

  • Health
  • State
  • Stats
  • Pending cluster tasks
  • Cluster reroute
  • Cluster update settings
  • Nodes stats
  • Nodes info
  • Nodes hot_threads
  • Nodes shutdown

Query DSL

Queries

  • match
  • multi_match
  • bool
  • boosting
  • common_terms
  • constant_score
  • dis_max
  • filtered
  • fuzzy_like_this_query (flt)
  • fuzzy_like_this_field_query (flt_field)
  • function_score
  • fuzzy
  • geo_shape
  • has_child
  • has_parent
  • ids
  • indices
  • match_all
  • mlt
  • mlt_field
  • nested
  • prefix
  • query_string
  • simple_query_string
  • range
  • regexp
  • span_first
  • span_multi_term
  • span_near
  • span_not
  • span_or
  • span_term
  • term
  • terms
  • top_children
  • wildcard
  • minimum_should_match
  • multi_term_query_rewrite
  • template_query

Filters

  • and
  • bool
  • exists
  • geo_bounding_box
  • geo_distance
  • geo_distance_range
  • geo_polygon
  • geoshape
  • geohash
  • has_child
  • has_parent
  • ids
  • indices
  • limit
  • match_all
  • missing
  • nested
  • not
  • or
  • prefix
  • query
  • range
  • regexp
  • script
  • term
  • terms
  • type

Facets

  • Terms
  • Range
  • Histogram
  • Date Histogram
  • Filter
  • Query
  • Statistical
  • Terms Stats
  • Geo Distance

Aggregations

  • min
  • max
  • sum
  • avg
  • stats
  • extended stats
  • value count
  • percentiles
  • percentile ranks
  • cardinality
  • geo bounds
  • top hits
  • scripted metric
  • global
  • filter
  • filters
  • missing
  • nested
  • reverse nested
  • children
  • terms
  • significant terms
  • range
  • date range
  • ipv4 range
  • histogram
  • date histogram
  • geo distance
  • geohash grid

項目主頁:http://www.baiduhome.net/lib/view/home/1417077815924

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!