Created
April 22, 2021 14:22
-
-
Save disalvo/205d5192c37ff7b2da3622c5a1234e25 to your computer and use it in GitHub Desktop.
Golang delete (DeleteByQuery) docs on ElasticSearch using go-elasticsearch
This file contains 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
func initElasticsearch() (*elasticsearch.Client, error) { | |
connectionString := fmt.Sprintf("%s:%s", "server-url", "server-port") | |
cfg := elasticsearch.Config{ | |
Addresses: []string{connectionString}, | |
Username: "username", | |
Password: "password", | |
} | |
es, err := elasticsearch.NewClient(cfg) | |
if err != nil { | |
log.Fatal("Error creating ElasticSearch client.") | |
} | |
return es, err | |
} | |
func DeleteDocOnElasticSearch(index string, myField string) bool { | |
var ( | |
buf bytes.Buffer | |
mapResp map[string]interface{} | |
) | |
logConnection, _ = initElasticsearch() // init elastic search connection | |
// Elastic query | |
query := map[string]interface{}{ | |
"query": map[string]interface{}{ | |
"bool": map[string]interface{}{ | |
"filter": []interface{}{ | |
map[string]interface{}{ | |
"match": map[string]interface{}{ | |
"my_field": myField, | |
}, | |
}, | |
}, | |
}, | |
}, | |
} | |
if err := json.NewEncoder(&buf).Encode(query); err != nil { | |
log.Fatal("Error on json.NewEncoder()") | |
} | |
body := strings.NewReader(buf.String()) | |
// DeleteByQuery request | |
res, err := logConnection.DeleteByQuery([]string{index}, body) | |
if err != nil { | |
log.Fatal("Elasticsearch DeleteByQuery() API ERROR") | |
return false | |
} | |
defer res.Body.Close() | |
// Decode response | |
if err := json.NewDecoder(res.Body).Decode(&mapResp); err != nil { | |
log.Fatal("Error parsing the response body,") | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment