Class yii\sphinx\Query

Inheritanceyii\sphinx\Query » yii\db\Query
Subclassesyii\sphinx\ActiveQuery
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-sphinx/blob/master/src/Query.php

Query represents a SELECT SQL statement.

Query provides a set of methods to facilitate the specification of different clauses in a SELECT statement. These methods can be chained together.

By calling createCommand(), we can get a yii\sphinx\Command instance which can be further used to perform/execute the Sphinx query.

For example,

$query = new Query();
$query->select('id, group_id')
    ->from('idx_item')
    ->limit(10);
// build and execute the query
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();

Since Sphinx does not store the original indexed text, the snippets for the rows in query result should be build separately via another query. You can simplify this workflow using snippetCallback().

Warning: even if you do not set any query limit, implicit LIMIT 0,20 is present by default!

Public Properties

Hide inherited properties

Property Type Description Defined By
$connection yii\sphinx\Connection Sphinx connection instance. yii\sphinx\Query
$facets array Facet search specifications. yii\sphinx\Query
$groupLimit integer Groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
$match string|\yii\db\Expression Text, which should be searched in fulltext mode. yii\sphinx\Query
$options array Per-query options in format: optionName => optionValue They will compose OPTION clause. yii\sphinx\Query
$showMeta boolean|string|\yii\db\Expression Whether to automatically perform 'SHOW META' query against main one. yii\sphinx\Query
$snippetCallback callable PHP callback, which should be used to fetch source data for the snippets. yii\sphinx\Query
$snippetOptions array Query options for the call snippet. yii\sphinx\Query
$within string WITHIN GROUP ORDER BY clause. yii\sphinx\Query

Public Methods

Hide inherited methods

Method Description Defined By
addFacets() Adds additional FACET part of the query. yii\sphinx\Query
addOptions() Adds additional query options. yii\sphinx\Query
addWithin() Adds additional WITHIN GROUP ORDER BY columns to the query. yii\sphinx\Query
create() Creates a new Query object and copies its property values from an existing one. yii\sphinx\Query
createCommand() Creates a Sphinx command that can be used to execute this query. yii\sphinx\Query
facets() Sets FACET part of the query. yii\sphinx\Query
getConnection() yii\sphinx\Query
getTablesUsedInFrom() yii\sphinx\Query
groupLimit() Sets groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
innerJoin() yii\sphinx\Query
join() yii\sphinx\Query
leftJoin() yii\sphinx\Query
match() Sets the fulltext query text. This text will be composed into MATCH operator inside the WHERE clause. yii\sphinx\Query
one() yii\sphinx\Query
options() Sets the query options. yii\sphinx\Query
populate() yii\sphinx\Query
rightJoin() yii\sphinx\Query
search() Executes the query and returns the complete search result including e.g. hits, facets. yii\sphinx\Query
setConnection() yii\sphinx\Query
showMeta() Sets whether to automatically perform 'SHOW META' for the search query. yii\sphinx\Query
snippetCallback() Sets the PHP callback, which should be used to retrieve the source data for the snippets building. yii\sphinx\Query
snippetOptions() Sets the call snippets query options. yii\sphinx\Query
within() Sets the WITHIN GROUP ORDER BY part of the query. yii\sphinx\Query

Protected Methods

Hide inherited methods

Method Description Defined By
callSnippets() Builds a snippets from provided source data. yii\sphinx\Query
callSnippetsInternal() Builds a snippets from provided source data by the given index. yii\sphinx\Query
defaultConnection() yii\sphinx\Query
fillUpSnippets() Fills the query result rows with the snippets built from source determined by snippetCallback() result. yii\sphinx\Query
queryScalar() yii\sphinx\Query

Property Details

Hide inherited properties

$connection public property

Sphinx connection instance.

$facets public property

Facet search specifications. For example:

[
    'group_id',
    'brand_id' => [
        'order' => ['COUNT(*)' => SORT_ASC],
    ],
    'price' => [
        'select' => 'INTERVAL(price,200,400,600,800) AS price',
        'order' => ['FACET()' => SORT_ASC],
    ],
    'name_in_json' => [
        'select' => [new Expression('json_attr.name AS name_in_json')],
    ],
]

You need to use search() method in order to fetch facet results.

Note: if you specify custom select for the facet, ensure facet name has corresponding column inside it.

public array $facets = []
$groupLimit public property (available since version 2.0.6)

Groups limit: to return (no more than) N top matches for each group. This option will take effect only if groupBy is set.

