Golang操作es使用mysql语法

发布时间 2023-10-20 15:58:10作者: 朝阳1
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
)

// 根据sql查询
func main() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://192.168.252.1:9200",
		},
	}
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		fmt.Println("Elasticsearch connection error:", err)
	}
	es, _ := elasticsearch.NewClient(cfg)
	res, err := es.Search(
		es.Search.WithQuery("SELECT SomeInt,SomeStr,SomeBool FROM some_index where SomeStr = \"Another Value\""),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}

	defer res.Body.Close()

	if res.IsError() {
		var e map[string]interface{}
		if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
			log.Fatalf("Error parsing the response body: %s", err)
		} else {
			// Print the response status and error information.
			log.Fatalf("[%s] %s: %s",
				res.Status(),
				e["error"].(map[string]interface{})["type"],
				e["error"].(map[string]interface{})["reason"],
			)
		}
	}

	var r map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}

	// Print the response status, number of results, and request duration.
	log.Printf(
		"[%s] %d 中了; 花费: %dms",
		res.Status(),
		int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64)),
		int(r["took"].(float64)),
	)
	//map[_shards:map[failed:0 skipped:0 successful:1 total:1]
	//hits:map[hits:[map[_id:xfPNS4sB8raaM58KGS-L _index:some_index _score:0.6931471
	//_source:map[SomeBool:false SomeInt:42 SomeStr:Another Value]]]
	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		log.Printf(" ID=%s, 内容=%v", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
	}
	//TODO 删除文档
	// Set up the request object.
	req := esapi.DeleteRequest{
		Index:      "some_index",
		DocumentID: r["ID"].(string),
	}

	res, err = req.Do(context.Background(), client)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
}