Skip to content

Instantly share code, notes, and snippets.

@olivere
Created March 1, 2018 07:27
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save olivere/e4a376b4783c0914e44ea4f745ce2ebf to your computer and use it in GitHub Desktop.
Save olivere/e4a376b4783c0914e44ea4f745ce2ebf to your computer and use it in GitHub Desktop.
Getting started with Elastic v6
package main
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/olivere/elastic"
)
type Tweet struct {
User string `json:"user"`
Message string `json:"message"`
}
func main() {
// Create a client
client, err := elastic.NewClient()
if err != nil {
// Handle error
}
// Create an index
_, err = client.CreateIndex("tweets").Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
// Add a document to the index
tweet := Tweet{User: "olivere", Message: "Take Five"}
_, err = client.Index().
Index("tweets").
Type("doc").
Id("1").
BodyJson(tweet).
Refresh("wait_for").
Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
// Search with a term query
termQuery := elastic.NewTermQuery("user", "olivere")
searchResult, err := client.Search().
Index("tweets"). // search in index "tweets"
Query(termQuery). // specify the query
Sort("user.keyword", true). // sort by "user" field, ascending
From(0).Size(10). // take documents 0-9
Pretty(true). // pretty print request and response JSON
Do(context.Background()) // 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)
// 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("tweets").Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
}
@olivere
Copy link
Author

olivere commented Aug 26, 2018

For Go 1.11 (or Go 1.10.4) with modules support, use this import instead:

import (
	"context"
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/olivere/elastic/v6" // <- notice the trailing v6
)
...

@Phillip-Gabler
Copy link

Ok... trying this for the first time, and I get:

C:\zSandbox\GoWorkspace\src\github.comcast.com\pgable000\predictElk>go build
go: downloading github.com/olivere/elastic/v6 v6.2.5
bulkInsert.go:9:2: unknown import path "github.com/olivere/elastic/v6": cannot find module providing package github.com/olivere/elastic/v6

Any thoughts? (I am compiling on Windows 7, then will move the code to Linux.)

Copy link

ghost commented Jan 5, 2019

Module support comes with v7 if I recall correctly, so your only option is to manually enter the v6 release commit in your go.mod and wait for v7 to be released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment