Class yii\sphinx\Query

Inheritanceyii\sphinx\Query » yii\db\Query » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable, yii\db\ExpressionInterface, yii\db\QueryInterface
Uses Traitsyii\db\QueryTrait
Subclassesyii\sphinx\ActiveQuery
Available since version2.0
Source Code https://github.com/yiisoft/yii2-sphinx/blob/master/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

PropertyTypeDescriptionDefined By
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$connection yii\sphinx\Connection Sphinx connection instance yii\sphinx\Query
$distinct boolean Whether to select distinct rows of data only. yii\db\Query
$emulateExecution boolean Whether to emulate the actual query execution, returning empty or false results. yii\db\QueryTrait
$facets array Facet search specifications. yii\sphinx\Query
$from array The table(s) to be selected from. yii\db\Query
$groupBy array How to group the query results. yii\db\Query
$groupLimit integer Groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
$having string|array|yii\db\ExpressionInterface The condition to be applied in the GROUP BY clause. yii\db\Query
$indexBy string|callable The name of the column by which the query results should be indexed by. yii\db\QueryTrait
$join array How to join with other tables. yii\db\Query
$limit integer|yii\db\ExpressionInterface Maximum number of records to be returned. yii\db\QueryTrait
$match string|yii\db\Expression Text, which should be searched in fulltext mode. yii\sphinx\Query
$offset integer|yii\db\ExpressionInterface Zero-based offset from where the records are to be returned. yii\db\QueryTrait
$options array Per-query options in format: optionName => optionValue They will compose OPTION clause. yii\sphinx\Query
$orderBy array How to sort the query results. yii\db\QueryTrait
$params array List of query parameter values indexed by parameter placeholders. yii\db\Query
$queryCacheDependency yii\caching\Dependency The dependency to be associated with the cached query result for this query yii\db\Query
$queryCacheDuration integer|true The default number of seconds that query results can remain valid in cache. yii\db\Query
$select array The columns being selected. yii\db\Query
$selectOption string Additional option that should be appended to the 'SELECT' keyword. yii\db\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
$tablesUsedInFrom string[] Table names indexed by aliases yii\sphinx\Query
$union array This is used to construct the UNION clause(s) in a SQL statement. yii\db\Query
$where string|array|yii\db\ExpressionInterface Query condition. yii\db\QueryTrait
$within string WITHIN GROUP ORDER BY clause. yii\sphinx\Query

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__toString() Returns the SQL representation of Query yii\db\Query
__unset() Sets a component property to be null. yii\base\Component
addFacets() Adds additional FACET part of the query. yii\sphinx\Query
addGroupBy() Adds additional group-by columns to the existing ones. yii\db\Query
addOptions() Adds additional query options. yii\sphinx\Query
addOrderBy() Adds additional ORDER BY columns to the query. yii\db\QueryTrait
addParams() Adds additional parameters to be bound to the query. yii\db\Query
addSelect() Add more columns to the SELECT part of the query. yii\db\Query
addWithin() Adds additional WITHIN GROUP ORDER BY columns to the query. yii\sphinx\Query
all() Executes the query and returns all results as an array. yii\sphinx\Query
andFilterCompare() Adds a filtering condition for a specific column and allow the user to choose a filter operator. yii\db\Query
andFilterHaving() Adds an additional HAVING condition to the existing one but ignores empty operands. yii\db\Query
andFilterWhere() Adds an additional WHERE condition to the existing one but ignores empty operands. yii\db\QueryTrait
andHaving() Adds an additional HAVING condition to the existing one. yii\db\Query
andWhere() Adds an additional WHERE condition to the existing one. yii\db\QueryTrait
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
average() Returns the average of the specified column values. yii\db\Query
batch() Starts a batch query. yii\db\Query
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
cache() Enables query cache for this Query. yii\db\Query
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
column() Executes the query and returns the first column of the result. yii\db\Query
count() Returns the number of records. yii\db\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
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
distinct() Sets the value indicating whether to SELECT DISTINCT or not. yii\db\Query
each() Starts a batch query and retrieves data row by row. yii\db\Query
emulateExecution() Sets whether to emulate query execution, preventing any interaction with data storage. yii\db\QueryTrait
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
exists() Returns a value indicating whether the query result contains any row of data. yii\db\Query
facets() Sets FACET part of the query. yii\sphinx\Query
filterHaving() Sets the HAVING part of the query but ignores empty operands. yii\db\Query
filterWhere() Sets the WHERE part of the query but ignores empty operands. yii\db\QueryTrait
from() Sets the FROM part of the query. yii\db\Query
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getConnection() yii\sphinx\Query
getTablesUsedInFrom() Returns table names used in from() indexed by aliases. yii\sphinx\Query
groupBy() Sets the GROUP BY part of the query. yii\db\Query
groupLimit() Sets groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
having() Sets the HAVING part of the query. yii\db\Query
indexBy() Sets the indexBy() property. yii\db\QueryTrait
init() Initializes the object. yii\base\BaseObject
innerJoin() Appends an INNER JOIN part to the query. yii\sphinx\Query
join() Appends a JOIN part to the query. yii\sphinx\Query
leftJoin() Appends a LEFT OUTER JOIN part to the query. yii\sphinx\Query
limit() Sets the LIMIT part of the query. yii\db\QueryTrait
match() Sets the fulltext query text. This text will be composed into MATCH operator inside the WHERE clause. yii\sphinx\Query
max() Returns the maximum of the specified column values. yii\db\Query
min() Returns the minimum of the specified column values. yii\db\Query
noCache() Disables query cache for this Query. yii\db\Query
off() Detaches an existing event handler from this component. yii\base\Component
offset() Sets the OFFSET part of the query. yii\db\QueryTrait
on() Attaches an event handler to an event. yii\base\Component
one() Executes the query and returns a single row of result. yii\sphinx\Query
options() Sets the query options. yii\sphinx\Query
orFilterHaving() Adds an additional HAVING condition to the existing one but ignores empty operands. yii\db\Query
orFilterWhere() Adds an additional WHERE condition to the existing one but ignores empty operands. yii\db\QueryTrait
orHaving() Adds an additional HAVING condition to the existing one. yii\db\Query
orWhere() Adds an additional WHERE condition to the existing one. yii\db\QueryTrait
orderBy() Sets the ORDER BY part of the query. yii\db\QueryTrait
params() Sets the parameters to be bound to the query. yii\db\Query
populate() Converts the raw query results into the format as specified by this query. yii\db\Query
prepare() Prepares for building SQL. yii\db\Query
rightJoin() Appends a RIGHT OUTER JOIN part to the query. yii\sphinx\Query
scalar() Returns the query result as a scalar value. yii\db\Query
search() Executes the query and returns the complete search result including e.g. hits, facets. yii\sphinx\Query
select() Sets the SELECT part of the query. yii\db\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
sum() Returns the sum of the specified column values. yii\db\Query
trigger() Triggers an event. yii\base\Component
union() Appends a SQL statement using UNION operator. yii\db\Query
where() Sets the WHERE part of the query. yii\db\QueryTrait
within() Sets the WITHIN GROUP ORDER BY part of the query. yii\sphinx\Query

