1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package main
import ( "bytes" "context" "encoding/json" "fmt" "log" "strings"
elasticsearch "github.com/elastic/go-elasticsearch/v8" "github.com/elastic/go-elasticsearch/v8/esapi" )
func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://127.0.0.1:9200", }, Username: "elastic", Password: "123456", } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the client: %s", err) } res, err := es.Info() if err != nil { log.Fatalf("Error getting response: %s", err) } defer res.Body.Close() fmt.Println("connect to es success") add := add(es) fmt.Println("新增:", add) query := query(es) fmt.Println("query:", query.String()) deltete := delete(es) fmt.Println("query:", deltete) }
func add(es *elasticsearch.Client) *esapi.Response { add, err := es.Index( "test", strings.NewReader(`{"title" : "hello word"}`), es.Index.WithRefresh("true"), es.Index.WithPretty(), es.Index.WithFilterPath("result", "_id"), ) if err != nil { panic(err) } return add }
func query(es *elasticsearch.Client) *esapi.Response {
var buf bytes.Buffer where := map[string]interface{}{ "query": map[string]interface{}{ "match": map[string]interface{}{ "title": "hello word", }, }, } if err := json.NewEncoder(&buf).Encode(where); err != nil { log.Fatalf("Error encoding query: %s", err) } query, err := es.Search( es.Search.WithContext(context.Background()), es.Search.WithIndex("test"), es.Search.WithBody(&buf), es.Search.WithTrackTotalHits(true), es.Search.WithPretty(), ) if err != nil { panic(err) } return query }
func delete(es *elasticsearch.Client) *esapi.Response { delete, err := es.Delete("test", "dae5NoYBvw08KezVlFPX") if err != nil { panic(err) } return delete }
|