Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DOCS] Restructures repo readme #1339

Merged
merged 2 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
268 changes: 15 additions & 253 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,9 @@ This is the official PHP client for

## Contents

- [Getting started](#getting-started-)
- [Configuration](#configuration)
- [Use Elastic Cloud](#use-elastic-cloud)
- [Installation](#installation)
- [Connecting](#connecting)
- [Usage](#usage)
- [Index a document](#index-a-document)
- [Search a document](#search-a-document)
- [Delete a document](#delete-a-document)
- [Versioning](#versioning)
- [Backward Incompatible Changes](#backward-incompatible-changes-boom)
- [Mock the Elasticsearch client](#mock-the-elasticsearch-client)
Expand All @@ -26,165 +22,15 @@ This is the official PHP client for

***

## Getting started 🐣
## Installation

Using this client assumes that you have an
[Elasticsearch](https://www.elastic.co/elasticsearch/) server installed and
running.
Refer to the [Installation section](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_installation)
of the getting started documentation.

You can install the client in your PHP project using
[composer](https://getcomposer.org/):
## Connecting

```bash
composer require elasticsearch/elasticsearch
```

After the installation you can connect to Elasticsearch using the
`ClientBuilder` class. For instance, if your Elasticsearch is running on
`localhost:9200` you can use the following code:

```php

use Elastic\Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();

// Info API
$response = $client->info();

echo $response['version']['number']; // 8.0.0
```

The `$response` is an object of `Elastic\Elasticsearch\Response\Elasticsearch`
class that implements `ElasticsearchInterface`, PSR-7
[ResponseInterface](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface)
and [ArrayAccess](https://www.php.net/manual/en/class.arrayaccess.php).

This means the `$response` is a [PSR-7](https://www.php-fig.org/psr/psr-7/)
object:

```php
echo $response->getStatusCode(); // 200
echo (string) $response->getBody(); // Response body in JSON
```

and also an "array", meaning you can access the response body as an
associative array, as follows:


```php
echo $response['version']['number']; // 8.0.0

var_dump($response->asArray()); // response body content as array
```

Moreover, you can access the response body as object, string or bool:

```php
echo $response->version->number; // 8.0.0

var_dump($response->asObject()); // response body content as object
var_dump($response->asString()); // response body as string (JSON)
var_dump($response->asBool()); // true if HTTP response code between 200 and 300
```

## Configuration

Elasticsearch 8.0 offers
[security by default](https://www.elastic.co/blog/introducing-simplified-elastic-stack-security),
that means it uses [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security)
for protect the communication between client and server.

In order to configure `elasticsearch-php` for connecting to Elasticsearch 8.0 we
need to have the certificate authority file (CA).

You can install Elasticsearch in different ways, for instance using
[Docker](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html)
you need to execute the followind command:

```bash
docker pull docker.elastic.co/elasticsearch/elasticsearch:8.0.1
```
Once you have the docker image installed, you can execute Elasticsearch, for
instance using a single-node cluster configuration, as follows:

```bash
docker network create elastic
docker run --name es01 --net elastic -p 9200:9200 -p 9300:9300 -it docker.elastic.co/elasticsearch/elasticsearch:8.0.1
```

This command creates an `elastic` Docker network and start Elasticsearch
using the port `9200` (default).

When you run the docker image a password is generated for the `elastic` user
and it's printed to the terminal (you might need to scroll back a bit in the
terminal to view it). You have to copy it since we will need to connect to
Elasticsearch.

Now that Elasticsearch is running we can get the `http_ca.crt` file certificate.
We need to copy it from the docker instance, using the following command:

```bash
docker cp es01:/usr/share/elasticsearch/config/certs/http_ca.crt .
```

Once we have the `http_ca.crt` certificate and the `password`, copied during the
start of Elasticsearch, we can use it to connect with `elasticsearch-php` as
follows:

```php
$client = ClientBuilder::create()
->setHosts(['https://localhost:9200'])
->setBasicAuthentication('elastic', 'password copied during Elasticsearch start')
->setCABundle('path/to/http_ca.crt')
->build();
```

For more information about the Docker configuration of Elasticsearch you can
read the official documentation
[here](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html).

### Use Elastic Cloud

You can use [Elastic Cloud](https://www.elastic.co/cloud/) as server with
`elasticsearch-php`. Elastic Cloud is the PaaS solution offered by
[Elastic](https://www.elastic.co).

For connecting to Elastic Cloud you just need the `Cloud ID` and the `API key`.

You can get the `Cloud ID` from the `My deployment` page of your dashboard (see
the red rectangle reported in the screenshot).

![Cloud ID](docs/images/cloud_id.png)

You can generate an `API key` in the `Management` page under the section
`Security`.

![Security](docs/images/create_api_key.png)

When you click on `Create API key` button you can choose a name and set the
other options (for example, restrict privileges, expire after time, and so on).

![Choose an API name](docs/images/api_key_name.png)

After this step you will get the `API key`in the API keys page.

![API key](docs/images/cloud_api_key.png)

**IMPORTANT**: you need to copy and store the `API key`in a secure place, since
you will not be able to view it again in Elastic Cloud.

Once you have collected the `Cloud ID` and the `API key`, you can use
`elasticsearch-php` to connect to your Elastic Cloud instance, as follows:

```php
$client = ClientBuilder::create()
->setElasticCloudId('insert here the Cloud ID')
->setApiKey('insert here the API key')
->build();
```
Refer to the [Connecting section](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_connecting)
of the getting started documentation.

## Usage

Expand All @@ -196,97 +42,13 @@ of Elasticsearch APIs.
Here we reported the basic operation that you can perform with the client:
index, search and delete.

### Index a document

You can store (index) a JSON document in Elasticsearch using the following code:

```php
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\ServerResponseException;

$params = [
'index' => 'my_index',
'body' => [ 'testField' => 'abc']
];

try {
$response = $client->index($params);
} catch (ClientResponseException $e) {
// manage the 4xx error
} catch (ServerResponseException $e) {
// manage the 5xx error
} catch (Exception $e) {
// eg. network error like NoNodeAvailableException
}

print_r($response->asArray()); // response body content as array
```

Elasticsearch stores the `{"testField":"abc"}` JSON document in the `my_index`
index. The `ID` of the document is created automatically by Elasticsearch and
stored in `$response['_id']` field value. If you want to specify an `ID` for the
document you need to store it in `$params['id']`.

You can manage errors using `ClientResponseException` and
`ServerResponseException`. The PSR-7 response is available using
`$e->getResponse()` and the HTTP status code is available using `$e->getCode()`.

### Search a document

Elasticsearch provides many different way to search documents. The simplest
search that you can perform is a
[match query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html),
as follows:

```php
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$response = $client->search($params);

printf("Total docs: %d\n", $response['hits']['total']['value']);
printf("Max score : %.4f\n", $response['hits']['max_score']);
printf("Took : %d ms\n", $response['took']);

print_r($response['hits']['hits']); // documents
```

Using Elasticsearch you can perform different query search, for more information
we suggest toread the official documention reported
[here](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-your-data.html).

### Delete a document

You can delete a document specifing the `index` name and the `ID` of the
document, as follows:

```php
use Elastic\Elasticsearch\Exception\ClientResponseException;

try {
$response = $client->delete([
'index' => 'my_index',
'id' => 'my_id'
]);
} catch (ClientResponseException $e) {
if ($e->getCode() === 404) {
// the document does not exist
}
}
if ($response['acknowledge'] === 1) {
// the document has been delete
}
```

For more information about the Elasticsearch REST API you can read the official
documentation [here](https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html).
* [Creating an index](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_creating_an_index)
* [Indexing a document](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_indexing_documents)
* [Getting documents](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_getting_documents)
* [Searching documents](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_searching_documents)
* [Updating documents](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_updating_documents)
* [Deleting documents](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_deleting_documents)
* [Deleting an index](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html#_deleting_an_index)

### Versioning

Expand Down
1 change: 0 additions & 1 deletion docs/getting-started.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ operations with it.
[discrete]
=== Requirements

* TO DO
* http://getcomposer.org[composer]

If you don't have composer you can install it by running the following commands:
Expand Down
Loading