public integer $groupLimit null
$match public property

Text, which should be searched in fulltext mode. This value will be composed into MATCH operator inside the WHERE clause. Note: this value will be processed by yii\sphinx\Connection::escapeMatchValue(), if you need to compose complex match condition use Expression, see match() for details.

public string|\yii\db\Expression $match null
$options public property

Per-query options in format: optionName => optionValue They will compose OPTION clause. This is a Sphinx specific extension that lets you control a number of per-query options.

public array $options null
$showMeta public property

Whether to automatically perform 'SHOW META' query against main one. You may set this value to be string or Expression instance, in this case its value will be used as 'LIKE' condition for 'SHOW META' statement. You need to use search() method in order to fetch 'meta' results.

public boolean|string|\yii\db\Expression $showMeta null
$snippetCallback public property

PHP callback, which should be used to fetch source data for the snippets. Such callback will receive array of query result rows as an argument and must return the array of snippet source strings in the order, which match one of incoming rows. For example:

$query = new Query();
$query->from('idx_item')
    ->match('pencil')
    ->snippetCallback(function ($rows) {
        $result = [];
        foreach ($rows as $row) {
            $result[] = file_get_contents('/path/to/index/files/' . $row['id'] . '.txt');
        }
        return $result;
    })
    ->all();
public callable $snippetCallback null
$snippetOptions public property

Query options for the call snippet.

public array $snippetOptions null
$within public property

WITHIN GROUP ORDER BY clause. This is a Sphinx specific extension that lets you control how the best row within a group will to be selected. The possible value matches the orderBy one.

public string $within null

Method Details

Hide inherited methods

addFacets() public method

Adds additional FACET part of the query.

public $this addFacets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

                public function addFacets($facets)
{
    if (is_array($this->facets)) {
        $this->facets = array_merge($this->facets, $facets);
    } else {
        $this->facets = $facets;
    }
    return $this;
}

            
addOptions() public method

Adds additional query options.

See also options().

public $this addOptions ( $options )
$options array

Query options in format: optionName => optionValue

return $this

The query object itself

                public function addOptions($options)
{
    if (is_array($this->options)) {
        $this->options = array_merge($this->options, $options);
    } else {
        $this->options = $options;
    }
    return $this;
}

            
addWithin() public method

Adds additional WITHIN GROUP ORDER BY columns to the query.

See also within().

public $this addWithin ( $columns )
$columns string|array

