提供elasticsearch api查询 转化成go结构体最好有时间范围
以下是一个示例的Elasticsearch API查询转化为Go结构体的代码,包含了时间范围:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
)
type QueryResponse struct {
Took int `json:"took"`
TimedOut bool `json:"timed_out"`
Hits struct {
Total struct {
Value int `json:"value"`
Relation string `json:"relation"`
} `json:"total"`
Hits []struct {
Index string `json:"_index"`
Source json.RawMessage `json:"_source"`
} `json:"hits"`
} `json:"hits"`
}
type Document struct {
Index string `json:"_index"`
Source struct {
// Define your document fields here
Title string `json:"title"`
Timestamp time.Time `json:"timestamp"`
} `json:"_source"`
}
func main() {
// Elasticsearch client configuration
config := elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
}
// Create a new Elasticsearch client
client, err := elasticsearch.NewClient(config)
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
// Prepare the query
query := map[string]interface{}{
"query": map[string]interface{}{
"range": map[string]interface{}{
"timestamp": map[string]interface{}{
"gte": "2022-01-01T00:00:00Z",
"lte": "2022-01-31T23:59:59Z",
},
},
},
}
// Convert the query to JSON
queryBytes, err := json.Marshal(query)
if err != nil {
log.Fatalf("Error marshaling the query: %s", err)
}
// Perform the search request
res, err := client.Search(
client.Search.WithContext(context.Background()),
client.Search.WithIndex("your-index"),
client.Search.WithBody(bytes.NewReader(queryBytes)),
)
if err != nil {
log.Fatalf("Error performing the search request: %s", err)
}
defer res.Body.Close()
// Parse the search response
var queryResponse QueryResponse
if err := json.NewDecoder(res.Body).Decode(&queryResponse); err != nil {
log.Fatalf("Error parsing the search response: %s", err)
}
// Process the search results
for _, hit := range queryResponse.Hits.Hits {
var doc Document
if err := json.Unmarshal(hit.Source, &doc); err != nil {
log.Printf("Error unmarshaling document: %s", err)
continue
}
// Print the document fields
fmt.Printf("Index: %s, Title: %s, Timestamp: %s\n", doc.Index, doc.Source.Title, doc.Source.Timestamp)
}
}
在上面的代码中,你需要根据你的具体需求修改以下部分:
Addresses:Elasticsearch的地址。在示例中使用http://localhost:9200,你需要根据你的设置进行修改。query:查询的具体内容。在示例中使用了时间范围查询,你可以根据你的需求修改为其他查询方式。client.Search.WithIndex("your-index"):要进行查询的索引名称,你需要将其替换为你的索引名称。
运行上述代码,它将执行Elasticsearch查询并将结果转化为Go结构体进行处理。你可以根据需要进一步处理、保存、输出查询结果
原文地址: https://www.cveoy.top/t/topic/ii8H 著作权归作者所有。请勿转载和采集!