Files
rootandClaude Opus 5 8679200f41 Initial commit
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 13:57:10 +08:00

111 lines
2.4 KiB
Go

package elastic
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/elastic/go-elasticsearch/v8"
)
var (
AnalyzerIkSmart = "ik_smart"
AnalyzerIkMaxWord = "ik_max_word"
NumberOfShards = 1
NumberOfReplicas = 1
)
// Client
type Client struct {
Client *elasticsearch.Client
}
func unmarshalAggregateBody(bind interface{}, resp *Response) error {
var v map[string]interface{}
if bind == nil { //传入空表示只执行 defer
return nil
}
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
if len(v) > 0 {
if v, ok := v["aggregations"].(map[string]interface{}); ok {
b, _ := json.Marshal(v)
_ = json.Unmarshal(b, &bind)
}
}
return nil
}
func unmarshalBodyWithTotal(bind interface{}, resp *Response) error {
var v map[string]interface{}
if bind == nil { //传入空表示只执行 defer
return nil
}
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
if len(v) > 0 {
if h, ok := v["hits"].(map[string]interface{}); ok {
b, err := json.Marshal(h)
if err != nil {
return err
}
if err = json.Unmarshal(b, &bind); err != nil {
return err
}
}
}
return nil
}
func unmarshalBody(bind interface{}, resp *Response) error {
var v map[string]interface{}
if bind == nil { //传入空表示只执行 defer
return nil
}
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
if len(v) > 0 {
if h, ok := v["hits"].(map[string]interface{}); ok {
if hh, ok := h["hits"].([]interface{}); ok {
b, _ := json.Marshal(hh)
_ = json.Unmarshal(b, &bind)
}
} else if _, ok := v["docs"].([]interface{}); ok {
b, _ := json.Marshal(v["docs"])
_ = json.Unmarshal(b, &bind)
} else if _, ok := v["_source"].(map[string]interface{}); ok {
b, _ := json.Marshal(v)
_ = json.Unmarshal(b, &bind)
}
}
return nil
}
func marshalSearchM(query M) io.Reader {
var buf bytes.Buffer
if len(query) == 0 {
return nil
}
if err := json.NewEncoder(&buf).Encode(query); err != nil {
return nil
}
return bytes.NewReader(buf.Bytes())
}
func marshalBulkM(source M) io.Reader {
var buf bytes.Buffer
for k, v := range source {
var meta = []byte(fmt.Sprintf(`{ "index" : { "_id" : "%s" } }%s`, k, "\n"))
var data, _ = json.Marshal(v)
data = append(data, "\n"...)
buf.Grow(len(meta) + len(data))
buf.Write(meta)
buf.Write(data)
}
return bytes.NewReader(buf.Bytes())
}