What is the best way to push/add new elements into a nested array of objects?

I have a candidate Index where documents are structured like so :

{
  "_index" : "candidates",
  "_type" : "_doc",
  "_id" : "a23OcncBXBMGOH6pwXge",
  "_version" : 1,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "id" : "413",
    "firstname" : "Tania",
    "lastname" : "Stroman",
    "email" : "Berlin@yahoo.com",
    "zip" : "60306",
    "city" : "frankfurt",
    "birthday" : "1978-11-22",
    "tags" : [
      "php",
      "munich"
    ],
    "location" : {
      "lat" : 50.11601257324219,
      "lon" : 8.669955253601074
    }
  }
}

Once a candidate uploads their file, I add a field called 'file' to the elastic document for the first one and push the subsequent uploads to the array with the following code :

public function attachCandidateFile($file)
    {
        $client = ClientBuilder::create()->build();

        $params = [
            'index' => 'candidates',
            'id'    => $file['candidate_id']
        ];

        $candidate = $client->get($params);

        if (!is_array($candidate['_source']['file'])) {
            $candidate['_source']['file'] = [];
        } 
        array_push($candidate['_source']['file'], $file);

        $params = [
            'index' => 'candidates',
            'type'  => '_doc',
            'id'    =>  $file['candidate_id'],   
            'body'  => [
                'doc' => [
                    'file' => $candidate['_source']['file']
                ]
            ]                
           
        ];
        $response = $client->update($params);
        echo '<pre>', print_r($response, true) ,'</pre>';
    } 

Is there a way to update the candidate directly with the new object without needing the fetch $candidate['_source']['file'] so as to avoid overriding it ?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.