Skip to content

Latest commit

 

History

History
62 lines (48 loc) · 1.29 KB

File metadata and controls

62 lines (48 loc) · 1.29 KB
endpoint get
lang php
es_version 9.3
client elasticsearch/elasticsearch==9.3.0

Elasticsearch 9.3 get endpoint (PHP example)

Use $client->get() to retrieve a document by its ID.

$response = $client->get(['index' => 'products', 'id' => 'prod-1']);

$doc = $response['_source'];
echo "{$doc['name']}\${$doc['price']}\n";

The response includes metadata (_index, _id, _version, _seq_no, _primary_term) alongside the _source document body.

Selecting fields

Use _source_includes or _source_excludes to return only the fields you need:

$response = $client->get([
    'index' => 'products',
    'id' => 'prod-1',
    '_source_includes' => ['name', 'price'],
]);

To fetch metadata without the source body, disable it entirely:

$response = $client->get([
    'index' => 'products',
    'id' => 'prod-1',
    '_source' => false,
]);

Handling missing documents

A ClientResponseException with status 404 is thrown when the document does not exist:

use Elastic\Elasticsearch\Exception\ClientResponseException;

try {
    $client->get(['index' => 'products', 'id' => 'prod-999']);
} catch (ClientResponseException $e) {
    if ($e->getCode() === 404) {
        echo "Document not found\n";
    } else {
        throw $e;
    }
}