The columns (and the directions) to find best row within a group. Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. ['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).

return $this

The query object itself

                public function addWithin($columns)
{
    $columns = $this->normalizeOrderBy($columns);
    if ($this->within === null) {
        $this->within = $columns;
    } else {
        $this->within = array_merge($this->within, $columns);
    }
    return $this;
}

            
callSnippets() protected method

Builds a snippets from provided source data.

protected array callSnippets ( array $source )
$source array

The source data to extract a snippet from.

return array

Snippets list.

throws \yii\base\InvalidCallException

in case match() is not specified.

                protected function callSnippets(array $source)
{
    return $this->callSnippetsInternal($source, $this->from[0]);
}

            
callSnippetsInternal() protected method

Builds a snippets from provided source data by the given index.

protected array callSnippetsInternal ( array $source, $from )
$source array

The source data to extract a snippet from.

$from string

Name of the source index.

return array

Snippets list.

throws \yii\base\InvalidCallException

in case match() is not specified.

                protected function callSnippetsInternal(array $source, $from)
{
    $connection = $this->getConnection();
    $match = $this->match;
    if ($match === null) {
        throw new InvalidCallException('Unable to call snippets: "' . $this->className() . '::match" should be specified.');
    }
    return $connection->createCommand()
        ->callSnippets($from, $source, $match, $this->snippetOptions)
        ->queryColumn();
}

            
create() public static method

Creates a new Query object and copies its property values from an existing one.

The properties being copies are the ones to be used by query builders.

public static yii\sphinx\Query create ( $from )
$from yii\sphinx\Query

The source query object

return yii\sphinx\Query

The new Query object

                public static function create($from)
{
    return new self([
        'where' => $from->where,
        'limit' => $from->limit,
        'offset' => $from->offset,
        'orderBy' => $from->orderBy,
        'indexBy' => $from->indexBy,
        'select' => $from->select,
        'selectOption' => $from->selectOption,
        'distinct' => $from->distinct,
        'from' => $from->from,
        'groupBy' => $from->groupBy,
        'join' => $from->join,
        'having' => $from->having,
        'union' => $from->union,
        'params' => $from->params,
        // Sphinx specifics :
        'groupLimit' => $from->groupLimit,
        'options' => $from->options,
        'within' => $from->within,
        'match' => $from->match,
        'snippetCallback' => $from->snippetCallback,
        'snippetOptions' => $from->snippetOptions,
    ]);
}

            
createCommand() public method

Creates a Sphinx command that can be used to execute this query.

public yii\sphinx\Command createCommand ( $db null )
$db yii\sphinx\Connection

The Sphinx connection used to generate the SQL statement. If this parameter is not given, the sphinx application component will be used.

return yii\sphinx\Command

The created Sphinx command instance.

                public function createCommand($db = null)
{
    $this->setConnection($db);
    $db = $this->getConnection();
    list ($sql, $params) = $db->getQueryBuilder()->build($this);
    return $db->createCommand($sql, $params);
}

            
defaultConnection() protected method

protected yii\sphinx\Connection defaultConnection ( )
return yii\sphinx\Connection

Default connection value.

                protected function defaultConnection()
{
    return Yii::$app->get('sphinx');
}

            
facets() public method

Sets FACET part of the query.

public $this facets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

                public function facets($facets)
{
    $this->facets = $facets;
    return $this;
}

            
fillUpSnippets() protected method

Fills the query result rows with the snippets built from source determined by snippetCallback() result.

protected array|yii\sphinx\ActiveRecord[] fillUpSnippets ( $rows )
$rows array

Raw query result rows.

return array|yii\sphinx\ActiveRecord[]

Query result rows with filled up snippets.

                protected function fillUpSnippets($rows)
{
    if ($this->snippetCallback === null || empty($rows)) {
        return $rows;
    }
    $snippetSources = call_user_func($this->snippetCallback, $rows);
    $snippets = $this->callSnippets($snippetSources);
    $snippetKey = 0;
    foreach ($rows as $key => $row) {
        $rows[$key]['snippet'] = $snippets[$snippetKey];
        $snippetKey++;
    }
    return $rows;
}

            
getConnection() public method

public yii\sphinx\Connection getConnection ( )
return yii\sphinx\Connection

Sphinx connection instance

                public function getConnection()
{
    if ($this->_connection === null) {
        $this->_connection = $this->defaultConnection();
    }
    return $this->_connection;
}

            
getTablesUsedInFrom() public method (available since version 2.0.9)

public void getTablesUsedInFrom ( )

                public function getTablesUsedInFrom()
{
    // feature not supported, returning a stub:
    return [];
}

            
groupLimit() public method (available since version 2.0.6)

Sets groups limit: to return (no more than) N top matches for each group.

This option will take effect only if groupBy is set.

public $this groupLimit ( $limit )
$limit integer

Group limit.

return $this

The query object itself.

                public function groupLimit($limit)
{
    $this->groupLimit = $limit;
    return $this;
}

            
innerJoin() public method

public void innerJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function innerJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
join() public method

public void join ( $type, $table, $on '', $params = [] )
$type
$table
$on
$params

                public function join($type, $table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
leftJoin() public method

public void leftJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function leftJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
match() public method

Sets the fulltext query text. This text will be composed into MATCH operator inside the WHERE clause.

Note: this value will be processed by yii\sphinx\Connection::escapeMatchValue(), if you need to compose complex match condition use Expression:

$query = new Query();
$query->from('my_index')
    ->match(new Expression(':match', ['match' => '@(content) ' . Yii::$app->sphinx->escapeMatchValue($matchValue)]))
    ->all();
public $this match ( $query )
$query string|\yii\db\Expression|yii\sphinx\MatchExpression

Fulltext query text.

return $this

The query object itself.

                public function match($query)
{
    $this->match = $query;
    return $this;
}

            
one() public method

public void one ( $db null )
$db

                public function one($db = null)
{
    $row = parent::one($db);
    if ($row !== false) {
        list ($row) = $this->fillUpSnippets([$row]);
    }
    return $row;
}

            
options() public method

Sets the query options.

See also addOptions().

public $this options ( $options )
$options array

Query options in format: optionName => optionValue

return $this

The query object itself

                public function options($options)
{
    $this->options = $options;
    return $this;
}

            
populate() public method

public void populate ( $rows )
$rows

                public function populate($rows)
{
    return parent::populate($this->fillUpSnippets($rows));
}

            
queryScalar() protected method

protected void queryScalar ( $selectExpression, $db )
$selectExpression
$db

                protected function queryScalar($selectExpression, $db)
{
    if (!empty($this->emulateExecution)) {
        return null;
    }
    $select = $this->select;
    $limit = $this->limit;
    $offset = $this->offset;
    $this->select = [$selectExpression];
    $this->limit = null;
    $this->offset = null;
    $command = $this->createCommand($db);
    $this->select = $select;
    $this->limit = $limit;
    $this->offset = $offset;
    if (empty($this->groupBy) && empty($this->union) && !$this->distinct) {
        return $command->queryScalar();
    }
    return (new Query)->select([$selectExpression])
        ->from(['c' => $this])
        ->createCommand($command->db)
        ->queryScalar();
}

            
rightJoin() public method

public void rightJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function rightJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
search() public method

Executes the query and returns the complete search result including e.g. hits, facets.

public array search ( $db null )
$db yii\sphinx\Connection

The Sphinx connection used to generate the SQL statement.

return array

The query results.

                public function search($db = null)
{
    if (!empty($this->emulateExecution)) {
        return [
            'hits' => [],
            'facets' => [],
            'meta' => [],
        ];
    }
    $command = $this->createCommand($db);
    $dataReader = $command->query();
    $rawRows = $dataReader->readAll();
    $facets = [];
    foreach ($this->facets as $facetKey => $facetValue) {
        $dataReader->nextResult();
        $rawFacetResults = $dataReader->readAll();
        if (is_numeric($facetKey)) {
            $facet = [
                'name' => $facetValue,
                'value' => $facetValue,
                'count' => 'count(*)',
            ];
        } else {
            $facet = array_merge(
                [
                    'name' => $facetKey,
                    'value' => $facetKey,
                    'count' => 'count(*)',
                ],
                $facetValue
            );
        }
        foreach ($rawFacetResults as $rawFacetResult) {
            $rawFacetResult['value'] = isset($rawFacetResult[strtolower($facet['value'])]) ? $rawFacetResult[strtolower($facet['value'])] : null;
            $rawFacetResult['count'] = $rawFacetResult[$facet['count']];
            $facets[$facet['name']][] = $rawFacetResult;
        }
    }
    $meta = [];
    if (!empty($this->showMeta)) {
        $dataReader->nextResult();
        $rawMetaResults = $dataReader->readAll();
        foreach ($rawMetaResults as $rawMetaResult) {
            $meta[$rawMetaResult['Variable_name']] = $rawMetaResult['Value'];
        }
    }
    // rows should be populated after all data read from cursor, avoiding possible 'unbuffered query' error
    $rows = $this->populate($rawRows);
    return [
        'hits' => $rows,
        'facets' => $facets,
        'meta' => $meta,
    ];
}

            
setConnection() public method

public $this setConnection ( $connection )
$connection yii\sphinx\Connection

Sphinx connection instance

return $this

The query object itself

                public function setConnection($connection)
{
    $this->_connection = $connection;
    return $this;
}

            
showMeta() public method

Sets whether to automatically perform 'SHOW META' for the search query.

See also showMeta().

public $this showMeta ( $showMeta )
$showMeta boolean|string|\yii\db\Expression

Whether to automatically perform 'SHOW META'

return $this

The query object itself

                public function showMeta($showMeta)
{
    $this->showMeta = $showMeta;
    return $this;
}

            
snippetCallback() public method

Sets the PHP callback, which should be used to retrieve the source data for the snippets building.

See also snippetCallback().

public $this snippetCallback ( $callback )
$callback callable

PHP callback, which should be used to fetch source data for the snippets.

return $this

The query object itself

                public function snippetCallback($callback)
{
    $this->snippetCallback = $callback;
    return $this;
}

            
snippetOptions() public method

Sets the call snippets query options.

See also snippetCallback().

public $this snippetOptions ( $options )
$options array

Call snippet options in format: option_name => option_value

return $this

The query object itself

                public function snippetOptions($options)
{
    $this->snippetOptions = $options;
    return $this;
}

            
within() public method

Sets the WITHIN GROUP ORDER BY part of the query.

See also addWithin().

public $this within ( $columns )
$columns string|array

The columns (and the directions) to find best row within a group. Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. ['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).

return $this

The query object itself

                public function within($columns)
{
    $this->within = $this->normalizeOrderBy($columns);
    return $this;
}