diff --git a/bin/main.go b/bin/main.go index fb37e3c..a3333f8 100644 --- a/bin/main.go +++ b/bin/main.go @@ -301,22 +301,9 @@ func main() { } var conditions strings.Builder // 如果是查询 text, 直接从 Elasticsearch 返回结果 - var text_ids []int + var text_ids []string if text := QueryConditions("text"); len(text) > 0 { - rest := models.ElasticsearchSearch(strings.Join(text, " ")) - if rest == nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - for _, hit := range rest["hits"].(map[string]interface{})["hits"].([]interface{}) { - id, err := strconv.Atoi(hit.(map[string]interface{})["_id"].(string)) - if err != nil { - log.Println("strconv.Atoi failed:", err) - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - text_ids = append(text_ids, id) - } + text_ids := models.ElasticsearchSearch(strings.Join(text, " ")).GetIDList() if len(text_ids) > 0 { conditions.WriteString(fmt.Sprintf(" WHERE id IN (%s)", strings.Trim(strings.Replace(fmt.Sprint(text_ids), " ", ",", -1), "[]"))) } else { diff --git a/models/elasticsearch.go b/models/elasticsearch.go index a478075..a2f1c24 100644 --- a/models/elasticsearch.go +++ b/models/elasticsearch.go @@ -56,6 +56,13 @@ type SearchData struct { took int } +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 @@ -68,7 +75,7 @@ func ElasticsearchSearch(text string) (r *SearchData) { } if err := json.NewEncoder(&buf).Encode(query); err != nil { log.Printf("Error encoding query: %s", err) - return nil + return } es := elasticsearch_init() @@ -83,20 +90,20 @@ func ElasticsearchSearch(text string) (r *SearchData) { ) if err != nil { log.Printf("Error getting response: %s", err) - return nil + return } defer res.Body.Close() // 处理错误 if res.IsError() { log.Printf("Error: %s", res.String()) - return nil + return } // 转换返回结果 if err := json.NewDecoder(res.Body).Decode(&r); err != nil { log.Printf("Error parsing the response body: %s", err) - return nil + return } return r