forked from defensestation/osquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete.go
73 lines (60 loc) · 2.04 KB
/
delete.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Modified by DefenseStation on 2024-06-06
// Changes: Updated ElasticSearch client to OpenSearch client, changed package name to 'osquery',
// updated references to OpenSearch documentation, and modified examples accordingly.
package osquery
import (
"bytes"
"context"
"encoding/json"
"fmt"
opensearch "github.com/opensearch-project/opensearch-go/v4"
opensearchapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
)
// DeleteRequest represents a request to OpenSearch's Delete By Query API,
// described in
// https://opensearch.org/docs/latest/search-plugins/sql/sql/delete/
type DeleteRequest struct {
index []string
query Mappable
}
// Delete creates a new DeleteRequest object, to be filled via method chaining.
func Delete() *DeleteRequest {
return &DeleteRequest{}
}
// Index sets the index names for the request
func (req *DeleteRequest) Index(index ...string) *DeleteRequest {
req.index = index
return req
}
// Query sets a query for the request.
func (req *DeleteRequest) Query(q Mappable) *DeleteRequest {
req.query = q
return req
}
// Run executes the request using the provided OpenSearch client.
func (req *DeleteRequest) Run(
ctx context.Context,
client *opensearch.Client,
options *Options,
) (*opensearchapi.DocumentDeleteByQueryResp, error) {
// Serialize the request body to JSON
body, err := json.Marshal(req.query.Map())
if err != nil {
return nil, fmt.Errorf("failed to serialize request body: %w", err)
}
// Create a DeleteReq with the request body
deleteReq := opensearchapi.DocumentDeleteByQueryReq{
Body: bytes.NewReader(body), // Pass the encoded request body
}
// Apply any additional options to modify the DeleteReq, such as context or index
err = ApplyOptions(&deleteReq, options)
if err != nil {
return nil, err
}
var deleteResp opensearchapi.DocumentDeleteByQueryResp
// Execute the delete request using the OpenSearch client's Do method
if _, err := client.Do(ctx, deleteReq, &deleteResp); err != nil {
return nil, fmt.Errorf("delete request failed: %w", err)
}
return &deleteResp, nil
}