From 7ab7a8389632a8792e08d35bf78f031ce83be936 Mon Sep 17 00:00:00 2001 From: Haydar Kulekci Date: Fri, 17 Nov 2023 15:13:59 +0300 Subject: [PATCH] added boost field setter and getter for Knn Search --- src/Knn/Knn.php | 22 +++++++++++++++++++++- tests/Functional/Knn/KnnTest.php | 19 ++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Knn/Knn.php b/src/Knn/Knn.php index fe18b0b5..07b6489a 100644 --- a/src/Knn/Knn.php +++ b/src/Knn/Knn.php @@ -39,7 +39,7 @@ class Knn implements BuilderInterface private $numCandidates; /** - * @var int + * @var float|null */ private $boost; @@ -153,6 +153,22 @@ public function setSimilarity(float $similarity): void $this->similarity = $similarity; } + /** + * @return float|null + */ + public function getBoost(): ?float + { + return $this->boost; + } + + /** + * @param float $boost + */ + public function setBoost(float $boost): void + { + $this->boost = $boost; + } + /** * @return BuilderInterface|null */ @@ -193,6 +209,10 @@ public function toArray() $output['similarity'] = $this->getSimilarity(); } + if ($this->getBoost()) { + $output['boost'] = $this->getBoost(); + } + if ($this->getFilter()) { $output['filter'] = $this->getFilter()->toArray(); } diff --git a/tests/Functional/Knn/KnnTest.php b/tests/Functional/Knn/KnnTest.php index 8eae63fc..9aac8566 100644 --- a/tests/Functional/Knn/KnnTest.php +++ b/tests/Functional/Knn/KnnTest.php @@ -6,7 +6,8 @@ namespace ONGR\ElasticsearchDSL\Tests\Functional\Knn; -use ONGR\ElasticsearchDSL\Aggregation\Bucketing\DateHistogramAggregation; +use Composer\InstalledVersions; +use Elastic\Elasticsearch\Client; use ONGR\ElasticsearchDSL\Knn\Knn; use ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery; use ONGR\ElasticsearchDSL\Search; @@ -82,4 +83,20 @@ public function testKnnSearchWithFilter(): void $this->assertCount(1, $results['hits']['hits']); $this->assertEquals('doc_3', $results['hits']['hits'][0]['_id']); } + + /** + * Match all test + */ + public function testMultipleKnnSearchWithBoost(): void + { + $knn1 = new Knn('vector_field', [1, 2, 3], 1, 1); + $knn1->setFilter(new TermQuery('label', 2)); + $knn1->setBoost(0.5); + + $search = new Search(); + $search->addKnn($knn1); + $results = $this->executeSearch($search, true); + $this->assertCount(1, $results['hits']['hits']); + $this->assertEquals('doc_3', $results['hits']['hits'][0]['_id']); + } }