2024-10-07 16:26:41 +05:30
|
|
|
package elastic
|
2024-10-03 12:57:23 +05:30
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2024-10-07 16:26:41 +05:30
|
|
|
"elasticstream/opencdc"
|
|
|
|
|
2024-10-03 12:57:23 +05:30
|
|
|
"github.com/elastic/go-elasticsearch/esapi"
|
|
|
|
"github.com/elastic/go-elasticsearch/v8"
|
|
|
|
)
|
|
|
|
|
|
|
|
// search is calling Elastic Search search API
|
2024-10-07 16:26:41 +05:30
|
|
|
func search(client *elasticsearch.Client, index string, offset, size *int) ([]opencdc.Data, error) {
|
2024-10-03 12:57:23 +05:30
|
|
|
query := fmt.Sprintf(`{
|
|
|
|
"query": {
|
|
|
|
"match_all": {}
|
|
|
|
}
|
|
|
|
}`)
|
|
|
|
|
|
|
|
// Create the search request
|
|
|
|
req := esapi.SearchRequest{
|
|
|
|
Index: []string{index},
|
|
|
|
Body: strings.NewReader(query),
|
2024-10-07 09:50:00 +05:30
|
|
|
From: offset,
|
|
|
|
Size: size,
|
2024-10-03 12:57:23 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// Perform the request
|
|
|
|
res, err := req.Do(context.Background(), client)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error getting response: %s", err)
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
|
|
|
if res.IsError() {
|
2024-10-07 09:50:00 +05:30
|
|
|
return nil, fmt.Errorf("res.IsError() error: %s", res.String())
|
2024-10-03 12:57:23 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// Parse the response
|
|
|
|
var result struct {
|
|
|
|
Hits struct {
|
|
|
|
Hits []struct {
|
|
|
|
Source map[string]interface{} `json:"_source"`
|
|
|
|
} `json:"hits"`
|
|
|
|
} `json:"hits"`
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
|
|
|
|
return nil, fmt.Errorf("error parsing the response body: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Collect the records
|
|
|
|
newRecords := make([]map[string]interface{}, len(result.Hits.Hits))
|
|
|
|
for i, hit := range result.Hits.Hits {
|
|
|
|
newRecords[i] = hit.Source
|
|
|
|
}
|
|
|
|
|
2024-10-07 16:26:41 +05:30
|
|
|
header := opencdc.Header{Index: index}
|
2024-10-03 12:57:23 +05:30
|
|
|
|
2024-10-07 16:26:41 +05:30
|
|
|
var records []opencdc.Data
|
2024-10-03 12:57:23 +05:30
|
|
|
for _, v := range newRecords {
|
2024-10-07 16:26:41 +05:30
|
|
|
data := opencdc.Data{
|
2024-10-03 12:57:23 +05:30
|
|
|
Header: header,
|
|
|
|
Payload: v,
|
|
|
|
}
|
|
|
|
records = append(records, data)
|
|
|
|
}
|
|
|
|
|
2024-10-07 09:50:00 +05:30
|
|
|
// log.Println("records:", records)
|
|
|
|
|
2024-10-03 12:57:23 +05:30
|
|
|
return records, nil
|
|
|
|
}
|