Skip to content

Commit

Permalink
Allow to check if a response has results or not, easily?
Browse files Browse the repository at this point in the history
  • Loading branch information
romainruaud committed Jun 14, 2024
1 parent 0aa09bc commit a097b51
Showing 1 changed file with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ class QueryResponse implements ResponseInterface
*/
protected $aggregations;

/**
* @var array
*/
protected $totalHits = [];

/**
* Constructor
*
Expand Down Expand Up @@ -85,6 +90,39 @@ public function getAggregations()
return $this->aggregations;
}

/**
* Get total hits as given by the Elasticsearch server.
* Can be useful to check if there's been real hits, eg when querying with size:0 and track_total_hits:true
* we can receive response like :
*
* "total": {
* "value": 0,
* "relation": "gte"
* }
*
* @return array
*/
public function getTotalHits()
{
return $this->totalHits;
}

/**
* Return true if the responses has results.
* We cannot trust only count() for this.
*
* @return bool
*/
public function hasResults()
{
if (isset($this->totalHits['relation']) && (isset($this->totalHits['value']))) {
return ($this->totalHits['relation'] === 'gte' && $this->totalHits['value'] >= 0)
|| ($this->totalHits['relation'] === 'eq' && $this->totalHits['value'] > 0);
}

return $this->count > 0;
}

/**
* Build buckets from raw search response.
*
Expand Down Expand Up @@ -128,6 +166,8 @@ private function prepareDocuments(array $searchResponse, DocumentFactory $docume
? $searchResponse['hits']['total']['value']
: $searchResponse['hits']['total'];
// @codingStandardsIgnoreEnd

$this->totalHits = $searchResponse['hits']['total'];
}
}
}

0 comments on commit a097b51

Please sign in to comment.