Files
webp/models/elasticsearch.go
2023-11-20 03:26:46 +08:00

90 lines
2.1 KiB
Go

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
}
func ElasticsearchSearch(text 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.Fatalf("Error encoding query: %s", err)
}
es := elasticsearch_init()
// Perform the search request.
res, err := es.Search(
es.Search.WithContext(context.Background()),
es.Search.WithIndex("news"),
es.Search.WithBody(&buf),
es.Search.WithTrackTotalHits(true),
es.Search.WithPretty(),
)
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
// Check response status
if res.IsError() {
log.Fatalf("Error: %s", res.String())
}
// Deserialize the response into a map.
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
// 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
}