I'm using go-elasticsearch as a elastic search client.
I tried to update document using code from here elastic/go-elasticsearch/api.update.go
However using the same code from GitHub I got:
[UpdateRequest] unknown field [Title]
So far I have only one document which looks like this
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 4,
"successful": 4,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "posts",
"_type": "_doc",
"_id": "fc87941f-dc82-4fdb-9e04-460830e5f3ab",
"_score": 1.0,
"_source": {
"Title": "one two three2",
"Done": false,
"Created": "2022-02-09T11:51:59.027356 01:00",
"Updated": null
}
}
]
}
}
My go function:
func (postRepository) Update(id uuid.UUID, input inputs.Post) error {
channel := make(chan error)
go func() {
post := entities.Post{
Title: "title updated",
}
body, err := json.Marshal(post)
if err != nil {
channel <- err
}
request := esapi.UpdateRequest{
Index: index,
DocumentID: id.String(),
Body: strings.NewReader(string(body)),
}
response, err := request.Do(context.Background(), data.ElasticSearchClient)
if err != nil {
channel <- err
}
defer response.Body.Close()
if response.IsError() {
var b map[string]interface{}
e := json.NewDecoder(response.Body).Decode(&b)
if e != nil {
fmt.Println(fmt.Errorf("error parsing the response body: %s", err))
}
fmt.Println(fmt.Errorf("reason: %s", b["error"].(map[string]interface{})["reason"].(string)))
channel <- fmt.Errorf("[%s] Error indexing document", response.Status())
}
channel <- nil
}()
return <-channel
}
My entity:
type Post struct {
Title string
Done bool
Created time.Time
Updated *time.Time
}
In addition this is the only function which does not work, other function like: AddDocument
, RemoveDocument
, GetDocuments
all works as expected.
CodePudding user response:
Found solution here: a-simple-elasticsearch-crud-example-in-golang
Instead of using:
request := esapi.UpdateRequest{
Index: index,
DocumentID: id.String(),
Body: strings.NewReader(string(body)),
}
use
request := esapi.UpdateRequest{
Index: index,
DocumentID: id.String(),
Body: bytes.NewReader([]byte(fmt.Sprintf(`{"doc":%s}`, body))),
}