TP-55555 | latest push
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"cybertron/configs"
|
||||
"encoding/json"
|
||||
elasticsearch8 "github.com/elastic/go-elasticsearch/v8"
|
||||
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
|
||||
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
|
||||
@@ -44,15 +45,53 @@ func (el *ElasticSearchClient) IndexDocument(document interface{}) {
|
||||
}
|
||||
}
|
||||
|
||||
func (el *ElasticSearchClient) SearchDocuments(query *types.Query) *search.Response {
|
||||
func (el *ElasticSearchClient) SearchDocuments(query *types.Query, fields []string) ([]map[string]interface{}, error) {
|
||||
res, err := el.client.Search().
|
||||
Index(el.Config.Index).
|
||||
Request(&search.Request{
|
||||
Query: query,
|
||||
}).
|
||||
}).Source_(fields).
|
||||
Do(context.TODO())
|
||||
if err != nil {
|
||||
log.Println("Error getting response: %s", err)
|
||||
}
|
||||
return res
|
||||
var results []map[string]interface{}
|
||||
for _, hit := range res.Hits.Hits {
|
||||
var doc map[string]interface{}
|
||||
|
||||
err := json.Unmarshal(hit.Source_, &doc)
|
||||
doc["id"] = *hit.Id_
|
||||
if err != nil {
|
||||
log.Printf("Error unmarshalling document: %s", err)
|
||||
continue
|
||||
}
|
||||
results = append(results, doc)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (el *ElasticSearchClient) GetDocument(documentID string) (interface{}, error) {
|
||||
// Retrieve the document by its ID
|
||||
res, err := el.client.Get(el.Config.Index, documentID).Do(context.Background())
|
||||
var document interface{}
|
||||
if err != nil {
|
||||
log.Printf("Error getting response: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if the document exists
|
||||
if !res.Found {
|
||||
log.Printf("Document with ID %s not found", documentID)
|
||||
return document, nil
|
||||
}
|
||||
|
||||
// Unmarshal the JSON response into the provided document interface
|
||||
err = json.Unmarshal(res.Source_, &document)
|
||||
if err != nil {
|
||||
log.Printf("Error unmarshalling document: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return document, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user