2016-07-31 36 views
1

我只是試圖創建或替換文檔,但API文檔不清楚如何執行此操作。如何在Elasticsearch中創建或替換文檔?

upsert示例顯示了一個文件與一counter價值1創建:

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '777', 
    body: { 
     script: 'ctx._source.counter += 1', 
     upsert: { 
      counter: 1 
     } 
    } 
}, function(error, response) { 
    // ... 
}) 

我不需要增量腳本,所以我儘量只通過自身發送UPSERT,但我得到一個400 Validation Failed: 1: script or doc is missing

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      itworks: true, 
      ok: "oh yeah" 
     } 
    } 
}) 

好吧,讓我們嘗試一些愚蠢的,包括DOC兩次;一旦下doc,如果upsert下有一個,而一旦這大概會取代現有的文件,該文件將被用於否則創建一個新文件:

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      itworks: true, 
      ok: "oh yeah" 
     }, 
     doc: { 
      itworks: true, 
      ok: "oh yeah" 
     } 
    } 
}) 

也就是說實際工作,201創建。 200確定,當我重複一遍用不同的一個替換文檔:

client.update({ 
    index: "testindex", 
    type: "testType", 
    id: 1234, 
    body: { 
     upsert: { 
      whatever: "man" 
     }, 
     doc: { 
      whatever: "man" 
     } 
    } 
}) 

但是,當我檢查了DOC(client.get({index: "testindex", type: "testType", id: 1234})),我看到的不是替換原有文件,新的文檔與它合併。

如何用標準的Node客戶端替換Elasticsearch中的文檔? HTTP API使它看起來so simple,但我已經嘗試了一些在Node客戶端中的排列而沒有成功。有沒有替換命令?我必須刪除然後創建嗎?

回答

3

在Elasticsearch中,要替換文檔,您只需索引具有相同ID的文檔並自動替換它。

如果您想要更新文檔,您可以執行腳本更新,部分更新或兩者。

執行部分文檔更新時,您只需

部分文檔更新:

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '1', 
    body: { 
    // put the partial document under the `doc` key 
    doc: { 
     title: 'Updated' 
    } 
    } 
}, function (error, response) { 
    // ... 
}) 

腳本更新:在Elasticsearch

client.update({ 
    index: 'myindex', 
    type: 'mytype', 
    id: '1', 
    body: { 
    script: 'ctx._source.tags += tag', 
    params: { tag: 'some new tag' } 
    } 
}, function (error, response) { 
    // ... 
}); 

更多信息JS documentation

+0

具有相同ID的'create'調用返回409衝突:文檔存在,或者版本衝突,如果包含與現有版本不匹配的版本。 –

+2

嘗試'索引'而不是'創建' –

+0

就是這樣!我從來不會猜到這個詞。我在考慮如何在RDBMS中使用它們的索引,它們大多隻是一種優化。 –

1

這是一個我總是使用索引而不是創建的原因:

client.index({ 
    "index": 'index-name', 
    "type": 'mapping type', 
    "id": 'id you want to create/replace', 
    'body': JSON.stringify(obj) 
}, function (err, resp) { 
    if (err) { 
     console.error(err['message']) 
    } 
    else { 
     console.log(resp); 
     return resp 
    } 
});