59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package elastic
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"cybertron/configs"
|
|
elasticsearch8 "github.com/elastic/go-elasticsearch/v8"
|
|
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
|
|
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type ElasticSearchClient struct {
|
|
client *elasticsearch8.TypedClient
|
|
Config configs.ElasticConfig
|
|
}
|
|
|
|
func NewElasticClient(elasticConfig configs.ElasticConfig) (*ElasticSearchClient, error) {
|
|
cfg := elasticsearch8.Config{
|
|
Addresses: elasticConfig.Addresses,
|
|
APIKey: elasticConfig.APIKey,
|
|
Transport: &http.Transport{
|
|
TLSClientConfig: &tls.Config{
|
|
InsecureSkipVerify: true,
|
|
},
|
|
},
|
|
}
|
|
|
|
client, err := elasticsearch8.NewTypedClient(cfg)
|
|
return &ElasticSearchClient{
|
|
client: client,
|
|
Config: elasticConfig,
|
|
}, err
|
|
}
|
|
|
|
func (el *ElasticSearchClient) IndexDocument(document interface{}) {
|
|
_, err := el.client.Index(el.Config.Index).
|
|
Request(document).
|
|
Do(context.TODO())
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func (el *ElasticSearchClient) SearchDocuments(query *types.Query) *search.Response {
|
|
res, err := el.client.Search().
|
|
Index(el.Config.Index).
|
|
Request(&search.Request{
|
|
Query: query,
|
|
}).
|
|
Do(context.TODO())
|
|
if err != nil {
|
|
log.Println("Error getting response: %s", err)
|
|
}
|
|
return res
|
|
}
|