Created
March 26, 2019 20:22
-
-
Save jlopezzarza/bb9373c9b34a9bf221a8213b167b5cf6 to your computer and use it in GitHub Desktop.
Basic search in ES with the elastic/go-elasticsearch client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"os" | |
"strings" | |
"github.com/elastic/go-elasticsearch" | |
) | |
// Look for the movie in elasticSearch | |
func esSearch(query string) { | |
res, err := esConn.Search( | |
// esConn.Search.WithIndex("INDEX"), // you can especify an index | |
esConn.Search.WithBody(strings.NewReader(query)), | |
) | |
if err != nil { | |
log.Fatalf("ERROR: %s", err) | |
} | |
defer res.Body.Close() | |
if res.IsError() { | |
log.Println("Error in the elasticserch query: ", err) | |
} | |
var response map[string]interface{} | |
if err := json.NewDecoder(res.Body).Decode(&response); err != nil { | |
log.Printf("Error parsing the response body: %s", err) | |
} | |
for _, hit := range response["hits"].(map[string]interface{})["hits"].([]interface{}) { | |
log.Printf("Result: %s", hit.(map[string]interface{})["_source"]) | |
} | |
} | |
var esConn *elasticsearch.Client | |
// Connect to elasticsearch | |
func esConnect() { | |
log.Println("Connecting to Elastich Search") | |
addr := fmt.Sprintf("http://%s:%s", os.Getenv("ES_HOST"), os.Getenv("ES_PORT")) | |
cfg := elasticsearch.Config{ | |
Addresses: []string{ | |
addr, | |
}, | |
} | |
es, err := elasticsearch.NewClient(cfg) | |
if err != nil { | |
log.Fatal("Unable to connect to ES") | |
} | |
esConn = es | |
return | |
} | |
// Check if env variables are setted | |
func preflightCheck() { | |
if _, ok := os.LookupEnv("ES_HOST"); !ok { | |
log.Fatal("No elasticsearch host configured") | |
} | |
if _, ok := os.LookupEnv("ES_PORT"); !ok { | |
log.Fatal("No elasticsearch port configured") | |
} | |
} | |
func main() { | |
preflightCheck() | |
// Search for every document | |
query := `{"query" : { "match_all" : {} }}` | |
// Connect to ES and save the conn into the global variable | |
esConnect() | |
// Make the query to ES | |
esSearch(query) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment