l0s7r
l0s7r

Reputation: 35

Use elasticsearch atomic operation update

func (d *Dynamic) Like(ctx *gin.Context) {
    var (
        req message.Like
        err error
        buf bytes.Buffer
    )
    if err = ctx.ShouldBind(&req); err != nil {
        d.ResponseJson(ctx, 400, err.Error(), nil)
        return
    }
    doc := map[string]interface{}{
        "doc": map[string]interface{}{
            "like_number": 1,
        },
    }
    if err := json.NewEncoder(&buf).Encode(doc); err != nil {
        fmt.Printf("%v", err.Error())
    }
    resp, err := config.Global.ES.Update("live_dynamic_list", req.DynamicId, &buf, config.Global.ES.Update.WithDocumentType("doc"))
    fmt.Printf("%v", resp)
    if err != nil {
        d.ResponseJson(ctx, 400, err.Error(), nil)
        return
    }
    d.ResponseJson(ctx, 200, "success", nil)
}

Upvotes: 1

Views: 647

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

Atomic updates like in-place incrementation are usually performed via scripts:

POST live_dynamic_list/_update/doc_id
{
  "script" : {
    "source": "ctx._source.like_number += params.increment",
    "lang": "painless",
    "params" : {
      "increment" : 1
    }
  }
}

Here's how you can use such update scripts in go.

Upvotes: 3

Related Questions