单元测试查询

This commit is contained in:
2023-11-30 04:03:19 +08:00
parent e3174a125c
commit ffa12e09cb
3 changed files with 31 additions and 29 deletions

View File

@@ -30,14 +30,33 @@ func elasticsearch_init() (es *elasticsearch.Client) {
}
type SearchData struct {
Total int64 `json:"total"`
_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
}
func ElasticsearchSearch(text string) map[string]interface{} {
var (
r map[string]interface{}
)
func ElasticsearchSearch(text string) (r *SearchData) {
// 通过字符串构建查询
var buf bytes.Buffer
query := map[string]interface{}{
@@ -54,7 +73,7 @@ func ElasticsearchSearch(text string) map[string]interface{} {
es := elasticsearch_init()
// Perform the search request.
// 执行查询
res, err := es.Search(
es.Search.WithContext(context.Background()),
es.Search.WithIndex("my_index"),
@@ -68,30 +87,17 @@ func ElasticsearchSearch(text string) map[string]interface{} {
}
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
}