0

I have a kuzzle document with a json like this:

j00:
{ '1': 'dsds',
  '2': 'rer',
  '5': 'yytyh hgvhg',
  '8': 'koo kllkl vv'
}

currently i'am doing this to update a key :

kuzzle_doc = await get_kuzzle_doc(i,c,d);

current_value = kuzzle_doc._source.j00[key_to_modify];
new_value = modify(current_value);

kuzzle_doc._source.j00[key_to_modify] = new_value;


try {
        const response = await kuzzle.document.update(
            i,
            c,
            d,
            {
            j00: kuzzle_doc._source.j00
            }
        );
        console.log('response',response);
} catch (error) {
        console.error("await kuzzle.document.update ....", error);
}
  1. Is this the correct way to update the json ?
  2. what about a nested json ? like :
    { 
     'a': 'dsds',
     'b': 'rer',
     'c': 'yytyh hgvhg',
     'd': 'koo kllkl vv'
     'e': {}
    }
    

What's the efficient way to update a key in the nested json ?

ibstelix
  • 103
  • 7

1 Answers1

0

To update one attribute from a document you can modify the attribute of your document and then send the whole document:

const myDoc = {
  foo: 'bar',
  baz: {
    will: 'smith'
  }
};

myDoc.foo = 'newValue';
myDoc.baz.will = 'anderson';

kuzzle.document.update(
  'index',
  'collection',
  'docId',
  myDoc
);
Jeno
  • 128
  • 6
  • Thanks you @Kévin , that's the way i 'am doing it i was worrying about the amount of data to first get the doc (need to always update the latest version), update it then send it back. How to block any update before i finish updating ? – ibstelix Apr 09 '21 at 13:58
  • 1
    ES is handling the versioning of a document, if someone tries to update a document which on a version higher than what he has then he will receive an error. You can use the `retryOnConflict` option which will retry n times to update the document. See https://docs.kuzzle.io/sdk/js/7/controllers/document/update/ – Jeno Apr 09 '21 at 14:04
  • Thank you very much ! – ibstelix Apr 09 '21 at 14:07
  • The documentation does not give the type of error in case of confilct (in case we want to catch it) – ibstelix Apr 09 '21 at 14:11
  • 1
    it's actually a services.storage.unexpected_error https://docs.kuzzle.io/core/2/api/errors/error-codes/services/ of type ExternalServiceError – Jeno Apr 09 '21 at 14:23
  • After many test i noticed, from your example if i do delete myDoc.baz.will; ``` console.log(myDoc) ``` shows "will" is deleted but after ``` kuzzle.document.update( 'index', 'collection', 'docId', myDoc ); ``` i find myDoc is not updated. Key deletion is not updated to kuzzle on field update can be updated to kuzzle; is that true ? – ibstelix Apr 09 '21 at 21:47
  • 1
    Hi, the method `kuzzle.document.update` only update the modified fields (it's not required to send the whole document, just the fields you need to update), you'll need to use `kuzzle.document.replace` to apply fields deletion (it's required to send the whole document) – E.Berthier Apr 13 '21 at 16:18