Protected Methods

Hide inherited methods

MethodDescriptionDefined 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
cleanUpTableNames() Clean up table names and aliases Both aliases and names are enclosed into {{ and }}. yii\db\Query
defaultConnection() yii\sphinx\Query
fillUpSnippets() Fills the query result rows with the snippets built from source determined by snippetCallback() result. yii\sphinx\Query
filterCondition() Removes empty operands from the given query condition. yii\db\QueryTrait
getUnaliasedColumnsFromSelect() yii\db\Query
getUniqueColumns() Returns unique column names excluding duplicates. yii\db\Query
isEmpty() Returns a value indicating whether the give value is "empty". yii\db\QueryTrait
normalizeOrderBy() Normalizes format of ORDER BY data. yii\db\QueryTrait
queryScalar() Queries a scalar value by setting select() first. yii\sphinx\Query
setCommandCache() Sets $command cache, if this query has enabled caching. yii\db\Query

Property Details

$connection public property

Sphinx connection instance

public yii\sphinx\Connection getConnection ( )
public $this setConnection ( $connection )
$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 yii\db\Expression, see match() for details.

$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 yii\db\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.

$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
$tablesUsedInFrom public read-only property

Table names indexed by aliases

$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

addFacets() public method

Adds additional FACET part of the query.

