提供elasticsearch api查询 转化成go结构体覆盖百分之90的查询场景
以下是一个示例,展示了如何将Elasticsearch API查询转换为Go结构体:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type ElasticsearchQuery struct {
Query struct {
Term struct {
Field string `json:"field"`
Value string `json:"value"`
} `json:"term"`
} `json:"query"`
}
type ElasticsearchResponse struct {
Hits struct {
Total struct {
Value int `json:"value"`
} `json:"total"`
Hits []struct {
Source map[string]interface{} `json:"_source"`
} `json:"hits"`
} `json:"hits"`
}
func main() {
// 构建查询结构体
query := ElasticsearchQuery{
Query: struct {
Term struct {
Field string `json:"field"`
Value string `json:"value"`
} `json:"term"`
}{
Term: struct {
Field string `json:"field"`
Value string `json:"value"`
}{
Field: "name",
Value: "John",
},
},
}
// 将结构体转换为JSON
jsonData, err := json.Marshal(query)
if err != nil {
fmt.Println("Error:", err)
return
}
// 发送POST请求到Elasticsearch
resp, err := http.Post("http://localhost:9200/index/_search", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// 解析响应
var response ElasticsearchResponse
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
fmt.Println("Error:", err)
return
}
// 处理响应数据
fmt.Println("Total Hits:", response.Hits.Total.Value)
for _, hit := range response.Hits.Hits {
fmt.Println("Source:", hit.Source)
}
}
注意,这只是一个简单的示例,仅覆盖了部分查询场景。具体的查询结构体和响应结构体可能会根据实际情况进行修改。您可能需要根据您的具体需求进行调整
原文地址: https://www.cveoy.top/t/topic/ii8C 著作权归作者所有。请勿转载和采集!