From 9e12c40ae30b4c4c6b22c33fcf228f87173571b0 Mon Sep 17 00:00:00 2001 From: Han Speerstra Date: Mon, 25 Jan 2021 20:21:40 +0100 Subject: [PATCH] Add script_fields support --- README.md | 14 +++++++++ src/Search/SearchRequest.php | 11 +++++++ tests/Unit/Search/SearchRequestTest.php | 38 +++++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/README.md b/README.md index f1e8840..0bc45ab 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,20 @@ $request->setTrackTotalHits(true); // track scores $request->setTrackScores(true); +// script fields +$request->setScriptFields([ + 'my_doubled_field' => [ + 'script' => [ + 'lang' => 'painless', + 'source' => 'doc[params.field] * params.multiplier', + 'params' => [ + 'field' => 'my_field', + 'multiplier' => 2, + ], + ], + ], +]); + // boost indices $request->setIndicesBoost([ ['my-alias' => 1.4], diff --git a/src/Search/SearchRequest.php b/src/Search/SearchRequest.php index 0f39b49..99d48bb 100644 --- a/src/Search/SearchRequest.php +++ b/src/Search/SearchRequest.php @@ -58,6 +58,10 @@ final class SearchRequest implements ArrayableInterface * @var bool|null */ private $trackScores; + /** + * @var array|null + */ + private $scriptFields; public function __construct(array $query) { @@ -142,6 +146,12 @@ public function setTrackScores(bool $trackScores): self return $this; } + public function setScriptFields(array $scriptFields): self + { + $this->scriptFields = $scriptFields; + return $this; + } + public function toArray(): array { $request = [ @@ -161,6 +171,7 @@ public function toArray(): array 'trackTotalHits' => 'track_total_hits', 'indicesBoost' => 'indices_boost', 'trackScores' => 'track_scores', + 'scriptFields' => 'script_fields', ] as $property => $requestParameter) { if (isset($this->$property)) { $request[$requestParameter] = $this->$property; diff --git a/tests/Unit/Search/SearchRequestTest.php b/tests/Unit/Search/SearchRequestTest.php index a7af6ed..076b8eb 100644 --- a/tests/Unit/Search/SearchRequestTest.php +++ b/tests/Unit/Search/SearchRequestTest.php @@ -296,4 +296,42 @@ public function test_array_casting_with_track_scores(): void 'track_scores' => true, ], $request->toArray()); } + + public function test_array_casting_with_script_fields(): void + { + $request = new SearchRequest([ + 'match_all' => new stdClass(), + ]); + + $request->setScriptFields([ + 'my_doubled_field' => [ + 'script' => [ + 'lang' => 'painless', + 'source' => 'doc[params.field] * params.multiplier', + 'params' => [ + 'field' => 'my_field', + 'multiplier' => 2, + ], + ], + ], + ]); + + $this->assertEquals([ + 'query' => [ + 'match_all' => new stdClass(), + ], + 'script_fields' => [ + 'my_doubled_field' => [ + 'script' => [ + 'lang' => 'painless', + 'source' => 'doc[params.field] * params.multiplier', + 'params' => [ + 'field' => 'my_field', + 'multiplier' => 2, + ], + ], + ], + ], + ], $request->toArray()); + } }