public $this addFacets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

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

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

all() public method

Executes the query and returns all results as an array.

public array all ( $db null )
$db yii\db\Connection

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

return array

The query results. If the query results in nothing, an empty array will be returned.

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.

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.

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

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.

defaultConnection() protected method

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

Default connection value.

facets() public method

Sets FACET part of the query.

public $this facets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

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.

getConnection() public method

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

Sphinx connection instance

getTablesUsedInFrom() public method (available since version 2.0.9)

Returns table names used in from() indexed by aliases.

Both aliases and names are enclosed into {{ and }}.

public string[] getTablesUsedInFrom ( )
return string[]

Table names indexed by aliases

throws yii\base\InvalidConfigException
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.

innerJoin() public method

Appends an INNER JOIN part to the query.

public $this innerJoin ( $table, $on '', $params = [] )
$table string|array

The table to be joined.

Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).

Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a yii\sphinx\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on string|array

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query.

return $this

The query object itself

join() public method

Appends a JOIN part to the query.

The first parameter specifies what type of join it is.

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

The type of join, such as INNER JOIN, LEFT JOIN.

$table string|array

The table to be joined.

Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).

Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a yii\sphinx\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on string|array

The join condition that should appear in the ON part. Please refer to where() on how to specify this parameter.

Note that the array format of where() is designed to match columns to values instead of columns to columns, so the following would not work as expected: ['post.author_id' => 'user.id'], it would match the post.author_id column value against the string 'user.id'. It is recommended to use the string syntax here which is more suited for a join:

'post.author_id = user.id'
$params array

The parameters (name => value) to be bound to the query.

return $this

The query object itself

leftJoin() public method

Appends a LEFT OUTER JOIN part to the query.

public $this leftJoin ( $table, $on '', $params = [] )
$table string|array

The table to be joined.

Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).

Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a yii\sphinx\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on string|array

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query

return $this

The query object itself

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 yii\db\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.

one() public method

Executes the query and returns a single row of result.

public array|boolean one ( $db null )
$db yii\db\Connection

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

return array|boolean

The first row (in terms of an array) of the query result. False is returned if the query results in nothing.

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

queryScalar() protected method

Queries a scalar value by setting select() first.

Restores the value of select to make this query reusable.

protected boolean|string queryScalar ( $selectExpression, $db )
$selectExpression string|yii\db\ExpressionInterface
$db yii\db\Connection|null
rightJoin() public method

Appends a RIGHT OUTER JOIN part to the query.

public $this rightJoin ( $table, $on '', $params = [] )
$table string|array

The table to be joined.

Use a string to represent the name of the table to be joined. The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). The method will automatically quote the table name unless it contains some parenthesis (which means the table is given as a sub-query or DB expression).

Use an array to represent joining with a sub-query. The array must contain only one element. The value must be a yii\sphinx\Query object representing the sub-query while the corresponding key represents the alias for the sub-query.

$on string|array

The join condition that should appear in the ON part. Please refer to join() on how to specify this parameter.

$params array

The parameters (name => value) to be bound to the query

return $this

The query object itself

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.

setConnection() public method

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

Sphinx connection instance

return $this

The query object itself

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

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

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

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