111 lines
2.3 KiB
Go
111 lines
2.3 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{config.GetString("elasticsearch.host")},
|
|
Username: config.GetString("elasticsearch.user"),
|
|
Password: config.GetString("elasticsearch.password"),
|
|
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 {
|
|
_shards struct {
|
|
failed int
|
|
skipped int
|
|
successful int
|
|
total int
|
|
}
|
|
Hits struct {
|
|
Hits []struct {
|
|
ID string `json:"_id"`
|
|
Index string `json:"_index"`
|
|
Score float64 `json:"_score"`
|
|
Source struct {
|
|
Content string `json:"content"`
|
|
} `json:"_source"`
|
|
Type string `json:"_type"`
|
|
} `json:"hits"`
|
|
max_score float64
|
|
total struct {
|
|
relation string
|
|
value int
|
|
}
|
|
} `json:"hits"`
|
|
timed_out bool
|
|
took int
|
|
}
|
|
|
|
// 获取搜索结果的 ID 列表
|
|
func (sd *SearchData) GetIDList() (id_list []string) {
|
|
for _, hit := range sd.Hits.Hits {
|
|
id_list = append(id_list, hit.ID)
|
|
}
|
|
return id_list
|
|
}
|
|
|
|
// 获取搜索结果的内容列表
|
|
func ElasticsearchSearch(text string) (r *SearchData) {
|
|
// 通过字符串构建查询
|
|
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
|
|
}
|
|
|
|
es := elasticsearch_init()
|
|
|
|
// 执行查询
|
|
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
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
// 处理错误
|
|
if res.IsError() {
|
|
log.Printf("Error: %s", res.String())
|
|
return
|
|
}
|
|
|
|
// 转换返回结果
|
|
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
|
|
log.Printf("Error parsing the response body: %s", err)
|
|
return
|
|
}
|
|
|
|
return r
|
|
}
|