package models import ( "bytes" "context" "crypto/tls" "encoding/json" "log" "net/http" "github.com/elastic/go-elasticsearch/v8" ) func elasticsearch_init() (es *elasticsearch.Client) { es, err := elasticsearch.NewClient(elasticsearch.Config{ Addresses: []string{ Viper.Get("elasticsearch.host").(string), }, Username: Viper.Get("elasticsearch.user").(string), Password: Viper.Get("elasticsearch.password").(string), Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, }) if err != nil { log.Printf("Error creating the client: %s", err) return nil } return es } type SearchData struct { Total int64 `json:"total"` } func ElasticsearchSearch(text string) map[string]interface{} { var ( r map[string]interface{} ) // 通过字符串构建查询 var buf bytes.Buffer query := map[string]interface{}{ "query": map[string]interface{}{ "match": map[string]interface{}{ "content": text, }, }, } if err := json.NewEncoder(&buf).Encode(query); err != nil { log.Printf("Error encoding query: %s", err) return nil } es := elasticsearch_init() // Perform the search request. res, err := es.Search( es.Search.WithContext(context.Background()), es.Search.WithIndex("my_index"), es.Search.WithBody(&buf), es.Search.WithTrackTotalHits(true), es.Search.WithPretty(), ) if err != nil { log.Printf("Error getting response: %s", err) return nil } defer res.Body.Close() // Check response status if res.IsError() { log.Printf("Error: %s", res.String()) return nil } // Deserialize the response into a map. if err := json.NewDecoder(res.Body).Decode(&r); err != nil { log.Printf("Error parsing the response body: %s", err) return nil } // Print the response status, number of results, and request duration. log.Printf( "[%s] %d hits; took: %dms", res.Status(), int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64)), int(r["took"].(float64)), ) // Print the ID and document source for each hit. for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) { log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"]) } return r }