Skip to content

Latest commit

 

History

History
62 lines (51 loc) · 1.43 KB

File metadata and controls

62 lines (51 loc) · 1.43 KB
endpoint create
lang php
es_version 9.3
client elasticsearch/elasticsearch==9.3.0

Elasticsearch 9.3 create endpoint (PHP example)

Use $client->create() to index a document only if it does not already exist. This guarantees no accidental overwrites.

$response = $client->create([
    'index' => 'products',
    'id' => 'prod-1',
    'body' => [
        'name' => 'Espresso Machine Pro',
        'brand' => 'BrewMaster',
        'price' => 899.99,
        'category' => 'appliances',
        'in_stock' => true,
        'rating' => 4.7,
    ],
]);
echo "{$response['result']} document {$response['_id']}\n";

Unlike index, this will never replace an existing document.

Handling conflicts

If a document with the same id already exists, an exception with status 409 is thrown:

use Elastic\Elasticsearch\Exception\ClientResponseException;

try {
    $client->create(['index' => 'products', 'id' => 'prod-1', 'body' => ['name' => 'Duplicate']]);
} catch (ClientResponseException $e) {
    if ($e->getCode() === 409) {
        echo "Document prod-1 already exists\n";
    } else {
        throw $e;
    }
}

Auto-generated IDs

Omit the id parameter and use op_type to let Elasticsearch assign a unique ID:

$response = $client->index([
    'index' => 'products',
    'body' => ['name' => 'New Product', 'price' => 49.99],
    'op_type' => 'create',
]);
echo "Created with ID: {$response['_id']}\n";