yii\elasticsearch\Query::scalar PHP Method

scalar() public method

The value returned will be the specified field in the first document of the query results.
public scalar ( string $field, Connection $db = null ) : string
$field string name of the attribute to select
$db Connection the database connection used to execute the query. If this parameter is not given, the `elasticsearch` application component will be used.
return string the value of the specified attribute in the first record of the query result. Null is returned if the query result is empty or the field does not exist.
    public function scalar($field, $db = null)
    {
        $record = self::one($db);
        if ($record !== false) {
            if ($field === '_id') {
                return $record['_id'];
            } elseif (isset($record['_source'][$field])) {
                return $record['_source'][$field];
            } elseif (isset($record['fields'][$field])) {
                return count($record['fields'][$field]) == 1 ? reset($record['fields'][$field]) : $record['fields'][$field];
            }
        }
        return null;
    }