Golang操作es使用mysql语法

有时候拼接es语法太麻烦了,熟悉mysql的同学可以用mysql语法,6.X以上的es版本都支持

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v8"
	"log"
)

type Response struct {
	Shards Shards `json:"_shards"`
	Hits   Hits   `json:"hits"`
}

type Shards struct {
	Failed     int `json:"failed"`
	Skipped    int `json:"skipped"`
	Successful int `json:"successful"`
	Total      int `json:"total"`
}

type Hits struct {
	Hits []Hit `json:"hits"`
}

type Hit struct {
	ID     string  `json:"_id"`
	Index  string  `json:"_index"`
	Score  float64 `json:"_score"`
	Source Source  `json:"_source"`
}

type Source struct {
	SomeBool bool   `json:"SomeBool"`
	SomeInt  int    `json:"SomeInt"`
	SomeStr  string `json:"SomeStr"`
}
type QueryResponse struct {
	Columns []Column        `json:"columns"`
	Rows    [][]interface{} `json:"rows"`
}

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

// 根据sql查询
func main() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://192.168.252.1:9200",
		},
	}
	es, err := elasticsearch.NewClient(cfg)
	if err != nil {
		log.Fatalf("连接出错: %s", err)
	}
	var buf bytes.Buffer
	query := map[string]interface{}{
		"query": "SELECT SomeInt,SomeStr,SomeBool FROM some_index where SomeStr = 'Another Value' limit 1",
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	res, err := es.SQL.Query(&buf)
	fmt.Println(res, err)

	defer res.Body.Close()
	var queryResponse QueryResponse
	err = json.NewDecoder(res.Body).Decode(&queryResponse)
	if err != nil {
		fmt.Println("Error unmarshaling JSON:", err)
		return
	}

	fmt.Println("Columns:")
	for _, col := range queryResponse.Columns {
		fmt.Printf("Name: %s, Type: %s\n", col.Name, col.Type)
	}

	fmt.Println("\nRows:")
	for _, row := range queryResponse.Rows {
		for i, val := range row {
			fmt.Printf("Value at index %d: %v\n", i, val)
		}
	}
}

结果

[200 OK] {"columns":[{"name":"SomeInt","type":"long"},{"name":"SomeStr","type":"text"},{"name":"SomeBool","type":"boolean"}],"rows":[[42,"Another Value",false]]} <nil>
Columns:
Name: SomeInt, Type: long
Name: SomeStr, Type: text
Name: SomeBool, Type: boolean

Rows:
Value at index 0: 42
Value at index 1: Another Value
Value at index 2: false

posted @ 2023-10-20 15:55  朝阳1  阅读(70)  评论(0编辑  收藏  举报