使用Elasticsearch更新文档。

huangapple go评论90阅读模式
英文:

Go update document using elastic search

问题

我正在使用go-elasticsearch作为Elasticsearch客户端。

我尝试使用这里的代码来更新文档:elastic/go-elasticsearch/api.update.go

然而,使用GitHub上相同的代码时,我遇到了以下错误:

[UpdateRequest] unknown field [Title]

到目前为止,我只有一个文档,它的结构如下所示:

{
	"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
				}
			}
		]
	}
}

我的Go函数如下:

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
}

我的实体如下:

type Post struct {
	Title   string
	Done    bool
	Created time.Time
	Updated *time.Time
}

此外,这是唯一一个不起作用的函数,其他函数如AddDocumentRemoveDocumentGetDocuments都按预期工作。

英文:

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

{
	&quot;took&quot;: 3,
	&quot;timed_out&quot;: false,
	&quot;_shards&quot;: {
		&quot;total&quot;: 4,
		&quot;successful&quot;: 4,
		&quot;skipped&quot;: 0,
		&quot;failed&quot;: 0
	},
	&quot;hits&quot;: {
		&quot;total&quot;: {
			&quot;value&quot;: 1,
			&quot;relation&quot;: &quot;eq&quot;
		},
		&quot;max_score&quot;: 1.0,
		&quot;hits&quot;: [
			{
				&quot;_index&quot;: &quot;posts&quot;,
				&quot;_type&quot;: &quot;_doc&quot;,
				&quot;_id&quot;: &quot;fc87941f-dc82-4fdb-9e04-460830e5f3ab&quot;,
				&quot;_score&quot;: 1.0,
				&quot;_source&quot;: {
					&quot;Title&quot;: &quot;one two three2&quot;,
					&quot;Done&quot;: false,
					&quot;Created&quot;: &quot;2022-02-09T11:51:59.027356+01:00&quot;,
					&quot;Updated&quot;: null
				}
			}
		]
	}
}

My go function:

func (postRepository) Update(id uuid.UUID, input inputs.Post) error {
	channel := make(chan error)
	go func() {
		post := entities.Post{
			Title:   &quot;title updated&quot;,
		}

		body, err := json.Marshal(post)
		if err != nil {
			channel &lt;- 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 &lt;- err
		}
		defer response.Body.Close()

		if response.IsError() {
			var b map[string]interface{}
			e := json.NewDecoder(response.Body).Decode(&amp;b)
			if e != nil {
				fmt.Println(fmt.Errorf(&quot;error parsing the response body: %s&quot;, err))
			}
			fmt.Println(fmt.Errorf(&quot;reason: %s&quot;, b[&quot;error&quot;].(map[string]interface{})[&quot;reason&quot;].(string)))
			channel &lt;- fmt.Errorf(&quot;[%s] Error indexing document&quot;, response.Status())
		}

		channel &lt;- nil
	}()
	return &lt;-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.

答案1

得分: 4

在这里找到解决方案:在Golang中的一个简单的Elasticsearch CRUD示例

不要使用:

request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body:       strings.NewReader(string(body)),
}

而是使用:

request := esapi.UpdateRequest{
    Index:      index,
    DocumentID: id.String(),
    Body: bytes.NewReader([]byte(fmt.Sprintf(`{&quot;doc&quot;:%s}`, body))),
}
英文:

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(`{&quot;doc&quot;:%s}`, body))),
}

huangapple
  • 本文由 发表于 2022年2月9日 19:04:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/71048446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定