Commit 956ecc5d authored by work's avatar work

es-php

parent edae5b99
......@@ -25,7 +25,8 @@
"voku/simple_html_dom": "^4.5",
"yiisoft/yii2-elasticsearch": "~2.0.0",
"workerman/workerman": "^3.5",
"aliyuncs/oss-sdk-php": "^2.3"
"aliyuncs/oss-sdk-php": "^2.3",
"elasticsearch/elasticsearch": "^7.4"
},
"require-dev": {
"yiisoft/yii2-debug": "~2.0.0",
......
......@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "b4597476a86922ec3d1494465523a1e8",
"content-hash": "c74650379de435f8618ee861ec785d20",
"packages": [
{
"name": "aliyuncs/oss-sdk-php",
......@@ -353,6 +353,69 @@
"time": "2018-04-10T10:11:19+00:00"
},
{
"name": "elasticsearch/elasticsearch",
"version": "v7.4.1",
"source": {
"type": "git",
"url": "https://github.com/elastic/elasticsearch-php.git",
"reference": "39eb8c046184e9a305288509fe48f02a2307de90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/39eb8c046184e9a305288509fe48f02a2307de90",
"reference": "39eb8c046184e9a305288509fe48f02a2307de90",
"shasum": ""
},
"require": {
"ext-json": ">=1.3.7",
"guzzlehttp/ringphp": "~1.0",
"php": "^7.1",
"psr/log": "~1.0"
},
"require-dev": {
"cpliakas/git-wrapper": "~2.0",
"doctrine/inflector": "^1.3",
"mockery/mockery": "^1.2",
"phpstan/phpstan-shim": "^0.11",
"phpunit/phpunit": "^7.5",
"squizlabs/php_codesniffer": "^3.4",
"symfony/finder": "~4.0",
"symfony/yaml": "~4.0"
},
"suggest": {
"ext-curl": "*",
"monolog/monolog": "Allows for client-level logging and tracing"
},
"type": "library",
"autoload": {
"files": [
"src/autoload.php"
],
"psr-4": {
"Elasticsearch\\": "src/Elasticsearch/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Zachary Tong"
},
{
"name": "Enrico Zimuel"
}
],
"description": "PHP Client for Elasticsearch",
"keywords": [
"client",
"elasticsearch",
"search"
],
"time": "2019-11-26T11:59:39+00:00"
},
{
"name": "ezyang/htmlpurifier",
"version": "v4.10.0",
"source": {
......@@ -400,6 +463,107 @@
"time": "2018-02-23T01:58:20+00:00"
},
{
"name": "guzzlehttp/ringphp",
"version": "1.1.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/RingPHP.git",
"reference": "5e2a174052995663dd68e6b5ad838afd47dd615b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/RingPHP/zipball/5e2a174052995663dd68e6b5ad838afd47dd615b",
"reference": "5e2a174052995663dd68e6b5ad838afd47dd615b",
"shasum": ""
},
"require": {
"guzzlehttp/streams": "~3.0",
"php": ">=5.4.0",
"react/promise": "~2.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "~4.0"
},
"suggest": {
"ext-curl": "Guzzle will use specific adapters if cURL is present"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Ring\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.",
"time": "2018-07-31T13:22:33+00:00"
},
{
"name": "guzzlehttp/streams",
"version": "3.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/streams.git",
"reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/streams/zipball/47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5",
"reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Stream\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Provides a simple abstraction over streams of data",
"homepage": "http://guzzlephp.org/",
"keywords": [
"Guzzle",
"stream"
],
"time": "2014-10-12T19:18:40+00:00"
},
{
"name": "kartik-v/bootstrap-fileinput",
"version": "v4.4.8",
"source": {
......@@ -1795,6 +1959,99 @@
"time": "2019-02-25T10:56:34+00:00"
},
{
"name": "psr/log",
"version": "1.1.2",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
],
"time": "2019-11-01T11:05:21+00:00"
},
{
"name": "react/promise",
"version": "v2.7.1",
"source": {
"type": "git",
"url": "https://github.com/reactphp/promise.git",
"reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/reactphp/promise/zipball/31ffa96f8d2ed0341a57848cbb84d88b89dd664d",
"reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8"
},
"type": "library",
"autoload": {
"psr-4": {
"React\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jan Sorgalla",
"email": "jsorgalla@gmail.com"
}
],
"description": "A lightweight implementation of CommonJS Promises/A for PHP",
"keywords": [
"promise",
"promises"
],
"time": "2019-01-07T21:25:54+00:00"
},
{
"name": "swiftmailer/swiftmailer",
"version": "v6.1.2",
"source": {
......
......@@ -10,7 +10,9 @@ return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'ad155f8f1cf0d418fe49e248db8c661b' => $vendorDir . '/react/promise/src/functions_include.php',
'180092cfc969a12e06f2132a203a3184' => $vendorDir . '/codeception/verify/src/Codeception/function.php',
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php',
'8592c7b0947d8a0965a9e8c3d16f9c24' => $vendorDir . '/elasticsearch/elasticsearch/src/autoload.php',
);
......@@ -67,10 +67,15 @@ return array(
'Symfony\\Component\\CssSelector\\' => array($vendorDir . '/symfony/css-selector'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Symfony\\Component\\BrowserKit\\' => array($vendorDir . '/symfony/browser-kit'),
'React\\Promise\\' => array($vendorDir . '/react/promise/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'OSS\\' => array($vendorDir . '/aliyuncs/oss-sdk-php/src/OSS'),
'GuzzleHttp\\Stream\\' => array($vendorDir . '/guzzlehttp/streams/src'),
'GuzzleHttp\\Ring\\' => array($vendorDir . '/guzzlehttp/ringphp/src'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
'Elasticsearch\\' => array($vendorDir . '/elasticsearch/elasticsearch/src/Elasticsearch'),
'Egulias\\EmailValidator\\' => array($vendorDir . '/egulias/email-validator/EmailValidator'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
......
......@@ -11,9 +11,11 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php',
'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php',
'180092cfc969a12e06f2132a203a3184' => __DIR__ . '/..' . '/codeception/verify/src/Codeception/function.php',
'6124b4c8570aa390c21fafd04a26c69f' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'2c102faa651ef8ea5874edb585946bce' => __DIR__ . '/..' . '/swiftmailer/swiftmailer/lib/swift_required.php',
'8592c7b0947d8a0965a9e8c3d16f9c24' => __DIR__ . '/..' . '/elasticsearch/elasticsearch/src/autoload.php',
);
public static $prefixLengthsPsr4 = array (
......@@ -105,8 +107,13 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
'Symfony\\Component\\Console\\' => 26,
'Symfony\\Component\\BrowserKit\\' => 29,
),
'R' =>
array (
'React\\Promise\\' => 14,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
),
'O' =>
......@@ -115,6 +122,8 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
),
'G' =>
array (
'GuzzleHttp\\Stream\\' => 18,
'GuzzleHttp\\Ring\\' => 16,
'GuzzleHttp\\Psr7\\' => 16,
),
'F' =>
......@@ -123,6 +132,7 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
),
'E' =>
array (
'Elasticsearch\\' => 14,
'Egulias\\EmailValidator\\' => 23,
),
'D' =>
......@@ -385,6 +395,14 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
array (
0 => __DIR__ . '/..' . '/symfony/browser-kit',
),
'React\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/react/promise/src',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
......@@ -393,6 +411,14 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
array (
0 => __DIR__ . '/..' . '/aliyuncs/oss-sdk-php/src/OSS',
),
'GuzzleHttp\\Stream\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/streams/src',
),
'GuzzleHttp\\Ring\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/ringphp/src',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
......@@ -401,6 +427,10 @@ class ComposerStaticInit33057934f3e7eaaa1ce2d53797277936
array (
0 => __DIR__ . '/..' . '/fzaninotto/faker/src/Faker',
),
'Elasticsearch\\' =>
array (
0 => __DIR__ . '/..' . '/elasticsearch/elasticsearch/src/Elasticsearch',
),
'Egulias\\EmailValidator\\' =>
array (
0 => __DIR__ . '/..' . '/egulias/email-validator/EmailValidator',
......
......@@ -712,6 +712,71 @@
]
},
{
"name": "elasticsearch/elasticsearch",
"version": "v7.4.1",
"version_normalized": "7.4.1.0",
"source": {
"type": "git",
"url": "https://github.com/elastic/elasticsearch-php.git",
"reference": "39eb8c046184e9a305288509fe48f02a2307de90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/39eb8c046184e9a305288509fe48f02a2307de90",
"reference": "39eb8c046184e9a305288509fe48f02a2307de90",
"shasum": ""
},
"require": {
"ext-json": ">=1.3.7",
"guzzlehttp/ringphp": "~1.0",
"php": "^7.1",
"psr/log": "~1.0"
},
"require-dev": {
"cpliakas/git-wrapper": "~2.0",
"doctrine/inflector": "^1.3",
"mockery/mockery": "^1.2",
"phpstan/phpstan-shim": "^0.11",
"phpunit/phpunit": "^7.5",
"squizlabs/php_codesniffer": "^3.4",
"symfony/finder": "~4.0",
"symfony/yaml": "~4.0"
},
"suggest": {
"ext-curl": "*",
"monolog/monolog": "Allows for client-level logging and tracing"
},
"time": "2019-11-26T11:59:39+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"src/autoload.php"
],
"psr-4": {
"Elasticsearch\\": "src/Elasticsearch/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Zachary Tong"
},
{
"name": "Enrico Zimuel"
}
],
"description": "PHP Client for Elasticsearch",
"keywords": [
"client",
"elasticsearch",
"search"
]
},
{
"name": "ezyang/htmlpurifier",
"version": "v4.10.0",
"version_normalized": "4.10.0.0",
......@@ -880,6 +945,111 @@
]
},
{
"name": "guzzlehttp/ringphp",
"version": "1.1.1",
"version_normalized": "1.1.1.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/RingPHP.git",
"reference": "5e2a174052995663dd68e6b5ad838afd47dd615b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/RingPHP/zipball/5e2a174052995663dd68e6b5ad838afd47dd615b",
"reference": "5e2a174052995663dd68e6b5ad838afd47dd615b",
"shasum": ""
},
"require": {
"guzzlehttp/streams": "~3.0",
"php": ">=5.4.0",
"react/promise": "~2.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "~4.0"
},
"suggest": {
"ext-curl": "Guzzle will use specific adapters if cURL is present"
},
"time": "2018-07-31T13:22:33+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"GuzzleHttp\\Ring\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function."
},
{
"name": "guzzlehttp/streams",
"version": "3.0.0",
"version_normalized": "3.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/streams.git",
"reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/streams/zipball/47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5",
"reference": "47aaa48e27dae43d39fc1cea0ccf0d84ac1a2ba5",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"time": "2014-10-12T19:18:40+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"GuzzleHttp\\Stream\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Provides a simple abstraction over streams of data",
"homepage": "http://guzzlephp.org/",
"keywords": [
"Guzzle",
"stream"
]
},
{
"name": "kartik-v/bootstrap-fileinput",
"version": "v4.4.8",
"version_normalized": "4.4.8.0",
......@@ -3200,6 +3370,103 @@
]
},
{
"name": "psr/log",
"version": "1.1.2",
"version_normalized": "1.1.2.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2019-11-01T11:05:21+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
]
},
{
"name": "react/promise",
"version": "v2.7.1",
"version_normalized": "2.7.1.0",
"source": {
"type": "git",
"url": "https://github.com/reactphp/promise.git",
"reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/reactphp/promise/zipball/31ffa96f8d2ed0341a57848cbb84d88b89dd664d",
"reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8"
},
"time": "2019-01-07T21:25:54+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"React\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jan Sorgalla",
"email": "jsorgalla@gmail.com"
}
],
"description": "A lightweight implementation of CommonJS Promises/A for PHP",
"keywords": [
"promise",
"promises"
]
},
{
"name": "sebastian/code-unit-reverse-lookup",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
......
# Files to exclude when creating archive
/tests export-ignore
/.github export-ignore
/.gitmodules export-ignore
/.gitignore export-ignore
/.php_cs export-ignore
/.travis.yml export-ignore
/.phpstan-src.neon export-ignore
/.phpstan-src-71.neon export-ignore
/.phpstan-tests.neon export-ignore
/phpunit-integration.xml export-ignore
/phpunit.xml export-ignore
/ruleset.xml export-ignore
/travis export-ignore
/util export-ignore
# 7.4
- Using a deprecated parameter is notified triggering a [E_USER_DEPRECATED](https://www.php.net/manual/en/errorfunc.constants.php)
error (e.g. using the `type` parameter will generate a `Specifying types in urls has been deprecated`
deprecation message).
- When `delete` with an empty `id` an `Elasticsearch\Common\Exceptions\RuntimeException\Missing404Exception`
exception is thrown. Previously it was a `Elasticsearch\Common\Exceptions\RuntimeException\InvalidArgumentException`.
# 7.0
- Requirement of PHP 7.1 instead of 7.0 that is not supported since 1 Jan 2019.
See [PHP supported version](https://www.php.net/supported-versions.php) for
more information.
- Elasticsearch 7.0 deprecated APIs that accept types, introduced new typeless
APIs, and removed support for the _default_ mapping. Read [this](https://www.elastic.co/blog/moving-from-types-to-typeless-apis-in-elasticsearch-7-0)
blog post for more information.
- Added type hints and return type declarations where possible
[#897](https://github.com/elastic/elasticsearch-php/pull/897)
# 6.7
- `{type}` part in `indices.put_mapping` API is not required anymore, see new specification [here](https://github.com/elastic/elasticsearch/blob/v6.7.0/rest-api-spec/src/main/resources/rest-api-spec/api/indices.put_mapping.json)
# 6.0
- [Search Templates]: PutTemplate endpoint has been removed (see [Elasticsearch Breaking Changes](https://www.elastic.co/guide/en/elasticsearch/reference/current/breaking_60_scripting_changes.html#_stored_search_template_apis_removed)),
use PutScript instead.
- [#674](https://github.com/elastic/elasticsearch-php/pull/674) `ClientBuilder::defaultLogger()` method was removed. It is recommended to [create the logger object manually](https://github.com/elastic/elasticsearch-php/blob/master/docs/configuration.asciidoc#enabling-the-logger).
This diff is collapsed.
This diff is collapsed.
Apache v2.0 Notice:
Copyright 2013-2014 Elasticsearch
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
LGPL v2.1 Notice:
Copyright (C) 2013-2014 Elasticsearch
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
\ No newline at end of file
This diff is collapsed.
{
"name": "elasticsearch/elasticsearch",
"description": "PHP Client for Elasticsearch",
"keywords": ["search","client", "elasticsearch"],
"type": "library",
"license": "Apache-2.0",
"authors": [
{
"name": "Zachary Tong"
},
{
"name": "Enrico Zimuel"
}
],
"require": {
"php": "^7.1",
"ext-json": ">=1.3.7",
"guzzlehttp/ringphp": "~1.0",
"psr/log": "~1.0"
},
"require-dev": {
"cpliakas/git-wrapper": "~2.0",
"doctrine/inflector": "^1.3",
"mockery/mockery": "^1.2",
"phpstan/phpstan-shim": "^0.11",
"phpunit/phpunit": "^7.5",
"squizlabs/php_codesniffer": "^3.4",
"symfony/finder": "~4.0",
"symfony/yaml": "~4.0"
},
"suggest": {
"ext-curl": "*",
"monolog/monolog": "Allows for client-level logging and tracing"
},
"autoload": {
"files": [
"src/autoload.php"
],
"psr-4": {
"Elasticsearch\\": "src/Elasticsearch/"
}
},
"autoload-dev": {
"psr-4": {
"Elasticsearch\\Tests\\": "tests/Elasticsearch/Tests/",
"Elasticsearch\\IntegrationTests\\": "tests/Elasticsearch/IntegrationTests/",
"Elasticsearch\\Util\\": "util/"
}
},
"config": {
"sort-packages": true
},
"scripts": {
"phpcs": [
"phpcs --standard=ruleset.xml --extensions=php --encoding=utf-8 --tab-width=4 -sp src",
"phpcs --standard=ruleset.xml --extensions=php --encoding=utf-8 --tab-width=4 -sp tests"
],
"phpstan7.1": [
"@php vendor/phpstan/phpstan-shim/phpstan.phar analyse -c phpstan-src-71.neon src --level 2 --no-progress"
],
"phpstan": [
"@php vendor/phpstan/phpstan-shim/phpstan.phar analyse -c phpstan-src.neon src --level 2 --no-progress"
]
}
}
[[breaking_changes]]
== Breaking changes from 6.x
### E_USER_DEPRECATED notice when using deprecated parameters
Starting from elasticsearch-php 7.4.0, we generate a PHP [E_USER_DEPRECATED](https://www.php.net/manual/en/errorfunc.constants.php)
notice every time you use a deprecated parameters for Elasticsearch.
We decided to add this notice to facilitate the code refactoring with the
new API specification of Elasticsearch (e.g. the usage of typeless APIs, see below).
### Moving from types to typeless APIs in Elasticsearch 7.0
Elasticsearch 7.0 deprecated APIs that accept types, introduced new typeless
APIs, and removed support for the _default_ mapping. Read [this](https://www.elastic.co/blog/moving-from-types-to-typeless-apis-in-elasticsearch-7-0)
blog post for more information.
### Type hint and return type
Added type hints and return type declarations in all the code base, where possible.
See PR [#897](https://github.com/elastic/elasticsearch-php/pull/897).
### PHP 7.1+ Requirement
We require using PHP 7.1+ for elasticsearch-php. PHP 7.0 is not supported since
1st Jan 2019. See [PHP supported version](https://www.php.net/supported-versions.php) for
more information.
[[Elasticsearch_ClientBuilder]]
=== Elasticsearch\ClientBuilder
Class ClientBuilder
*Methods*
The class defines the following methods:
* <<Elasticsearch_ClientBuildercreate_create,`create()`>>
* <<Elasticsearch_ClientBuildergetTransport_getTransport,`getTransport()`>>
* <<Elasticsearch_ClientBuildergetEndpoint_getEndpoint,`getEndpoint()`>>
* <<Elasticsearch_ClientBuildergetRegisteredNamespacesBuilders_getRegisteredNamespacesBuilders,`getRegisteredNamespacesBuilders()`>>
* <<Elasticsearch_ClientBuilderfromConfig_fromConfig,`fromConfig()`>>
* <<Elasticsearch_ClientBuilderdefaultHandler_defaultHandler,`defaultHandler()`>>
* <<Elasticsearch_ClientBuildermultiHandler_multiHandler,`multiHandler()`>>
* <<Elasticsearch_ClientBuildersingleHandler_singleHandler,`singleHandler()`>>
* <<Elasticsearch_ClientBuildersetConnectionFactory_setConnectionFactory,`setConnectionFactory()`>>
* <<Elasticsearch_ClientBuildersetConnectionPool_setConnectionPool,`setConnectionPool()`>>
* <<Elasticsearch_ClientBuildersetEndpoint_setEndpoint,`setEndpoint()`>>
* <<Elasticsearch_ClientBuilderregisterNamespace_registerNamespace,`registerNamespace()`>>
* <<Elasticsearch_ClientBuildersetTransport_setTransport,`setTransport()`>>
* <<Elasticsearch_ClientBuildersetHandler_setHandler,`setHandler()`>>
* <<Elasticsearch_ClientBuildersetLogger_setLogger,`setLogger()`>>
* <<Elasticsearch_ClientBuildersetTracer_setTracer,`setTracer()`>>
* <<Elasticsearch_ClientBuildersetSerializer_setSerializer,`setSerializer()`>>
* <<Elasticsearch_ClientBuildersetHosts_setHosts,`setHosts()`>>
* <<Elasticsearch_ClientBuildersetApiKey_setApiKey,`setApiKey()`>>
* <<Elasticsearch_ClientBuildersetBasicAuthentication_setBasicAuthentication,`setBasicAuthentication()`>>
* <<Elasticsearch_ClientBuildersetElasticCloudId_setElasticCloudId,`setElasticCloudId()`>>
* <<Elasticsearch_ClientBuildersetConnectionParams_setConnectionParams,`setConnectionParams()`>>
* <<Elasticsearch_ClientBuildersetRetries_setRetries,`setRetries()`>>
* <<Elasticsearch_ClientBuildersetSelector_setSelector,`setSelector()`>>
* <<Elasticsearch_ClientBuildersetSniffOnStart_setSniffOnStart,`setSniffOnStart()`>>
* <<Elasticsearch_ClientBuildersetSSLCert_setSSLCert,`setSSLCert()`>>
* <<Elasticsearch_ClientBuildersetSSLKey_setSSLKey,`setSSLKey()`>>
* <<Elasticsearch_ClientBuildersetSSLVerification_setSSLVerification,`setSSLVerification()`>>
* <<Elasticsearch_ClientBuilderbuild_build,`build()`>>
* <<Elasticsearch_ClientBuilderinstantiate_instantiate,`instantiate()`>>
[[Elasticsearch_ClientBuildercreate_create]]
.`create()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildergetTransport_getTransport]]
.`getTransport()`
****
[source,php]
----
/*
Can supply first parm to Client::__construct() when invoking manually or with dependency injection
*/
----
****
[[Elasticsearch_ClientBuildergetEndpoint_getEndpoint]]
.`getEndpoint()`
****
[source,php]
----
/*
Can supply second parm to Client::__construct() when invoking manually or with dependency injection
*/
----
****
[[Elasticsearch_ClientBuildergetRegisteredNamespacesBuilders_getRegisteredNamespacesBuilders]]
.`getRegisteredNamespacesBuilders()`
****
[source,php]
----
/*
Can supply third parm to Client::__construct() when invoking manually or with dependency injection
*/
----
****
[[Elasticsearch_ClientBuilderfromConfig_fromConfig]]
.`fromConfig()`
****
[source,php]
----
/*
Build a new client from the provided config. Hash keys
should correspond to the method name e.g. ['connectionPool']
corresponds to setConnectionPool().
*/
----
****
[[Elasticsearch_ClientBuilderdefaultHandler_defaultHandler]]
.`defaultHandler()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildermultiHandler_multiHandler]]
.`multiHandler()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersingleHandler_singleHandler]]
.`singleHandler()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetConnectionFactory_setConnectionFactory]]
.`setConnectionFactory()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetConnectionPool_setConnectionPool]]
.`setConnectionPool()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetEndpoint_setEndpoint]]
.`setEndpoint()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuilderregisterNamespace_registerNamespace]]
.`registerNamespace()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetTransport_setTransport]]
.`setTransport()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetHandler_setHandler]]
.`setHandler()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetLogger_setLogger]]
.`setLogger()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetTracer_setTracer]]
.`setTracer()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSerializer_setSerializer]]
.`setSerializer()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetHosts_setHosts]]
.`setHosts()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetApiKey_setApiKey]]
.`setApiKey()`
****
[source,php]
----
/*
Set the APIKey Pair, consiting of the API Id and the ApiKey of the Response from /_security/api_key
*/
----
****
[[Elasticsearch_ClientBuildersetBasicAuthentication_setBasicAuthentication]]
.`setBasicAuthentication()`
****
[source,php]
----
/*
Set the APIKey Pair, consiting of the API Id and the ApiKey of the Response from /_security/api_key
*/
----
****
[[Elasticsearch_ClientBuildersetElasticCloudId_setElasticCloudId]]
.`setElasticCloudId()`
****
[source,php]
----
/*
Set Elastic Cloud ID to connect to Elastic Cloud
*/
----
****
[[Elasticsearch_ClientBuildersetConnectionParams_setConnectionParams]]
.`setConnectionParams()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetRetries_setRetries]]
.`setRetries()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSelector_setSelector]]
.`setSelector()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSniffOnStart_setSniffOnStart]]
.`setSniffOnStart()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSSLCert_setSSLCert]]
.`setSSLCert()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSSLKey_setSSLKey]]
.`setSSLKey()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuildersetSSLVerification_setSSLVerification]]
.`setSSLVerification()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuilderbuild_build]]
.`build()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_ClientBuilderinstantiate_instantiate]]
.`instantiate()`
****
[source,php]
----
/*
*/
----
****
[[Elasticsearch_Namespaces_ClusterNamespace]]
=== Elasticsearch\Namespaces\ClusterNamespace
Class ClusterNamespace
Generated running $ php util/GenerateEndpoints.php 7.4.2
*Methods*
The class defines the following methods:
* <<Elasticsearch_Namespaces_ClusterNamespaceallocationExplain_allocationExplain,`allocationExplain()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacegetSettings_getSettings,`getSettings()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacehealth_health,`health()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacependingTasks_pendingTasks,`pendingTasks()`>>
* <<Elasticsearch_Namespaces_ClusterNamespaceputSettings_putSettings,`putSettings()`>>
* <<Elasticsearch_Namespaces_ClusterNamespaceremoteInfo_remoteInfo,`remoteInfo()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacereroute_reroute,`reroute()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacestate_state,`state()`>>
* <<Elasticsearch_Namespaces_ClusterNamespacestats_stats,`stats()`>>
[[Elasticsearch_Namespaces_ClusterNamespaceallocationExplain_allocationExplain]]
.`allocationExplain()`
****
[source,php]
----
/*
$params['include_yes_decisions'] = (boolean) Return 'YES' decisions in explanation (default: false)
$params['include_disk_info'] = (boolean) Return information about disk usage and shard sizes (default: false)
$params['body'] = (array) The index, shard, and primary flag to explain. Empty means 'explain the first unassigned shard'
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->allocationExplain($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacegetSettings_getSettings]]
.`getSettings()`
****
[source,php]
----
/*
$params['flat_settings'] = (boolean) Return settings in flat format (default: false)
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['include_defaults'] = (boolean) Whether to return all default clusters setting. (Default = false)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->getSettings($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacehealth_health]]
.`health()`
****
[source,php]
----
/*
$params['index'] = (list) Limit the information returned to a specific index
$params['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. (Options = open,closed,none,all) (Default = all)
$params['level'] = (enum) Specify the level of detail for returned information (Options = cluster,indices,shards) (Default = cluster)
$params['local'] = (boolean) Return local information, do not retrieve the state from master node (default: false)
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['wait_for_active_shards'] = (string) Wait until the specified number of shards is active
$params['wait_for_nodes'] = (string) Wait until the specified number of nodes is available
$params['wait_for_events'] = (enum) Wait until all currently queued events with the given priority are processed (Options = immediate,urgent,high,normal,low,languid)
$params['wait_for_no_relocating_shards'] = (boolean) Whether to wait until there are no relocating shards in the cluster
$params['wait_for_no_initializing_shards'] = (boolean) Whether to wait until there are no initializing shards in the cluster
$params['wait_for_status'] = (enum) Wait until cluster is in a specific state (Options = green,yellow,red)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->health($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacependingTasks_pendingTasks]]
.`pendingTasks()`
****
[source,php]
----
/*
$params['local'] = (boolean) Return local information, do not retrieve the state from master node (default: false)
$params['master_timeout'] = (time) Specify timeout for connection to master
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->pendingTasks($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespaceputSettings_putSettings]]
.`putSettings()`
****
[source,php]
----
/*
$params['flat_settings'] = (boolean) Return settings in flat format (default: false)
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['body'] = (array) The settings to be updated. Can be either `transient` or `persistent` (survives cluster restart). (Required)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->putSettings($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespaceremoteInfo_remoteInfo]]
.`remoteInfo()`
****
[source,php]
----
/*
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->remoteInfo($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacereroute_reroute]]
.`reroute()`
****
[source,php]
----
/*
$params['dry_run'] = (boolean) Simulate the operation only and return the resulting state
$params['explain'] = (boolean) Return an explanation of why the commands can or cannot be executed
$params['retry_failed'] = (boolean) Retries allocation of shards that are blocked due to too many subsequent allocation failures
$params['metric'] = (list) Limit the information returned to the specified metrics. Defaults to all but metadata (Options = _all,blocks,metadata,nodes,routing_table,master_node,version)
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['body'] = (array) The definition of `commands` to perform (`move`, `cancel`, `allocate`)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->reroute($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacestate_state]]
.`state()`
****
[source,php]
----
/*
$params['metric'] = (list) Limit the information returned to the specified metrics
$params['index'] = (list) A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
$params['local'] = (boolean) Return local information, do not retrieve the state from master node (default: false)
$params['master_timeout'] = (time) Specify timeout for connection to master
$params['flat_settings'] = (boolean) Return settings in flat format (default: false)
$params['wait_for_metadata_version'] = (number) Wait for the metadata version to be equal or greater than the specified metadata version
$params['wait_for_timeout'] = (time) The maximum time to wait for wait_for_metadata_version before timing out
$params['ignore_unavailable'] = (boolean) Whether specified concrete indices should be ignored when unavailable (missing or closed)
$params['allow_no_indices'] = (boolean) Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
$params['expand_wildcards'] = (enum) Whether to expand wildcard expression to concrete indices that are open, closed or both. (Options = open,closed,none,all) (Default = open)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->state($params);
----
****
[[Elasticsearch_Namespaces_ClusterNamespacestats_stats]]
.`stats()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['flat_settings'] = (boolean) Return settings in flat format (default: false)
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->cluster()->stats($params);
----
****
[[Elasticsearch_Namespaces_IngestNamespace]]
=== Elasticsearch\Namespaces\IngestNamespace
Class IngestNamespace
Generated running $ php util/GenerateEndpoints.php 7.4.2
*Methods*
The class defines the following methods:
* <<Elasticsearch_Namespaces_IngestNamespacedeletePipeline_deletePipeline,`deletePipeline()`>>
* <<Elasticsearch_Namespaces_IngestNamespacegetPipeline_getPipeline,`getPipeline()`>>
* <<Elasticsearch_Namespaces_IngestNamespaceprocessorGrok_processorGrok,`processorGrok()`>>
* <<Elasticsearch_Namespaces_IngestNamespaceputPipeline_putPipeline,`putPipeline()`>>
* <<Elasticsearch_Namespaces_IngestNamespacesimulate_simulate,`simulate()`>>
[[Elasticsearch_Namespaces_IngestNamespacedeletePipeline_deletePipeline]]
.`deletePipeline()`
****
[source,php]
----
/*
$params['id'] = (string) Pipeline ID
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->ingest()->deletePipeline($params);
----
****
[[Elasticsearch_Namespaces_IngestNamespacegetPipeline_getPipeline]]
.`getPipeline()`
****
[source,php]
----
/*
$params['id'] = (string) Comma separated list of pipeline ids. Wildcards supported
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->ingest()->getPipeline($params);
----
****
[[Elasticsearch_Namespaces_IngestNamespaceprocessorGrok_processorGrok]]
.`processorGrok()`
****
[source,php]
----
/*
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->ingest()->processorGrok($params);
----
****
[[Elasticsearch_Namespaces_IngestNamespaceputPipeline_putPipeline]]
.`putPipeline()`
****
[source,php]
----
/*
$params['id'] = (string) Pipeline ID
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['body'] = (array) The ingest definition (Required)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->ingest()->putPipeline($params);
----
****
[[Elasticsearch_Namespaces_IngestNamespacesimulate_simulate]]
.`simulate()`
****
[source,php]
----
/*
$params['id'] = (string) Pipeline ID
$params['verbose'] = (boolean) Verbose mode. Display data output for each processor in executed pipeline (Default = false)
$params['body'] = (array) The simulate definition (Required)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->ingest()->simulate($params);
----
****
[[Elasticsearch_Namespaces_NodesNamespace]]
=== Elasticsearch\Namespaces\NodesNamespace
Class NodesNamespace
Generated running $ php util/GenerateEndpoints.php 7.4.2
*Methods*
The class defines the following methods:
* <<Elasticsearch_Namespaces_NodesNamespacehotThreads_hotThreads,`hotThreads()`>>
* <<Elasticsearch_Namespaces_NodesNamespaceinfo_info,`info()`>>
* <<Elasticsearch_Namespaces_NodesNamespacereloadSecureSettings_reloadSecureSettings,`reloadSecureSettings()`>>
* <<Elasticsearch_Namespaces_NodesNamespacestats_stats,`stats()`>>
* <<Elasticsearch_Namespaces_NodesNamespaceusage_usage,`usage()`>>
[[Elasticsearch_Namespaces_NodesNamespacehotThreads_hotThreads]]
.`hotThreads()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['interval'] = (time) The interval for the second sampling of threads
$params['snapshots'] = (number) Number of samples of thread stacktrace (default: 10)
$params['threads'] = (number) Specify the number of threads to provide information for (default: 3)
$params['ignore_idle_threads'] = (boolean) Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true)
$params['type'] = (enum) The type to sample (default: cpu) (Options = cpu,wait,block)
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->nodes()->hotThreads($params);
----
****
[[Elasticsearch_Namespaces_NodesNamespaceinfo_info]]
.`info()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['metric'] = (list) A comma-separated list of metrics you wish returned. Leave empty to return all.
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->nodes()->info($params);
----
****
[[Elasticsearch_Namespaces_NodesNamespacereloadSecureSettings_reloadSecureSettings]]
.`reloadSecureSettings()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs to span the reload/reinit call. Should stay empty because reloading usually involves all cluster nodes.
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->nodes()->reloadSecureSettings($params);
----
****
[[Elasticsearch_Namespaces_NodesNamespacestats_stats]]
.`stats()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['metric'] = (list) Limit the information returned to the specified metrics
$params['index_metric'] = (list) Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified.
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->nodes()->stats($params);
----
****
[[Elasticsearch_Namespaces_NodesNamespaceusage_usage]]
.`usage()`
****
[source,php]
----
/*
$params['node_id'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['metric'] = (list) Limit the information returned to the specified metrics
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->nodes()->usage($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespace]]
=== Elasticsearch\Namespaces\SnapshotNamespace
Class SnapshotNamespace
Generated running $ php util/GenerateEndpoints.php 7.4.2
*Methods*
The class defines the following methods:
* <<Elasticsearch_Namespaces_SnapshotNamespacecleanupRepository_cleanupRepository,`cleanupRepository()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacecreate_create,`create()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacecreateRepository_createRepository,`createRepository()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacedelete_delete,`delete()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacedeleteRepository_deleteRepository,`deleteRepository()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespaceget_get,`get()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacegetRepository_getRepository,`getRepository()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacerestore_restore,`restore()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespacestatus_status,`status()`>>
* <<Elasticsearch_Namespaces_SnapshotNamespaceverifyRepository_verifyRepository,`verifyRepository()`>>
[[Elasticsearch_Namespaces_SnapshotNamespacecleanupRepository_cleanupRepository]]
.`cleanupRepository()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->cleanupRepository($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacecreate_create]]
.`create()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['snapshot'] = (string) A snapshot name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['wait_for_completion'] = (boolean) Should this request wait until the operation has completed before returning (Default = false)
$params['body'] = (array) The snapshot definition
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->create($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacecreateRepository_createRepository]]
.`createRepository()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
$params['verify'] = (boolean) Whether to verify the repository after creation
$params['body'] = (array) The repository definition (Required)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->createRepository($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacedelete_delete]]
.`delete()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['snapshot'] = (string) A snapshot name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->delete($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacedeleteRepository_deleteRepository]]
.`deleteRepository()`
****
[source,php]
----
/*
$params['repository'] = (list) A comma-separated list of repository names
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->deleteRepository($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespaceget_get]]
.`get()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['snapshot'] = (list) A comma-separated list of snapshot names
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['ignore_unavailable'] = (boolean) Whether to ignore unavailable snapshots, defaults to false which means a SnapshotMissingException is thrown
$params['verbose'] = (boolean) Whether to show verbose snapshot info or only show the basic info found in the repository index blob
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->get($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacegetRepository_getRepository]]
.`getRepository()`
****
[source,php]
----
/*
$params['repository'] = (list) A comma-separated list of repository names
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['local'] = (boolean) Return local information, do not retrieve the state from master node (default: false)
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->getRepository($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacerestore_restore]]
.`restore()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['snapshot'] = (string) A snapshot name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['wait_for_completion'] = (boolean) Should this request wait until the operation has completed before returning (Default = false)
$params['body'] = (array) Details of what to restore
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->restore($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespacestatus_status]]
.`status()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['snapshot'] = (list) A comma-separated list of snapshot names
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['ignore_unavailable'] = (boolean) Whether to ignore unavailable snapshots, defaults to false which means a SnapshotMissingException is thrown
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->status($params);
----
****
[[Elasticsearch_Namespaces_SnapshotNamespaceverifyRepository_verifyRepository]]
.`verifyRepository()`
****
[source,php]
----
/*
$params['repository'] = (string) A repository name
$params['master_timeout'] = (time) Explicit operation timeout for connection to master node
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->snapshot()->verifyRepository($params);
----
****
[[Elasticsearch_Namespaces_TasksNamespace]]
=== Elasticsearch\Namespaces\TasksNamespace
Class TasksNamespace
Generated running $ php util/GenerateEndpoints.php 7.4.2
*Methods*
The class defines the following methods:
* <<Elasticsearch_Namespaces_TasksNamespacecancel_cancel,`cancel()`>>
* <<Elasticsearch_Namespaces_TasksNamespaceget_get,`get()`>>
* <<Elasticsearch_Namespaces_TasksNamespacelist_list,`list()`>>
* <<Elasticsearch_Namespaces_TasksNamespacetasksList_tasksList,`tasksList()`>>
[[Elasticsearch_Namespaces_TasksNamespacecancel_cancel]]
.`cancel()`
****
[source,php]
----
/*
$params['task_id'] = (string) Cancel the task with specified task id (node_id:task_number)
$params['nodes'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['actions'] = (list) A comma-separated list of actions that should be cancelled. Leave empty to cancel all.
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->tasks()->cancel($params);
----
****
[[Elasticsearch_Namespaces_TasksNamespaceget_get]]
.`get()`
****
[source,php]
----
/*
$params['task_id'] = (string) Return the task with specified id (node_id:task_number)
$params['wait_for_completion'] = (boolean) Wait for the matching tasks to complete (default: false)
$params['timeout'] = (time) Explicit operation timeout
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->tasks()->get($params);
----
****
[[Elasticsearch_Namespaces_TasksNamespacelist_list]]
.`list()`
****
[source,php]
----
/*
$params['nodes'] = (list) A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes
$params['actions'] = (list) A comma-separated list of actions that should be returned. Leave empty to return all.
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->tasks()->list($params);
----
****
[[Elasticsearch_Namespaces_TasksNamespacetasksList_tasksList]]
.`tasksList()`
****
[source,php]
----
/*
Proxy function to list() to prevent BC break since 7.4.0
*/
$params = [
// ...
];
$client = ClientBuilder::create()->build();
$response = $client->tasks()->tasksList($params);
----
****
[[ElasticsearchPHP_Endpoints]]
== Reference - Endpoints
This is a complete list of namespaces and their associated endpoints.
NOTE: This is auto-generated documentation
* <<Elasticsearch_Client, Elasticsearch\Client>>
* <<Elasticsearch_ClientBuilder, Elasticsearch\ClientBuilder>>
* <<Elasticsearch_Namespaces_CatNamespace, Elasticsearch\Namespaces\CatNamespace>>
* <<Elasticsearch_Namespaces_ClusterNamespace, Elasticsearch\Namespaces\ClusterNamespace>>
* <<Elasticsearch_Namespaces_IndicesNamespace, Elasticsearch\Namespaces\IndicesNamespace>>
* <<Elasticsearch_Namespaces_IngestNamespace, Elasticsearch\Namespaces\IngestNamespace>>
* <<Elasticsearch_Namespaces_NodesNamespace, Elasticsearch\Namespaces\NodesNamespace>>
* <<Elasticsearch_Namespaces_SnapshotNamespace, Elasticsearch\Namespaces\SnapshotNamespace>>
* <<Elasticsearch_Namespaces_TasksNamespace, Elasticsearch\Namespaces\TasksNamespace>>
include::Elasticsearch/Client.asciidoc[]
include::Elasticsearch/ClientBuilder.asciidoc[]
include::Elasticsearch/Namespaces/CatNamespace.asciidoc[]
include::Elasticsearch/Namespaces/ClusterNamespace.asciidoc[]
include::Elasticsearch/Namespaces/IndicesNamespace.asciidoc[]
include::Elasticsearch/Namespaces/IngestNamespace.asciidoc[]
include::Elasticsearch/Namespaces/NodesNamespace.asciidoc[]
include::Elasticsearch/Namespaces/SnapshotNamespace.asciidoc[]
include::Elasticsearch/Namespaces/TasksNamespace.asciidoc[]
[[ElasticsearchPHP_Interfaces]]
== Reference - Interfaces
This is a complete list of available interfaces:
* There are no interfaces available.
[[ElasticsearchPHP_Namespaces]]
== Reference - Namespaces
This is a complete list of available namespaces:
* <<Elasticsearch, Elasticsearch>>
* <<Elasticsearch_Namespaces, Elasticsearch\Namespaces>>
include::Elasticsearch.asciidoc[]
include::Elasticsearch/Namespaces.asciidoc[]
C:19:"Sami\Renderer\Index":944:{a:3:{i:0;a:9:{s:20:"Elasticsearch\Client";s:40:"498c4d5be950c9bd8aea481182d66604a88e28f3";s:27:"Elasticsearch\ClientBuilder";s:40:"4a02663ab50b5d678afd8fc06f8b3840d116e9f6";s:37:"Elasticsearch\Namespaces\CatNamespace";s:40:"8d5a7545dc03dede1231b99b255e93830d82dd43";s:41:"Elasticsearch\Namespaces\ClusterNamespace";s:40:"76efc72f51c81c55d786b6f1a5b991153409e754";s:41:"Elasticsearch\Namespaces\IndicesNamespace";s:40:"45eb11f7e963d832b6cf9a07559b38ae199d010a";s:40:"Elasticsearch\Namespaces\IngestNamespace";s:40:"45161815593d106eac15f02aaab8c9b4c945389d";s:39:"Elasticsearch\Namespaces\NodesNamespace";s:40:"fbc57ed03a175214b326243dcedd39d23e0e79af";s:42:"Elasticsearch\Namespaces\SnapshotNamespace";s:40:"d85d989bb5d31c674c7e75dd9efd43bd7c9b867e";s:39:"Elasticsearch\Namespaces\TasksNamespace";s:40:"36025b3b27666f4cf825bebe058e6cd5f6079ab1";}i:1;a:1:{i:0;s:6:"master";}i:2;a:2:{i:0;s:13:"Elasticsearch";i:1;s:24:"Elasticsearch\Namespaces";}}}
\ No newline at end of file
[[community_dsls]]
== Community DSLs
=== ElasticsearchDSL
https://github.com/ongr-io/ElasticsearchDSL[Link: ElasticsearchDSL]
[quote, ElasticsearchDSL]
__________________________
Introducing Elasticsearch DSL library to provide objective query builder for Elasticsearch bundle and elasticsearch-php client. You can easily build any Elasticsearch query and transform it to an array.
__________________________
=== elasticsearcher
https://github.com/madewithlove/elasticsearcher[Link: elasticsearcher]
[quote, elasticsearcher]
__________________________
This agnostic package is a lightweight wrapper on top of the Elasticsearch PHP client. Its main goal is to allow for easier structuring of queries and indices in your application. It does not want to hide or replace functionality of the Elasticsearch PHP client.
__________________________
=== ElasticSearchQueryDSL
https://github.com/gskema/elasticsearch-query-dsl-php[Link: ElasticSearchQueryDSL]
[quote, ElasticSearchQueryDSL]
__________________________
Feature complete, object oriented, composable, extendable ElasticSearch query DSL builder for PHP. Deliberately built to be as simple as possible, easily usable and with explicit naming.
__________________________
== Community Integrations
=== Symfony
==== ONGR Elasticsearch Bundle
https://github.com/ongr-io/ElasticsearchBundle[Link: ONGR Elasticsearch Bundle]
[quote, ONGR Elasticsearch Bundle]
__________________________
Elasticsearch Bundle was created in order to serve the need for professional elasticsearch
integration with enterprise level Symfony 2 systems. This bundle is:
- Supported by ONGR.io development team.
- Uses the official elasticsearch-php client.
- Ensures full integration with Symfony 2 framework.
Technical goodies:
- Provides nestable and DSL query builder to be executed by type repository services.
- Uses Doctrine-like document / entities document-object mapping using annotations.
- Query results iterators are provided for your convenience.
- Registers console commands for index and types management and data import / export.
- Designed in an extensible way for all your custom needs.
__________________________
==== FOS Elastica Bundle
https://github.com/FriendsOfSymfony/FOSElasticaBundle[Link: FOS Elastica Bundle]
[quote, FOS Elastica Bundle]
__________________________
This bundle provides integration with https://github.com/ruflin/Elastica[Link: Elastica] for Symfony. Features include:
- Integrates the Elastica library into a Symfony environment
- Automatically generate mappings using a serializer
- Listeners for Doctrine events for automatic indexing
__________________________
=== Drupal
==== Elasticsearch Connector
https://www.drupal.org/project/elasticsearch_connector[Link: Elasticsearch Connector]
[quote, Elasticsearch Connector]
__________________________
Elasticsearch Connector is a set of modules designed to build a full Elasticsearch eco system in Drupal.
__________________________
=== Laravel
==== shift31/Laravel-Elasticsearch
https://github.com/shift31/laravel-elasticsearch[Link: shift31/Laravel-Elasticsearch]
[quote, Laravel-Elasticsearch]
__________________________
This is a Laravel (4+) Service Provider for the official Elasticsearch low-level client.
__________________________
==== cviebrock/Laravel-Elasticsearch
https://github.com/cviebrock/laravel-elasticsearch[Link: cviebrock/Laravel-Elasticsearch]
[quote, Laravel-Elasticsearch]
__________________________
An easy way to use the official Elastic Search client in your Laravel applications.
__________________________
==== Plastic
https://github.com/sleimanx2/plastic[Link: Plastic]
[quote, Plastic]
__________________________
Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a fluent syntax for mapping, querying, and storing eloquent models.
__________________________
=== Helper
==== Index Helper
https://github.com/Nexucis/es-php-index-helper[Link: nexucis/es-php-index-helper]
[quote, Index Helper]
_____________________
This helper is a light library which wrap the official client elasticsearch-php. It will help you to manage your ES Indices with no downtime.
This helper implements the philosophy described in the https://www.elastic.co/guide/en/elasticsearch/guide/master/index-aliases.html[official documentation]
which can be summarized in a few words : *use alias instead of index directly*
_____________________
This diff is collapsed.
[[connection_pool]]
== Connection Pool
The connection pool is an object inside the client that is responsible for maintaining the current list of nodes.
Theoretically, nodes are either dead or alive.
However, in the real world, things are never so clear. Nodes are sometimes in a gray-zone of _"probably dead but not
confirmed"_, _"timed-out but unclear why"_ or _"recently dead but now alive"_. The connection pool's job is to
manage this set of unruly connections and try to provide the best behavior to the client.
If a connection pool is unable to find an alive node to query against, it will return a `NoNodesAvailableException`.
This is distinct from an exception due to maximum retries. For example, your cluster may have 10 nodes. You execute
a request and 9 out of the 10 nodes fail due to connection timeouts. The tenth node succeeds and the query executes.
The first nine nodes will be marked dead (depending on the connection pool being used) and their "dead" timers will begin
ticking.
When the next request is sent to the client, nodes 1-9 are still considered "dead", so they will be skipped. The request
is sent to the only known alive node (#10), and if this node fails, a `NoNodesAvailableException` is returned. You'll note
this is much less than the `retries` value, because `retries` only applies to retries against alive nodes. In this case,
only one node is known to be alive, so `NoNodesAvailableException` is returned.
There are several connection pool implementations that you can choose from:
=== staticNoPingConnectionPool (default)
This connection pool maintains a static list of hosts, which are assumed to be alive when the client initializes. If
a node fails a request, it is marked as `dead` for 60 seconds and the next node is tried. After 60 seconds, the node
is revived and put back into rotation. Each additional failed request will cause the dead timeout to increase exponentially.
A successful request will reset the "failed ping timeout" counter.
If you wish to explicitly set the `StaticNoPingConnectionPool` implementation, you may do so with the `setConnectionPool()`
method of the ClientBuilder object:
[source,php]
----
$client = ClientBuilder::create()
->setConnectionPool('\Elasticsearch\ConnectionPool\StaticNoPingConnectionPool', [])
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== staticConnectionPool
Identical to the `StaticNoPingConnectionPool`, except it pings nodes before they are used to determine if they are alive.
This may be useful for long-running scripts, but tends to be additional overhead that is unnecessary for average PHP scripts.
To use the `StaticConnectionPool`:
[source,php]
----
$client = ClientBuilder::create()
->setConnectionPool('\Elasticsearch\ConnectionPool\StaticConnectionPool', [])
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== simpleConnectionPool
The `SimpleConnectionPool` simply returns the next node as specified by the Selector; it does not perform track
the "liveness" of nodes. This pool will return nodes whether they are alive or dead. It is just a simple pool of static
hosts.
The `SimpleConnectionPool` is not recommended for routine use, but it may be a useful debugging tool.
To use the `SimpleConnectionPool`:
[source,php]
----
$client = ClientBuilder::create()
->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== sniffingConnectionPool
Unlike the two previous static connection pools, this one is dynamic. The user provides a seed list of hosts, which the
client uses to "sniff" and discover the rest of the cluster. It achieves this through the Cluster State API. As new
nodes are added or removed from the cluster, the client will update it's pool of active connections.
To use the `SniffingConnectionPool`:
[source,php]
----
$client = ClientBuilder::create()
->setConnectionPool('\Elasticsearch\ConnectionPool\SniffingConnectionPool', [])
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== Custom Connection Pool
If you wish to implement your own custom Connection Pool, your class must implement `ConnectionPoolInterface`:
[source,php]
----
class MyCustomConnectionPool implements ConnectionPoolInterface
{
/**
* @param bool $force
*
* @return ConnectionInterface
*/
public function nextConnection($force = false)
{
// code here
}
/**
* @return void
*/
public function scheduleCheck()
{
// code here
}
}
----
You can then instantiate an instance of your ConnectionPool and inject it into the ClientBuilder:
[source,php]
----
$myConnectionPool = new MyCustomConnectionPool();
$client = ClientBuilder::create()
->setConnectionPool($myConnectionPool, [])
->build();
----
If your connection pool only makes minor changes, you may consider extending `AbstractConnectionPool`, which provides
some helper concrete methods. If you choose to go down this route, you need to make sure your ConnectionPool's implementation
has a compatible constructor (since it is not defined in the interface):
[source,php]
----
class MyCustomConnectionPool extends AbstractConnectionPool implements ConnectionPoolInterface
{
public function __construct($connections, SelectorInterface $selector, ConnectionFactory $factory, $connectionPoolParams)
{
parent::__construct($connections, $selector, $factory, $connectionPoolParams);
}
/**
* @param bool $force
*
* @return ConnectionInterface
*/
public function nextConnection($force = false)
{
// code here
}
/**
* @return void
*/
public function scheduleCheck()
{
// code here
}
}
----
If your constructor matches AbstractConnectionPool, you may use either object injection or namespace instantiation:
[source,php]
----
$myConnectionPool = new MyCustomConnectionPool();
$client = ClientBuilder::create()
->setConnectionPool($myConnectionPool, []) // object injection
->setConnectionPool('/MyProject/ConnectionPools/MyCustomConnectionPool', []) // or namespace
->build();
----
=== Which connection pool to choose? PHP and connection pooling
At first glance, the `sniffingConnectionPool` implementation seems superior. For many languages, it is. In PHP, the
conversation is a bit more nuanced.
Because PHP is a share-nothing architecture, there is no way to maintain a connection pool across script instances.
This means that every script is responsible for creating, maintaining, and destroying connections everytime the script
is re-run.
Sniffing is a relatively lightweight operation (one API call to `/_cluster/state`, followed by pings to each node) but
it may be a non-negligible overhead for certain PHP applications. The average PHP script will likely load the client,
execute a few queries and then close. Imagine this script being called 1000 times per second: the sniffing connection
pool will perform the sniffing and pinging process 1000 times per second. The sniffing process will add a large
amount of overhead
In reality, if your script only executes a few queries, the sniffing concept is _too_ robust. It tends to be more
useful in long-lived processes which potentially "out-live" a static list.
For this reason the default connection pool is currently the `staticNoPingConnectionPool`. You can, of course, change
this default - but we strongly recommend you load test and verify that it does not negatively impact your performance.
[[indexing_documents]]
== Indexing Documents
IMPORTANT: Please note that mapping types will disappear from Elasticsearch, read more https://www.elastic.co/guide/en/elasticsearch/reference/7.x/removal-of-types.html[here]. If you migrated types from Elasticsearch 6 to 7, you can address these with the `type` param.
When you add documents to Elasticsearch, you index JSON documents. This maps naturally to PHP associative arrays, since
they can easily be encoded in JSON. Therefore, in Elasticsearch-PHP you create and pass associative arrays to the client
for indexing. There are several methods of ingesting data into Elasticsearch, which we will cover here.
=== Single document indexing
When indexing a document, you can either provide an ID or let elasticsearch generate one for you.
{zwsp} +
.Providing an ID value
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => [ 'testField' => 'abc']
];
// Document will be indexed to my_index/_doc/my_id
$response = $client->index($params);
----
{zwsp} +
.Omitting an ID value
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [ 'testField' => 'abc']
];
// Document will be indexed to my_index/_doc/<autogenerated ID>
$response = $client->index($params);
----
{zwsp} +
If you need to set other parameters, such as a `routing` value, you specify those in the array alongside the `index`, etc. For example, let's set the routing and timestamp of this new document:
.Additional parameters
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id',
'routing' => 'company_xyz',
'timestamp' => strtotime("-1d"),
'body' => [ 'testField' => 'abc']
];
$response = $client->index($params);
----
{zwsp} +
=== Bulk Indexing
Elasticsearch also supports bulk indexing of documents. The bulk API expects JSON action/metadata pairs, separated by
newlines. When constructing your documents in PHP, the process is similar. You first create an action array object
(e.g. `index` object), then you create a document body object. This process repeats for all your documents.
A simple example might look like this:
.Bulk indexing with PHP arrays
[source,php]
----
for($i = 0; $i < 100; $i++) {
$params['body'][] = [
'index' => [
'_index' => 'my_index',
]
];
$params['body'][] = [
'my_field' => 'my_value',
'second_field' => 'some more values'
];
}
$responses = $client->bulk($params);
----
In practice, you'll likely have more documents than you want to send in a single bulk request. In that case, you need
to batch up the requests and periodically send them:
.Bulk indexing with batches
[source,php]
----
$params = ['body' => []];
for ($i = 1; $i <= 1234567; $i++) {
$params['body'][] = [
'index' => [
'_index' => 'my_index',
'_id' => $i
]
];
$params['body'][] = [
'my_field' => 'my_value',
'second_field' => 'some more values'
];
// Every 1000 documents stop and send the bulk request
if ($i % 1000 == 0) {
$responses = $client->bulk($params);
// erase the old bulk request
$params = ['body' => []];
// unset the bulk response when you are done to save memory
unset($responses);
}
}
// Send the last batch if it exists
if (!empty($params['body'])) {
$responses = $client->bulk($params);
}
----
[[getting_documents]]
== Getting Documents
Elasticsearch provides realtime GETs of documents. This means that as soon as the document has been indexed and your
client receives an acknowledgement, you can immediately retrieve the document from any shard. Get operations are
performed by requesting a document by it's full `index/type/id` path:
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
// Get doc at /my_index/_doc/my_id
$response = $client->get($params);
----
{zwsp} +
[[updating_documents]]
== Updating Documents
Updating a document allows you to either completely replace the contents of the existing document, or perform a partial
update to just some fields (either changing an existing field, or adding new fields).
=== Partial document update
If you want to partially update a document (e.g. change an existing field, or add a new one) you can do so by specifying
the `doc` in the `body` parameter. This will merge the fields in `doc` with the existing document
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => [
'doc' => [
'new_field' => 'abc'
]
]
];
// Update doc at /my_index/_doc/my_id
$response = $client->update($params);
----
{zwsp} +
=== Scripted document update
Sometimes you need to perform a scripted update, such as incrementing a counter or appending a new value to an array.
To perform a scripted update, you need to provide a script and (usually) a set of parameters:
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => [
'script' => 'ctx._source.counter += count',
'params' => [
'count' => 4
]
]
];
$response = $client->update($params);
----
{zwsp} +
=== Upserts
Upserts are "Update or Insert" operations. This means an upsert will attempt to run your update script, but if the document
does not exist (or the field you are trying to update doesn't exist), default values will be inserted instead.
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => [
'script' => [
'source' => 'ctx._source.counter += params.count',
'params' => [
'count' => 4
],
],
'upsert' => [
'counter' => 1
],
]
];
$response = $client->update($params);
----
{zwsp} +
[[deleting_documents]]
== Deleting documents
Finally, you can delete documents by specifying their full `/index/_doc_/id` path:
[source,php]
----
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
// Delete doc at /my_index/_doc_/my_id
$response = $client->delete($params);
----
{zwsp} +
[[experimental_and_beta_apis]]
== Experimental and beta APIs
The PHP client offers also `experimental` and `beta` APIs for Elasticsearch.
The Elasticsearch API are marked using the following convention:
- **Stable** APIs should be safe to use extensively in production.
Any breaking changes to these APIs should only occur in major versions and
will be clearly documented in the breaking changes documentation for that
release.
- **Beta** APIs are on track to become stable and permanent features.
Caution should be exercised in their use since it is possible we’d have to make
a breaking change to these APIs in a minor version, but we’ll avoid this
wherever possible.
- **Experimental** APIs are just that - an experiment. An experimental API might
have breaking changes in any future version, or it might even be removed
entirely.
All the `experimental` and `beta` APIs are marked with a `@note` tag in the
phpdoc section of the code.
=== Experimental
The experimental APIs included in the current version of `elasticsearch-php` are:
- [Ranking Evaluation](https://www.elastic.co/guide/en/elasticsearch/reference/7.4/search-rank-eval.html)
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
// ...
];
$result = $client->rankEval($params);
----
- [Painless Execute](https://www.elastic.co/guide/en/elasticsearch/painless/7.4/painless-execute-api.html)
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
// ...
];
$result = $client->scriptsPainlessExecute($params);
----
=== Beta
There are no beta APIs in the current version of `elasticsearch-php`.
\ No newline at end of file
[[future_mode]]
== Future Mode
The client offers a mode called "future" or "async" mode. This allows batch processing of requests (sent in parallel
to the cluster), which can have a dramatic impact on performance and throughput.
PHP is fundamentally single-threaded, however libcurl provides functionality called the "multi interface". This allows
languages like PHP to gain concurrency by providing a batch of requests to process. The batch is executed in a parallel
by the underlying multithreaded libcurl library, and the batch of responses is then returned to PHP.
In a single-threaded environment, the time to execute `n` requests is the sum of those `n` request's latencies. With
the multi interface, the time to execute `n` requests is the latency of the slowest request (assuming enough handles
are available to execute all requests in parallel).
Furthermore, the multi-interface allows requests to different hosts simultaneously, which means the Elasticsearch-PHP
client can more effectively utilize your full cluster.
=== Using Future Mode
Utilizing this feature is relatively straightforward, but it does introduce more responsibility into your code. To enable
future mode, set the `future` flag in the client options to `'lazy'`:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'future' => 'lazy'
]
];
$future = $client->get($params);
----
This will return a _future_, rather than the actual response. A future represents a _future computation_ and acts like
a placeholder. You can pass a future around your code like a regular object. When you need the result values, you
can _resolve_ the future. If the future has already resolved (due to some other activity), the values will be immediately
available. If the future has not resolved yet, the resolution will block until those values have become available (e.g.
after the API call completes).
In practice, this means you can queue up a batch of requests by using `future: lazy` and they will pend until you resolve
the futures, at which time all requests will be sent in parallel to the cluster and return asynchronously to curl.
This sounds tricky, but it is actually very simple thanks to RingPHP's `FutureArray` interface, which makes the future
act like a simple associative array. For example:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'future' => 'lazy'
]
];
$future = $client->get($params);
$doc = $future['_source']; // This call will block and force the future to resolve
----
Interacting with the future as an associative array, just like a normal response, will cause the future to resolve
that particular value (which in turn resolves all pending requests and values). This allows patterns such as:
[source,php]
----
$client = ClientBuilder::create()->build();
$futures = [];
for ($i = 0; $i < 1000; $i++) {
$params = [
'index' => 'test',
'id' => $i,
'client' => [
'future' => 'lazy'
]
];
$futures[] = $client->get($params); //queue up the request
}
foreach ($futures as $future) {
// access future's values, causing resolution if necessary
echo $future['_source'];
}
----
The queued requests will execute in parallel and populate their futures after execution. Batch size defaults to
100 requests-per-batch.
If you wish to force future resolution, but don't actually need the values immediately, you can call `wait()` on the future
to force resolution too:
[source,php]
----
$client = ClientBuilder::create()->build();
$futures = [];
for ($i = 0; $i < 1000; $i++) {
$params = [
'index' => 'test',
'id' => $i,
'client' => [
'future' => 'lazy'
]
];
$futures[] = $client->get($params); //queue up the request
}
//wait() forces future resolution and will execute the underlying curl batch
$futures[999]->wait();
----
=== Changing batch size
The default batch size is 100, meaning 100 requests will queue up before the client forces futures to begin resolving
(e.g. initiate a `curl_multi` call). The batch size can be changed depending on your preferences. The batch size
is controllable via the `max_handles` setting when configuring the handler:
[source,php]
----
$handlerParams = [
'max_handles' => 500
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$client = ClientBuilder::create()
->setHandler($defaultHandler)
->build();
----
This will change the behavior to wait on 500 queued requests before sending the batch. Note, however, that forcing a
future to resolve will cause the underlying curl batch to execute, regardless of if the batch is "full" or not. In this
example, only 499 requests are added to the queue...but the final future resolution will force the batch to flush
anyway:
[source,php]
----
$handlerParams = [
'max_handles' => 500
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$client = ClientBuilder::create()
->setHandler($defaultHandler)
->build();
$futures = [];
for ($i = 0; $i < 499; $i++) {
$params = [
'index' => 'test',
'id' => $i,
'client' => [
'future' => 'lazy'
]
];
$futures[] = $client->get($params); //queue up the request
}
// resolve the future, and therefore the underlying batch
$body = $future[499]['body'];
----
=== Heterogeneous batches are OK
It is possible to queue up heterogeneous batches of requests. For example, you can queue up several GETs, indexing requests
and a search:
[source,php]
----
$client = ClientBuilder::create()->build();
$futures = [];
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'future' => 'lazy'
]
];
$futures['getRequest'] = $client->get($params); // First request
$params = [
'index' => 'test',
'id' => 2,
'body' => [
'field' => 'value'
],
'client' => [
'future' => 'lazy'
]
];
$futures['indexRequest'] = $client->index($params); // Second request
$params = [
'index' => 'test',
'body' => [
'query' => [
'match' => [
'field' => 'value'
]
]
],
'client' => [
'future' => 'lazy'
]
];
$futures['searchRequest'] = $client->search($params); // Third request
// Resolve futures...blocks until network call completes
$searchResults = $futures['searchRequest']['hits'];
// Should return immediately, since the previous future resolved the entire batch
$doc = $futures['getRequest']['_source'];
----
=== Caveats to Future mode
There are a few caveats to using future mode. The biggest is also the most obvious: you need to deal with resolving the
future yourself. This is usually trivial, but can sometimes introduce unexpected complications.
For example, if you resolve manually using `wait()`, you may need to call `wait()` several times if there were retries.
This is because each retry will introduce another layer of wrapped futures, and each needs to be resolved to get the
final result.
This is not needed if you access values via the ArrayInterface however (e.g. `$response['hits']['hits']`), since
FutureArrayInterface will automatically and fully resolve the future to provide values.
Another caveat is that certain APIs will lose their "helper" functionality. For example, "exists" APIs (e.g.
`$client->exists()`, `$client->indices()->exists`, `$client->indices->templateExists()`, etc) typically return a true
or false under normal operation.
When operated in future mode, unwrapping of the future is left to your application,
which means the client can no longer inspect the response and return a simple true/false. Instead, you'll see the raw
response from Elasticsearch and will have to take action appropriately.
This also applies to `ping()`.
\ No newline at end of file
[[index_management]]
== Index Management Operations
Index management operations allow you to manage the indices in your Elasticsearch cluster, such as creating, deleting and
updating indices and their mappings/settings.
=== Create an index
The index operations are all contained under a distinct namespace, separated from other methods that are on the root
client object. As an example, let's create a new index:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index'
];
// Create the index
$response = $client->indices()->create($params);
----
{zwsp} +
You can specify any parameters that would normally be included in a new index creation API. All parameters that
would normally go in the request body are located in the 'body' parameter:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'first_name' => [
'type' => 'keyword'
],
'age' => [
'type' => 'integer'
]
]
]
]
];
// Create the index with mappings and settings now
$response = $client->indices()->create($params);
----
{zwsp} +
=== Create an index (advanced example)
This is a more complicated example of creating an index, showing how to define analyzers, tokenizers, filters and
index settings. Although essentially the same as the previous example, the more complicated example can be helpful
for "real world" usage of the client, since this particular syntax is easy to mess up.
[source,php]
----
$params = [
'index' => 'reuters',
'body' => [
'settings' => [ <1>
'number_of_shards' => 1,
'number_of_replicas' => 0,
'analysis' => [ <2>
'filter' => [
'shingle' => [
'type' => 'shingle'
]
],
'char_filter' => [
'pre_negs' => [
'type' => 'pattern_replace',
'pattern' => '(\\w+)\\s+((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\b',
'replacement' => '~$1 $2'
],
'post_negs' => [
'type' => 'pattern_replace',
'pattern' => '\\b((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\s+(\\w+)',
'replacement' => '$1 ~$2'
]
],
'analyzer' => [
'reuters' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => ['lowercase', 'stop', 'kstem']
]
]
]
],
'mappings' => [ <3>
'properties' => [
'title' => [
'type' => 'text',
'analyzer' => 'reuters',
'copy_to' => 'combined'
],
'body' => [
'type' => 'text',
'analyzer' => 'reuters',
'copy_to' => 'combined'
],
'combined' => [
'type' => 'text',
'analyzer' => 'reuters'
],
'topics' => [
'type' => 'keyword'
],
'places' => [
'type' => 'keyword'
]
]
]
]
];
$client->indices()->create($params);
----
<1> The top level `settings` contains config about the index (# of shards, etc) as well as analyzers
<2> `analysis` is nested inside of `settings`, and contains tokenizers, filters, char filters and analyzers
<3> `mappings` is another element nested inside of `settings`, and contains the mappings for various types
=== Delete an index
Deleting an index is very simple:
[source,php]
----
$params = ['index' => 'my_index'];
$response = $client->indices()->delete($params);
----
{zwsp} +
=== Put Settings API
The Put Settings API allows you to modify any index setting that is dynamic:
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_replicas' => 0,
'refresh_interval' => -1
]
]
];
$response = $client->indices()->putSettings($params);
----
{zwsp} +
=== Get Settings API
Get Settings API will show you the currently configured settings for one or more indexes:
[source,php]
----
// Get settings for one index
$params = ['index' => 'my_index'];
$response = $client->indices()->getSettings($params);
// Get settings for several indices
$params = [
'index' => [ 'my_index', 'my_index2' ]
];
$response = $client->indices()->getSettings($params);
----
{zwsp} +
=== Put Mappings API
The Put Mappings API allows you to modify or add to an existing index's mapping.
[source,php]
----
// Set the index and type
$params = [
'index' => 'my_index',
'body' => [
'_source' => [
'enabled' => true
],
'properties' => [
'first_name' => [
'type' => 'text',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
];
// Update the index mapping
$client->indices()->putMapping($params);
----
{zwsp} +
=== Get Mappings API
The Get Mappings API will return the mapping details about your indexes. Depending on the mappings that you wish to retrieve, you can specify one of more indexes:
[source,php]
----
// Get mappings for all indexes
$response = $client->indices()->getMapping();
// Get mappings in 'my_index'
$params = ['index' => 'my_index'];
$response = $client->indices()->getMapping($params);
// Get mappings for two indexes
$params = [
'index' => [ 'my_index', 'my_index2' ]
];
$response = $client->indices()->getMapping($params);
----
{zwsp} +
=== Other APIs in the Indices Namespace
There are a number of other APIs in the indices namespace that allow you to manage your elasticsearch indexes (add/remove templates, flush segments, close indexes, etc).
If you use an IDE with autocompletion, you should be able to easily explore the indices namespace by typing:
[source,php]
----
$client->indices()->
----
And perusing the list of available methods. Alternatively, browsing the `\Elasticsearch\Namespaces\Indices.php` file will show you the full list of available method calls (as well as parameter lists in the comments for each method).
= Elasticsearch-PHP
include::overview.asciidoc[]
include::quickstart.asciidoc[]
include::installation.asciidoc[]
include::configuration.asciidoc[]
include::per-request-configuration.asciidoc[]
include::futures.asciidoc[]
include::php_json_objects.asciidoc[]
include::index-operations.asciidoc[]
include::crud.asciidoc[]
include::search-operations.asciidoc[]
include::namespaces.asciidoc[]
include::security.asciidoc[]
include::connection-pool.asciidoc[]
include::selectors.asciidoc[]
include::serializers.asciidoc[]
include::php-version-requirement.asciidoc[]
include::breaking-changes.asciidoc[]
include::community.asciidoc[]
include::experimental-beta-apis.asciidoc[]
include::build/classes.asciidoc[]
[[installation]]
== Installation
Elasticsearch-php only has a three requirements that you need to worry about:
* PHP 7.0.0 or higher
* http://getcomposer.org[Composer]
* http://php.net/manual/en/book.curl.php[ext-curl]: the Libcurl extension for PHP (see note below)
* Native JSON Extensions (`ext-json`) 1.3.7 or higher
The rest of the dependencies will automatically be downloaded and installed by Composer. Composer is a package and dependency manager for PHP. Installing elasticsearch-php with Composer is very easy
[NOTE]
.Libcurl can be replaced
====
The default HTTP handlers that ship with Elasticsearch-php require the PHP libcurl extension, but it is not technically
required for the client to operate. If you have a host that does not have libcurl installed, you can use an
alternate HTTP handler based on PHP streams. Performance _will_ suffer, as the libcurl extension is much faster
====
=== Version Matrix
You need to match your version of Elasticsearch to the appropriate version of this library.
The master branch will always track Elasticsearch master, but it is not recommended to use `dev-master` in your production code.
[width="40%",options="header",frame="topbot"]
|============================
|Elasticsearch Version | Elasticsearch-PHP Branch
| >= 7.0, < 8.0 | `7.0`
| >= 6.6, <= 6.7 | `6.7.x`
| >= 6.0, <= 6.5 | `6.5.c`
| >= 5.0, < 6.0 | `5.0`
| >= 1.0, < 5.0 | `1.0`, `2.0`
| <= 0.90.* | `0.4`
|============================
=== Composer Installation
* Include elasticsearch-php in your `composer.json` file. If you are starting a new project, simply paste the following JSON snippet into a new file called `composer.json`. If you have an existing project, include this requirement under the rest of requirements already present:
+
[source,json]
--------------------------
{
"require": {
"elasticsearch/elasticsearch": "~7.0"
}
}
--------------------------
* Install the client with composer. The first command download the `composer.phar` PHP package, and the second command invokes the installation. Composer will automatically download any required dependencies, store them in a /vendor/ directory and build an autoloader.:
+
[source,shell]
--------------------------
curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev
--------------------------
+
More information about http://getcomposer.org/[Composer can be found at their website].
* Finally, include the generated autoloader in your main project. If your project is already based on Composer, the autoloader is likely already included somewhere and you don't need to add it again. Finally, instantiate a new client:
+
[source,php]
--------------------------
require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
--------------------------
+
Client instantiation is performed with a static helper function `create()`. This creates a ClientBuilder object,
which helps you to set custom configurations. When you are done configuring, you call the `build()` method to generate
a `Client` object. We'll discuss configuration more in the Configuration section
=== --no-dev flag
You'll notice that the installation command specified `--no-dev`. This prevents Composer
from installing the various testing and development dependencies. For average users, there
is no need to install the test suite. In particular, the development dependencies include
a full copy of Elasticsearch so that tests can be run against the REST specifications. This
is a rather large download for non-developers, hence the --no-dev flag
If you wish to contribute to development of this library, just omit the `--no-dev` flag to
be able to run tests.
[[namespaces]]
== Namespaces
The client has a number of "namespaces", which generally expose administrative
functionality. The namespaces correspond to the various administrative endpoints
in Elasticsearch. This is a complete list of namespaces:
[width="40%",options="header",frame="topbot"]
|============================
| Namespace | Functionality
| `indices()` | Index-centric stats and info
| `nodes()` | Node-centric stats and info
| `cluster()` | Cluster-centric stats and info
| `snapshot()` | Methods to snapshot/restore your cluster and indices
| `cat()` | Access to the Cat API (which is generally used standalone from the command line
|============================
Some methods are available in several different namespaces, which give you
the same information but grouped into different contexts. To see how these
namespaces work, let's look at the `_stats` output:
[source,php]
----
$client = ClientBuilder::create()->build();
// Index Stats
// Corresponds to curl -XGET localhost:9200/_stats
$response = $client->indices()->stats();
// Node Stats
// Corresponds to curl -XGET localhost:9200/_nodes/stats
$response = $client->nodes()->stats();
// Cluster Stats
// Corresponds to curl -XGET localhost:9200/_cluster/stats
$response = $client->cluster()->stats();
----
{zwsp} +
As you can see, the same `stats()` call is made through three different
namespaces. Sometimes the methods require parameters. These parameters work
just like any other method in the library.
For example, we can requests index stats about a specific index, or multiple
indices:
[source,php]
----
$client = ClientBuilder::create()->build();
// Corresponds to curl -XGET localhost:9200/my_index/_stats
$params['index'] = 'my_index';
$response = $client->indices()->stats($params);
// Corresponds to curl -XGET localhost:9200/my_index1,my_index2/_stats
$params['index'] = array('my_index1', 'my_index2');
$response = $client->indices()->stats($params);
----
{zwsp} +
As another example, here is how you might add an alias to an existing index:
[source,php]
----
$params['body'] = array(
'actions' => array(
array(
'add' => array(
'index' => 'myindex',
'alias' => 'myalias'
)
)
)
);
$client->indices()->updateAliases($params);
----
Notice how both the `stats` calls and the updateAlias took a variety of parameters,
each according to what the particular API requires. The `stats` API only requires
an index name(s), while the `updateAlias` requires a body of actions.
\ No newline at end of file
[[overview]]
== Overview
This is the official PHP client for Elasticsearch. It is designed to be a very low-level client that does not stray from the REST API.
All methods closely match the REST API, and furthermore, match the method structure of other language clients (ruby, python, etc). We hope that this consistency makes it easy to get started with a client, and to seamlessly switch from one language to the next with minimal effort.
The client is designed to be "unopinionated". There are a few universal niceties added to the client (cluster state sniffing, round-robin requests, etc) but largely it is very barebones. This was intentional. We want a common base that more sophisticated libraries can build on top of.
[[per_request_configuration]]
== Per-request configuration
There are several configurations that can be set on a per-request basis, rather than at a connection- or client-level.
These are specified as part of the request associative array.
=== Request Identification
You can enrich your requests against Elasticsearch with an identifier string, that allows you to discover this identifier
in https://www.elastic.co/guide/en/elasticsearch/reference/7.4/logging.html#deprecation-logging[deprecation logs], to support you with
https://www.elastic.co/guide/en/elasticsearch/reference/7.4/index-modules-slowlog.html#_identifying_search_slow_log_origin[identifying search slow log origin]
or to help with https://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html#_identifying_running_tasks[identifying running tasks].
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'opaqueId' => 'app17@dc06.eu_user1234', <1>
]
];
$response = $client->get($params);
----
<1> This will populate the `X-Opaque-Id` header with the value `app17@dc06.eu_user1234`
=== Ignoring exceptions
The library attempts to throw exceptions for common problems. These exceptions match the HTTP response code provided
by Elasticsearch. For example, attempting to GET a nonexistent document will throw a `MissingDocument404Exception`.
Exceptions are a useful and consistent way to deal with problems like missing documents, syntax errors, version
conflicts, etc. But sometimes you want to deal with the response body rather than catch exceptions (often useful
in test suites).
If you need that behavior, you can configure an `ignore` parameter. This should be configured in the `client` parameter
of the request array. For example, this example will ignore the `MissingDocument404Exception`
exception and instead return the JSON provided by Elasticsearch.
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test_missing',
'id' => 1,
'client' => [ 'ignore' => 404 ] <1>
];
echo $client->get($params);
> {"_index":"test_missing","_type":"_doc","_id":"1","found":false}
----
<1> This will ignore just the 404 missing exception
You can specify multiple HTTP status codes to ignore, by providing an array of values:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test_missing',
'client' => [ 'ignore' => [400, 404] ] <1>
];
echo $client->get($params);
> No handler found for uri [/test_missing/test/] and method [GET]
----
<1> `ignore` also accepts an array of exceptions to ignore. In this example,
the `BadRequest400Exception` is being ignored
It should be noted that the response is simply a string, which may or may not be encoded as JSON. In the first example,
the response body was a complete JSON object which could be decoded. In the second example, it was simply a string.
Since the client has no way of knowing what the exception response will contain, no attempts to decode it are taken.
=== Providing custom query parameters
Sometimes you need to provide custom query params, such as authentication tokens for a third-party plugin or proxy.
All query parameters are white-listed in Elasticsearch-php, which is to protect you from specifying a param which is
not accepted by Elasticsearch.
If you need custom parameters, you need to bypass this whitelisting mechanism. To do so, add them to the `custom`
parameter as an array of values:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'parent' => 'abc', // white-listed Elasticsearch parameter
'client' => [
'custom' => [
'customToken' => 'abc', // user-defined, not white listed, not checked
'otherToken' => 123
]
]
];
$exists = $client->exists($params);
----
=== Increasing the Verbosity of responses
By default, the client will only return the response body. If you require more information (e.g. stats about the transfer,
headers, status codes, etc), you can tell the client to return a more verbose response. This is enabled via the
`verbose` parameter in the client options.
Without verbosity, all you see is the response body:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1
];
$response = $client->get($params);
print_r($response);
Array
(
[_index] => test
[_type] => _doc
[_id] => 1
[_version] => 1
[found] => 1
[_source] => Array
(
[field] => value
)
)
----
With verbosity turned on, you will see all of the transfer stats:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'verbose' => true
]
];
$response = $client->get($params);
print_r($response);
Array
(
[transfer_stats] => Array
(
[url] => http://127.0.0.1:9200/test/test/1
[content_type] => application/json; charset=UTF-8
[http_code] => 200
[header_size] => 86
[request_size] => 51
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.00289
[namelookup_time] => 9.7E-5
[connect_time] => 0.000265
[pretransfer_time] => 0.000322
[size_upload] => 0
[size_download] => 96
[speed_download] => 33217
[speed_upload] => 0
[download_content_length] => 96
[upload_content_length] => -1
[starttransfer_time] => 0.002796
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 127.0.0.1
[certinfo] => Array
(
)
[primary_port] => 9200
[local_ip] => 127.0.0.1
[local_port] => 62971
)
[curl] => Array
(
[error] =>
[errno] => 0
)
[effective_url] => http://127.0.0.1:9200/test/test/1
[headers] => Array
(
[Content-Type] => Array
(
[0] => application/json; charset=UTF-8
)
[Content-Length] => Array
(
[0] => 96
)
)
[status] => 200
[reason] => OK
[body] => Array
(
[_index] => test
[_type] => _doc
[_id] => 1
[_version] => 1
[found] => 1
[_source] => Array
(
[field] => value
)
)
)
----
=== Curl Timeouts
It is possible to configure per-request curl timeouts via the `timeout` and `connect_timeout` parameters. These
control the client-side, curl timeouts. The `connect_timeout` paramter controls how long curl should wait for the
"connect" phase to finish, while the `timeout` parameter controls how long curl should wait for the entire request
to finish.
If either timeout expires, curl will close the connection and return an error. Both parameters should be specified
in seconds.
Note: client-side timeouts *do not* mean that Elasticsearch aborts the request. Elasticsearch will continue executing
the request until it completes. In the case of a slow query or bulk request, the operation will continue executing
"in the background", unknown to your client. If your client kills connections rapidly with a timeout, only to immediately
execute another request, it is possible to swamp the server with many connections because there is no "back-pressure" on the
client. In these situations, you will see the appropriate threadpool queue growing in size, and may start receiving
`EsRejectedExecutionException` exceptions from Elasticsearch when the queue finally reaches capacity.
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'timeout' => 10, // ten second timeout
'connect_timeout' => 10
]
];
$response = $client->get($params);
----
=== Enabling Future Mode
The client supports asynchronous, batch processing of requests. This is enabled (if your HTTP handler supports it) on
a per-request basis via the `future` parameter in the client options:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'future' => 'lazy'
]
];
$future = $client->get($params);
$results = $future->wait(); // resolve the future
----
Future mode supports two options: `true` or `'lazy'`. For more details about how asynchronous execution functions, and
how to work with the results, see the dedicated page on <<future_mode>>.
=== SSL Encryption
Normally, you will specify SSL configurations when you create the client (see
<<security>> for more details), since encryption typically
applies to all requests. However, it is possible to configure on a per-request basis too if you need that functionality.
For example, if you need to use a self-signed cert on a specific request, you can specify it via the `verify` parameter
in the client options:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'index' => 'test',
'id' => 1,
'client' => [
'verify' => 'path/to/cacert.pem' //Use a self-signed certificate
]
];
$result = $client->get($params);
----
[[php_version_requirement]]
== PHP Version Requirement
Version 7.0 of Elasticsearch-PHP requires PHP version 7.1.0 or higher.
In addition, it requires the native JSON extension to be version 1.3.7 or higher.
[[php_json_objects]]
== Dealing with JSON Arrays and Objects in PHP
A common source of confusion with the client revolves around JSON arrays and objects, and how to specify them in PHP.
In particular, problems are caused by empty objects and arrays of objects. This page will show you some common patterns
used in Elasticsearch JSON API, and how to convert that to a PHP representation
=== Empty Objects
The Elasticsearch API uses empty JSON objects in several locations, and this can cause problems for PHP. Unlike other
languages, PHP does not have a "short" notation for empty objects and so many developers are unaware how to specify
an empty object.
Consider adding a Highlight to a query:
[source,json]
----
{
"query" : {
"match" : {
"content" : "quick brown fox"
}
},
"highlight" : {
"fields" : {
"content" : {} <1>
}
}
}
----
<1> This empty JSON object is what causes problems.
The problem is that PHP will automatically convert `"content" : {}` into `"content" : []`, which is no longer valid
Elasticsearch DSL. We need to tell PHP that the empty object is explicitly an object, not an array. To define this
query in PHP, you would do:
[source,json]
----
$params['body'] = array(
'query' => array(
'match' => array(
'content' => 'quick brown fox'
)
),
'highlight' => array(
'fields' => array(
'content' => new \stdClass() <1>
)
)
);
$results = $client->search($params);
----
<1> We use the generic PHP stdClass object to represent an empty object. The JSON will now encode correctly.
By using an explicit stdClass object, we can force the `json_encode` parser to correctly output an empty object, instead
of an empty array. Sadly, this verbose solution is the only way to acomplish the goal in PHP...there is no "short"
version of an empty object.
=== Arrays of Objects
Another common pattern in Elasticsearch DSL is an array of objects. For example, consider adding a sort to your query:
[source,json]
----
{
"query" : {
"match" : { "content" : "quick brown fox" }
},
"sort" : [ <1>
{"time" : {"order" : "desc"}},
{"popularity" : {"order" : "desc"}}
]
}
----
<1> "sort" contains an array of JSON objects
This arrangement is *very* common, but the construction in PHP can be tricky since it requires nesting arrays. The
verbosity of PHP tends to obscure what is actually going on. To construct an array of objects, you actually need
an array of arrays:
[source,json]
----
$params['body'] = array(
'query' => array(
'match' => array(
'content' => 'quick brown fox'
)
),
'sort' => array( <1>
array('time' => array('order' => 'desc')), <2>
array('popularity' => array('order' => 'desc')) <3>
)
);
$results = $client->search($params);
----
<1> This array encodes the `"sort" : []` array
<2> This array encodes the `{"time" : {"order" : "desc"}}` object
<3> This array encodes the `{"popularity" : {"order" : "desc"}}` object
If you are on PHP 5.4+, I would strongly encourage you to use the short array syntax. It makes these nested arrays
much simpler to read:
[source,json]
----
$params['body'] = [
'query' => [
'match' => [
'content' => 'quick brown fox'
]
],
'sort' => [
['time' => ['order' => 'desc']],
['popularity' => ['order' => 'desc']]
]
];
$results = $client->search($params);
----
=== Arrays of empty objects
Occasionally, you'll encounter DSL that requires both of the previous patterns. The function score query is a good
example, it sometimes requires an array of objects, and some of those objects might be empty JSON objects.
Given this query:
[source,json]
----
{
"query":{
"function_score":{
"functions":[
{
"random_score":{}
}
],
"boost_mode":"replace"
}
}
}
----
We can build it using the following PHP code:
[source,json]
----
$params['body'] = array(
'query' => array(
'function_score' => array(
'functions' => array( <1>
array( <2>
'random_score' => new \stdClass() <3>
)
)
)
)
);
$results = $client->search($params);
----
<1> This encodes the array of objects: `"functions" : []`
<2> This encodes an object inside the array: `{ "random_score": {} }`
<3> This encodes the empty JSON object: `"random_score": {}`
\ No newline at end of file
[[quickstart]]
== Quickstart
This section will give you a quick overview of the client and how the major functions work.
=== Installation
* Include elasticsearch-php in your `composer.json` file:
+
[source,json]
----------------------------
{
"require": {
"elasticsearch/elasticsearch": "~7.0"
}
}
----------------------------
* Install the client with composer:
+
[source,shell]
----------------------------
curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev
----------------------------
* Include the autoloader in your main project (if you haven't already), and instantiate a new client :
+
[source,php]
----------------------------
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();
----------------------------
=== Index a document
In elasticsearch-php, almost everything is configured by associative arrays. The REST endpoint, document and optional parameters - everything is an associative array.
To index a document, we need to specify three pieces of information: index, id and a document body. This is done by
constructing an associative array of key:value pairs. The request body is itself an associative array with key:value pairs
corresponding to the data in your document:
[source,php]
----------------------------
$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
----------------------------
The response that you get back indicates the document was created in the index that you specified. The response is an
associative array containing a decoded version of the JSON that Elasticsearch returns:
[source,php]
----------------------------
Array
(
[_index] => my_index
[_type] => _doc
[_id] => my_id
[_version] => 1
[created] => 1
)
----------------------------
=== Get a document
Let's get the document that we just indexed. This will simply return the document:
[source,php]
----------------------------
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
$response = $client->get($params);
print_r($response);
----------------------------
The response contains some metadata (index, version, etc.) as well as a `_source` field, which is the original document
that you sent to Elasticsearch.
[source,php]
----------------------------
Array
(
[_index] => my_index
[_type] => _doc
[_id] => my_id
[_version] => 1
[found] => 1
[_source] => Array
(
[testField] => abc
)
)
----------------------------
=== Search for a document
Searching is a hallmark of elasticsearch, so let's perform a search. We are going to use the Match query as a demonstration:
[source,php]
----------------------------
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$response = $client->search($params);
print_r($response);
----------------------------
The response is a little different from the previous responses. We see some metadata (`took`, `timed_out`, etc) and
an array named `hits`. This represents your search results. Inside of `hits` is another array named `hits`, which contains
individual search results:
[source,php]
----------------------------
Array
(
[took] => 1
[timed_out] =>
[_shards] => Array
(
[total] => 5
[successful] => 5
[failed] => 0
)
[hits] => Array
(
[total] => 1
[max_score] => 0.30685282
[hits] => Array
(
[0] => Array
(
[_index] => my_index
[_type] => _doc
[_id] => my_id
[_score] => 0.30685282
[_source] => Array
(
[testField] => abc
)
)
)
)
)
----------------------------
=== Delete a document
Alright, let's go ahead and delete the document that we added previously:
[source,php]
----------------------------
$params = [
'index' => 'my_index',
'id' => 'my_id'
];
$response = $client->delete($params);
print_r($response);
----------------------------
You'll notice this is identical syntax to the `get` syntax. The only difference is the operation: `delete` instead of
`get`. The response will confirm the document was deleted:
[source,php]
----------------------------
Array
(
[found] => 1
[_index] => my_index
[_type] => _doc
[_id] => my_id
[_version] => 2
)
----------------------------
=== Delete an index
Due to the dynamic nature of elasticsearch, the first document we added automatically built an index with some default settings. Let's delete that index because we want to specify our own settings later:
[source,php]
----------------------------
$deleteParams = [
'index' => 'my_index'
];
$response = $client->indices()->delete($deleteParams);
print_r($response);
----------------------------
The response:
[source,php]
----------------------------
Array
(
[acknowledged] => 1
)
----------------------------
=== Create an index
Now that we are starting fresh (no data or index), let's add a new index with some custom settings:
[source,php]
----------------------------
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$response = $client->indices()->create($params);
print_r($response);
----------------------------
Elasticsearch will now create that index with your chosen settings, and return an acknowledgement:
[source,php]
----------------------------
Array
(
[acknowledged] => 1
)
----------------------------
=== Wrap up
That was just a crash-course overview of the client and it's syntax. If you are familiar with elasticsearch, you'll
notice that the methods are named just like REST endpoints.
You'll also notice that the client is configured in a manner that facilitates easy discovery via your IDE. All core
actions are available under the `$client` object (indexing, searching, getting, etc). Index and cluster management
are located under the `$client->indices()` and `$client->cluster()` objects, respectively.
Check out the rest of the Documentation to see how the entire client works.
[[search_operations]]
== Search Operations
Well...it isn't called elasticsearch for nothing! Let's talk about search operations in the client.
The client gives you full access to every query and parameter exposed by the REST API, following the naming scheme as
much as possible. Let's look at a few examples so you can become familiar with the syntax.
=== Match Query
Here is a standard curl for a Match query:
[source,shell]
----
curl -XGET 'localhost:9200/my_index/_search' -d '{
"query" : {
"match" : {
"testField" : "abc"
}
}
}'
----
{zwsp} +
And here is the same query constructed in the client:
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$results = $client->search($params);
----
{zwsp} +
Notice how the structure and layout of the PHP array is identical to that of the JSON request body. This makes it very
simple to convert JSON examples into PHP. A quick method to check your PHP array (for more complex examples) is to
encode it back to JSON and check by eye:
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
print_r(json_encode($params['body']));
{"query":{"match":{"testField":"abc"}}}
----
{zwsp} +
.Using Raw JSON
****
Sometimes it is convenient to use raw JSON for testing purposes, or when migrating from a different system. You can
use raw JSON as a string in the body, and the client will detect this automatically:
[source,php]
----
$json = '{
"query" : {
"match" : {
"testField" : "abc"
}
}
}';
$params = [
'index' => 'my_index',
'body' => $json
];
$results = $client->search($params);
----
****
{zwsp} +
Search results follow the same format as Elasticsearch search response, the only difference is that the JSON response is
serialized back into PHP arrays. Working with the search results is as simple as iterating over the array values:
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$results = $client->search($params);
$milliseconds = $results['took'];
$maxScore = $results['hits']['max_score'];
$score = $results['hits']['hits'][0]['_score'];
$doc = $results['hits']['hits'][0]['_source'];
----
{zwsp} +
=== Bool Queries
Bool queries can be easily constructed using the client. For example, this query:
[source,shell]
----
curl -XGET 'localhost:9200/my_index/_search' -d '{
"query" : {
"bool" : {
"must": [
{
"match" : { "testField" : "abc" }
},
{
"match" : { "testField2" : "xyz" }
}
]
}
}
}'
----
{zwsp} +
Would be structured like this (Note the position of the square brackets):
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => [
[ 'match' => [ 'testField' => 'abc' ] ],
[ 'match' => [ 'testField2' => 'xyz' ] ],
]
]
]
]
];
$results = $client->search($params);
----
{zwsp} +
Notice that the `must` clause accepts an array of arrays. This will be serialized into an array of JSON objects internally,
so the final resulting output will be identical to the curl example. For more details about arrays vs objects in PHP,
see <<php_json_objects, Dealing with JSON Arrays and Objects in PHP>>.
=== A more complicated example
Let's construct a slightly more complicated example: a boolean query that contains both a filter and a query.
This is a very common activity in elasticsearch queries, so it will be a good demonstration.
The curl version of the query:
[source,shell]
----
curl -XGET 'localhost:9200/my_index/_search' -d '{
"query" : {
"bool" : {
"filter" : {
"term" : { "my_field" : "abc" }
},
"should" : {
"match" : { "my_other_field" : "xyz" }
}
}
}
}'
----
{zwsp} +
And in PHP:
[source,php]
----
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'filter' => [
'term' => [ 'my_field' => 'abc' ]
],
'should' => [
'match' => [ 'my_other_field' => 'xyz' ]
]
]
]
]
];
$results = $client->search($params);
----
{zwsp} +
=== Scrolling
The Scrolling functionality of Elasticsearch is used to paginate over many documents in a bulk manner, such as exporting
all the documents belonging to a single user. It is more efficient than regular search because it doesn't need to maintain
an expensive priority queue ordering the documents.
Scrolling works by maintaining a "point in time" snapshot of the index which is then used to page over.
This window allows consistent paging even if there is background indexing/updating/deleting. First, you execute a search
request with `scroll` enabled. This returns a "page" of documents, and a scroll_id which is used to continue
paginating through the hits.
More details about scrolling can be found in the https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html[Link: reference documentation].
This is an example which can be used as a template for more advanced operations:
[source,php]
----
$client = ClientBuilder::create()->build();
$params = [
'scroll' => '30s', // how long between scroll requests. should be small!
'size' => 50, // how many results *per shard* you want back
'index' => 'my_index',
'body' => [
'query' => [
'match_all' => new \stdClass()
]
]
];
// Execute the search
// The response will contain the first batch of documents
// and a scroll_id
$response = $client->search($params);
// Now we loop until the scroll "cursors" are exhausted
while (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {
// **
// Do your work here, on the $response['hits']['hits'] array
// **
// When done, get the new scroll_id
// You must always refresh your _scroll_id! It can change sometimes
$scroll_id = $response['_scroll_id'];
// Execute a Scroll request and repeat
$response = $client->scroll([
'scroll_id' => $scroll_id, //...using our previously obtained _scroll_id
'scroll' => '30s' // and the same timeout window
]
);
}
----
[[security]]
== Security
The Elasticsearch-PHP client supports two security features: HTTP Authentication and SSL encryption.
=== HTTP Authentication
If your Elasticsearch server is protected by HTTP Authentication, you need to provide the credentials to ES-PHP so
that requests can be authenticated server-side. Authentication credentials are provided as part of the host array
when instantiating the client:
[source,php]
----
$hosts = [
'http://user:pass@localhost:9200', // HTTP Basic Authentication
'http://user2:pass2@other-host.com:9200' // Different credentials on different host
];
$client = ClientBuilder::create()
->setHosts($hosts)
->build();
----
Credentials are provided per-host, which allows each host to have their own set of credentials. All requests sent to the
cluster will use the appropriate credentials depending on the node being talked to.
=== ApiKey Authentication
If your Elasticsearch cluster is secured by API keys as described https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html[here], you can use these values to connect the client with your cluster, as illustrated in the following code snippet.
[source,php]
----
$client = ClientBuilder::create()
->setApiKey('id', 'api_key') <1>
->build();
----
<1> ApiKey pair of `id` and `api_key` from the create API key response.
=== SSL Encryption
Configuring SSL is a little more complex. You need to identify if your certificate has been signed by a public
Certificate Authority (CA), or if it is a self-signed certificate.
[NOTE]
.A note on libcurl version
=================
If you believe the client is configured to correctly use SSL, but it simply is not working, check your libcurl
version. On certain platforms, various features may or may not be available depending on version number of libcurl.
For example, the `--cacert` option was not added to the OSX version of libcurl until version 7.37.1. The `--cacert`
option is equivalent to PHP's `CURLOPT_CAINFO` constant, meaning that custom certificate paths will not work on lower
versions.
If you are encountering problems, update your libcurl version and/or check the http://curl.haxx.se/changes.html[curl changelog].
=================
==== Public CA Certificates
If your certificate has been signed by a public Certificate Authority and your server has up-to-date root certificates,
you only need to use `https` in the host path. The client will automatically verify SSL certificates:
[source,php]
----
$hosts = [
'https://localhost:9200' <1>
];
$client = ClientBuilder::create()
->setHosts($hosts)
->build();
----
<1> Note that `https` is used, not `http`
If your server has out-dated root certificates, you may need to use a certificate bundle. For PHP clients, the best
way is to use https://github.com/composer/ca-bundle[composer/ca-bundle]. Once installed, you need to tell the client to
use your certificates instead of the system-wide bundle. To do this, specify the path to verify:
[source,php]
----
$hosts = ['https://localhost:9200'];
$caBundle = \Composer\CaBundle\CaBundle::getBundledCaBundlePath();
$client = ClientBuilder::create()
->setHosts($hosts)
->setSSLVerification($caBundle)
->build();
----
==== Self-signed Certificates
Self-signed certificates are certs that have not been signed by a public CA. They are signed by your own organization.
Self-signed certificates are often used for internal purposes, when you can securely spread the root certificate
yourself. It should not be used when being exposed to public consumers, since this leaves the client vulnerable to
man-in-the-middle attacks.
If you are using a self-signed certificate, you need to provide the certificate to the client. This is the same syntax
as specifying a new root bundle, but instead you point to your certificate:
[source,php]
----
$hosts = ['https://localhost:9200'];
$myCert = 'path/to/cacert.pem';
$client = ClientBuilder::create()
->setHosts($hosts)
->setSSLVerification($myCert)
->build();
----
=== Using Authentication with SSL
It is possible to use HTTP authentication with SSL. Simply specify `https` in the URI, configure SSL settings as
required and provide authentication credentials. For example, this snippet will authenticate using Basic HTTP auth
and a self-signed certificate:
[source,php]
----
$hosts = ['https://user:pass@localhost:9200'];
$myCert = 'path/to/cacert.pem';
$client = ClientBuilder::create()
->setHosts($hosts)
->setSSLVerification($myCert)
->build();
----
\ No newline at end of file
[[selectors]]
== Selectors
The connection pool maintains the list of connections, and decides when nodes should transition from alive to dead (and
vice versa). It has no logic to choose connections, however. That job belongs to the Selector class.
The selector's job is to return a single connection from a provided array of connections. Like the Connection Pool,
there are several implementations to choose from.
=== RoundRobinSelector (Default)
This selector returns connections in a round-robin fashion. Node #1 is selected on the first request, Node #2 on
the second request, etc. This ensures an even load of traffic across your cluster. Round-robin'ing happens on a
per-request basis (e.g. sequential requests go to different nodes).
The `RoundRobinSelector` is default, but if you wish to explicitily configure it you can do:
[source,php]
----
$client = ClientBuilder::create()
->setSelector('\Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector')
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== StickyRoundRobinSelector
This selector is "sticky", in that it prefers to reuse the same connection repeatedly. For example, Node #1 is chosen
on the first request. Node #1 will continue to be re-used for each subsequent request until that node fails. Upon failure,
the selector will round-robin to the next available node, then "stick" to that node.
This is an ideal strategy for many PHP scripts. Since PHP scripts are shared-nothing and tend to exit quickly, creating
new connections for each request is often a sub-optimal strategy and introduces a lot of overhead. Instead, it is
better to "stick" to a single connection for the duration of the script.
By default, this selector will randomize the hosts upon initialization, which will still guarantee an even distribution
of load across the cluster. It changes the round-robin dynamics from per-request to per-script.
If you are using <<future_mode>>, the "sticky" behavior of this selector will be non-ideal, since all parallel requests
will go to the same node instead of multiple nodes in your cluster. When using future mode, the default `RoundRobinSelector`
should be preferred.
If you wish to use this selector, you may do so with:
[source,php]
----
$client = ClientBuilder::create()
->setSelector('\Elasticsearch\ConnectionPool\Selectors\StickyRoundRobinSelector')
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== RandomSelector
This selector simply returns a random node, regardless of state. It is generally just for testing.
If you wish to use this selector, you may do so with:
[source,php]
----
$client = ClientBuilder::create()
->setSelector('\Elasticsearch\ConnectionPool\Selectors\RandomSelector')
->build();
----
Note that the implementation is specified via a namespace path to the class.
=== Custom Selector
You can implement your own custom selector. Custom selectors must implement `SelectorInterface`
[source,php]
----
namespace MyProject\Selectors;
use Elasticsearch\Connections\ConnectionInterface;
use Elasticsearch\ConnectionPool\Selectors\SelectorInterface
class MyCustomSelector implements SelectorInterface
{
/**
* Selects the first connection
*
* @param array $connections Array of Connection objects
*
* @return ConnectionInterface
*/
public function select($connections)
{
// code here
}
}
----
{zwsp} +
You can then use your custom selector either via object injection or namespace instantiation:
[source,php]
----
$mySelector = new MyCustomSelector();
$client = ClientBuilder::create()
->setSelector($mySelector) // object injection
->setSelector('\MyProject\Selectors\FirstSelector') // or namespace
->build();
----
[[serializers]]
== Serializers
The client has three serializers available. You will most likely never need
to change the serializer, unless you have special requirements or are
implementing a new protocol.
The job of the serializer is to encode the outgoing request body and decode
the incoming response body. In 99% of cases, this is a simple conversion
to/from JSON.
The default serializer is the `SmartSerializer`
=== SmartSerializer
==== Serialize()
The `SmartSerializer` inspects the data to be encoded. If the request body
is provided as a string, it is passed directly to Elasticsearch as a string.
This allows users to provide raw JSON, or raw strings for certain endpoints that
dont have structure (such as the Analyze endpoint).
If the data is an array, it is converted to json. If the data provided was an
empty array, the serializer manually converts the JSON from an empty array (`[]`)
to an empty object (`{}`) so that it is valid JSON for Elasticsearch request
bodies.
==== Deserialize()
When decoding the response body, the `SmartSerializer` introspects the
`content_type` headers to determine the appropriate encoding. If the data is
encoded as JSON, it is decoded into an array using `json_decode`. Otherwise,
it is returned as a string.
This functionality is required to cooperate with endpoints such as the `Cat`
endpoints, which return tabular text instead of JSON.
==== Selecting the SmartSerializer
The SmartSerializer is selected by default, but if you wish to manually configure it for explicitness, you can
do so by using the `setSerializer()` method on the ClientBuilder object:
[source,php]
----
$client = ClientBuilder::create()
->setSerializer('\Elasticsearch\Serializers\SmartSerializer');
->build();
----
Note that the serializer is configured by specifying a namespace path to the serializer.
=== ArrayToJSONSerializer
==== Serialize()
The `ArrayToJSONSerializer` inspects the data to be encoded. If the request body
is provided as a string, it is passed directly to Elasticsearch as a string.
This allows users to provide raw JSON, or raw strings for certain endpoints that
dont have structure (such as the Analyze endpoint).
If the data is an array, it is converted to json. If the data provided was an
empty array, the serializer manually converts the JSON from an empty array (`[]`)
to an empty object (`{}`) so that it is valid JSON for Elasticsearch request
bodies.
==== Deserialize()
When decoding the response body, everything is decoded to JSON from JSON. If
the data is not valid JSON, `null` will be returned.
==== Selecting the ArrayToJSONSerializer
You can select `ArrayToJSONSerializer` by using the `setSerializer()` method on the ClientBuilder object:
[source,php]
----
$client = ClientBuilder::create()
->setSerializer('\Elasticsearch\Serializers\ArrayToJSONSerializer');
->build();
----
Note that the serializer is configured by specifying a namespace path to the serializer.
=== EverythingToJSONSerializer
==== Serialize()
The `EverythingToJSONSerializer` tries to convert everything to JSON.
If the data provided was an empty array, the serializer manually converts the
JSON from an empty array (`[]`) to an empty object (`{}`) so that it is valid
JSON for Elasticsearch request bodies.
If the data was not an array and/or not convertible to JSON, the method returns
`null`.
==== Deserialize()
When decoding the response body, everything is decoded to JSON from JSON. If
the data is not valid JSON, `null` will be returned.
==== Selecting the EverythingToJSONSerializer
You can select `EverythingToJSONSerializer` by using the `setSerializer()` method on the ClientBuilder object:
[source,php]
----
$client = ClientBuilder::create()
->setSerializer('\Elasticsearch\Serializers\EverythingToJSONSerializer');
->build();
----
Note that the serializer is configured by specifying a namespace path to the serializer.
=== Implementing your own Serializer
If you want to use your own custom serializer, you need to implement the `SerializerInterface` interface. Please
keep in mind that the client uses a single Serializer object for all endpoints and all connections.
[source,php]
----
class MyCustomSerializer implements SerializerInterface
{
/**
* Serialize request body
*
* @param string|array $data Request body
*
* @return string
*/
public function serialize($data)
{
// code here
}
/**
* Deserialize response body
*
* @param string $data Response body
* @param array $headers Response Headers
*
* @return array|string
*/
public function deserialize($data, $headers)
{
// code here
}
}
----
{zwsp} +
To then use your custom serializer, you can specify the namespace path in the `setSerializer()` method of the ClientBuilder
object:
[source,php]
----
$client = ClientBuilder::create()
->setSerializer('\MyProject\Serializers\MyCustomSerializer');
->build();
----
Alternatively, if your serializer has a constructor or further initialization that should occur before given to the
client, you can instantiate an object and provide that instead:
[source,php]
----
$mySerializer = new MyCustomSerializer($a, $b, $c);
$mySerializer->setFoo("bar");
$client = ClientBuilder::create()
->setSerializer($mySerializer);
->build();
----
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment