### Install Yii2 Elasticsearch Extension via Composer Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/installation.md Use Composer to install the yiisoft/yii2-elasticsearch package. This is the preferred method for installation. ```bash composer require --prefer-dist yiisoft/yii2-elasticsearch ``` -------------------------------- ### Install Yii 2 Elasticsearch Extension Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/README.md Install the Yii 2 Elasticsearch extension using composer. Specify the desired version for compatibility. ```bash composer require --prefer-dist yiisoft/yii2-elasticsearch:"~2.1.0" ``` -------------------------------- ### Fetch and Sort by Runtime Field Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-query.md Example for fetching users' full names by concatenating first and last names, and sorting them alphabetically. Ensure the runtime field is included in the `fields()` array. ```php $results = (new yii\elasticsearch\Query()) ->from('users') ->runtimeMappings([ 'full_name' => [ 'type' => 'keyword', 'script' => "emit(doc['first_name'].value + ' ' + doc['last_name'].value)", ], ]) ->fields(['full_name']) ->orderBy(['full_name' => SORT_ASC]) ->search($connection); ``` -------------------------------- ### Elasticsearch Aggregation Result Example Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md This is an example of the processed data structure returned after performing a date histogram aggregation, mapping date strings to document counts. ```php [ '2020-01-01' => 5, '2020-02-01' => 3, '2020-03-01' => 17, ] ``` -------------------------------- ### Find Elasticsearch Records using Query DSL (Match Query) Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Utilize the query() method with Elasticsearch's Query DSL to perform more complex searches. This example uses a 'match' query on the 'title' field. ```php // Finding records using query DSL // (see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html) $articles = Article::find()->query(['match' => ['title' => 'yii']])->all(); ``` -------------------------------- ### Find Elasticsearch Records using Query DSL (Bool Query) Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md This example demonstrates a more complex query using Elasticsearch's 'bool' query structure, combining 'must' clauses with 'term' and 'terms' filters. ```php $articles = Article::find()->query([ 'bool' => [ 'must' => [ ['term' => ['is_active' => true]], ['terms' => ['email' => ['johnsmith@example.com', 'janedoe@example.com']]] ] ] ])->all(); ``` -------------------------------- ### Retrieve Elasticsearch Records by Primary Key Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Fetch single or multiple records using their primary keys. Methods like get(), findOne(), mget(), and findAll() are available. ```php // Getting records using the primary key $customer = Customer::get(1); // get a record by pk $customer = Customer::findOne(1); // also works $customers = Customer::mget([1,2,3]); // get multiple records by pk $customers = Customer::findAll([1, 2, 3]); // also works ``` -------------------------------- ### Demonstrating Object Attribute Merging Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md This example shows how Elasticsearch merges object attributes by default when using the `_update` endpoint. Each subsequent save operation merges new data into the existing object attribute. ```php $customer = new Customer(); $customer->my_attribute = ['foo' => 'v1', 'bar' => 'v2']; $customer->save(); // at this point the value of my_attribute in Elasticsearch is {"foo": "v1", "bar": "v2"} $customer->my_attribute = ['foo' => 'v3', 'bar' => 'v4']; $customer->save(); // now the value of my_attribute in Elasticsearch is {"foo": "v3", "bar": "v4"} $customer->my_attribute = ['baz' => 'v5']; $customer->save(); // now the value of my_attribute in Elasticsearch is {"foo": "v3", "bar": "v4", "baz": "v5"} // but $customer->my_attribute is still equal to ['baz' => 'v5'] ``` -------------------------------- ### Create a New Elasticsearch Record Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Instantiate a new record, set its primary key (only for new records), and populate attributes before saving. Attributes can be set individually or as an array. ```php // Creating a new record $customer = new Customer(); $customer->_id = 1; // setting primary keys is only allowed for new records $customer->last_name = 'Doe'; // attributes can be set one by one $customer->attributes = ['first_name' => 'Jane', 'email' => 'janedoe@example.com']; // or together $customer->save(); ``` -------------------------------- ### Using ActiveDataProvider with Elasticsearch Query Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-data-providers.md Demonstrates how to configure and use the yii\elasticsearch\ActiveDataProvider with a yii\elasticsearch\Query, including setting pagination, retrieving models, aggregations, and suggestions. ```php use yii\elasticsearch\ActiveDataProvider; use yii\elasticsearch\Query; // Using Query $query = new Query(); $query->from('customer'); // ActiveQuery can also be used // $query = Customer::find(); $query->addAggregate(['date_histogram' => [ 'field' => 'registered_at', 'calendar_interval' => 'month', ]]); $query->addSuggester('customer_name', [ 'text' => 'Hans', 'term' => [ 'field' => 'customer_name', ] ]); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 10, ] ]); $models = $dataProvider->getModels(); $aggregations = $dataProvider->getAggregations(); $suggestion = $dataProvider->getSuggestions(); ``` -------------------------------- ### Enable Elasticsearch DebugPanel Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/topics-debug.md Add this configuration to your application's config file to enable the Elasticsearch DebugPanel within the yii debug module. Ensure the debug module is already bootstrapped and configured. ```php // ... 'bootstrap' => ['debug'], 'modules' => [ 'debug' => [ 'class' => 'yii\debug\Module', 'panels' => [ 'elasticsearch' => [ 'class' => 'yii\elasticsearch\DebugPanel', ], ], ], ], // ... ``` -------------------------------- ### Find Elasticsearch Records with Simple Conditions Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Use the find() and where() methods to retrieve records based on simple attribute-value conditions. The one() method fetches the first matching record. ```php // Finding records using simple conditions $customer = Customer::find()->where(['first_name' => 'John', 'last_name' => 'Smith'])->one(); ``` -------------------------------- ### Define Query Building Blocks in Yii2 Elasticsearch Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Create static methods within a custom query class to encapsulate reusable query components, making complex queries more manageable. ```php class CustomerQuery extends ActiveQuery { public static function name($name) { return ['match' => ['name' => $name]]; } public static function address($address) { return ['match' => ['address' => $address]]; } public static function registrationDateRange($dateFrom, $dateTo) { return ['range' => ['registered_at' => [ 'gte' => $dateFrom, 'lte' => $dateTo, ]]]; } } ``` -------------------------------- ### Define Customer Relations (Orders and Invoices) Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Defines a `hasMany` relation for orders and a `via` relation for invoices from a Customer Elasticsearch ActiveRecord. Ensure limits are explicitly set for both relations, especially for via-relations, to match expected data retrieval. ```php class Customer extends yii\elasticsearch\ActiveRecord { // Every customer has multiple orders, every order has exactly one invoice public function getOrders() { // This relation gets up to 100 most recent orders of current customer return $this->hasMany(Order::className(), ['customer_id' => '_id']) ->orderBy(['created_at' => SORT_DESC]) ->limit(100); // override the default limit of 10 } public function getInvoices() { // This via-relation works by fetching the related "orders" // models first. This query also needs a limit, but it makes // no sense to make that limit different from the underlying // relation. return $this->hasMany(Invoice::className(), ['_id' => 'order_id']) ->via('orders')->limit(100); } } ``` -------------------------------- ### Add Term Suggester to Elasticsearch Query Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Utilize `addSuggester` to implement a term suggester for finding similar search terms within a specified field. Using `limit(0)` ensures only suggestions are returned, not search hits. ```php $searchResult = Customer::find()->limit(0) ->addSuggester('customer_name', [ 'text' => 'Hans', 'term' => [ 'field' => 'name', ] ])->search(); // Note that limit(0) will prevent the query from returning hits, // so only suggestions are returned $suggestions = ArrayHelper::map($searchResult["suggest"]["customer_name"], 'text', 'options'); $names = ArrayHelper::getColumn($suggestions['Hans'], 'text'); // $names == ['Hanns', 'Hannes', 'Hanse', 'Hansi'] ``` -------------------------------- ### Configure Yii2 Elasticsearch Connection Component Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/installation.md Configure the Elasticsearch connection component in your Yii application's configuration file. Ensure the 'nodes' are correctly set for your Elasticsearch cluster. ```php return [ //.... 'components' => [ 'elasticsearch' => [ 'class' => 'yii\elasticsearch\Connection', 'nodes' => [ ['http_address' => '127.0.0.1:9200'], // configure more hosts if you have a cluster ], // set autodetectCluster to false if you don't want to auto detect nodes // 'autodetectCluster' => false, 'dslVersion' => 7, // default is 5 ], ], ]; ``` -------------------------------- ### Construct Complex Elasticsearch Queries in Yii2 Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Combine query building blocks defined in a custom query class to construct and execute complex boolean queries against Elasticsearch using Yii2's Active Record. ```php $customers = Customer::find()->query([ 'bool' => [ 'must' => [ CustomerQuery::registrationDateRange('2016-01-01', '2016-01-20') ], 'should' => [ CustomerQuery::name('John'), CustomerQuery::address('London'), ], 'must_not' => [ CustomerQuery::name('Jack'), ], ], ])->all(); ``` -------------------------------- ### Define Elasticsearch ActiveRecord Class Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Extend yii\elasticsearch\ActiveRecord and implement the attributes() method to define record attributes. Do not include the primary key attribute (_id) in the attributes list. ```php class Customer extends yii\elasticsearch\ActiveRecord { // Other class attributes and methods go here // ... public function attributes() { return ['first_name', 'last_name', 'order_ids', 'email', 'registered_at', 'updated_at', 'status', 'is_active']; } } ``` -------------------------------- ### Set track_total_hits to 'true' in Query Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-query.md Use this option to ensure exact document counts are always returned, overriding the default threshold of 10,000 hits. Note that the value must be a literal string 'true', not a boolean. ```php $query = new Query(); $query->from('customer'); // Note the literal string 'true', not a boolean value! $query->addOptions(['track_total_hits' => 'true']); ``` -------------------------------- ### Add Date Histogram Aggregation to Elasticsearch Query Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Use `addAggregate` to define a date histogram aggregation for grouping documents by month based on a date field. Set `limit(0)` to retrieve only metadata and aggregations, not search hits. ```php $searchResult = Customer::find()->addAggregate('customers_by_date', [ 'date_histogram' => [ 'field' => 'registered_at', 'calendar_interval' => 'month', ], ])->limit(0)->search(); $customersByDate = ArrayHelper::map($searchResult['aggregations']['customers_by_date']['buckets'], 'key_as_string', 'doc_count'); ``` -------------------------------- ### Define Elasticsearch Mapping in Yii2 ActiveRecord Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/mapping-indexing.md Defines the mapping for an Elasticsearch index within a Yii2 ActiveRecord model. This includes field types and properties. ```php class Customer extends yii\elasticsearch\ActiveRecord { // Other class attributes and methods go here // ... /** * @return array This model's mapping */ public static function mapping() { return [ // Field types: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html#field-datatypes 'properties' => [ 'first_name' => ['type' => 'text'], 'last_name' => ['type' => 'text'], 'order_ids' => ['type' => 'keyword'], 'email' => ['type' => 'keyword'], 'registered_at' => ['type' => 'date'], 'updated_at' => ['type' => 'date'], 'status' => ['type' => 'keyword'], 'is_active' => ['type' => 'boolean'], ] ]; } /** * Set (update) mappings for this model */ public static function updateMapping() { $db = static::getDb(); $command = $db->createCommand(); $command->setMapping(static::index(), static::type(), static::mapping()); } /** * Create this model's index */ public static function createIndex() { $db = static::getDb(); $command = $db->createCommand(); $command->createIndex(static::index(), [ //'aliases' => [ /* ... */ ], 'mappings' => static::mapping(), //'settings' => [ /* ... */ ], ]); } /** * Delete this model's index */ public static function deleteIndex() { $db = static::getDb(); $command = $db->createCommand(); $command->deleteIndex(static::index(), static::type()); } } ``` -------------------------------- ### Configure Array Attributes in Yii2 Elasticsearch Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md Override the default behavior of treating single-item arrays as values by defining `arrayAttributes()` to ensure fields like 'order_ids' are always returned as arrays. ```php public function arrayAttributes() { return ['order_ids']; } ``` -------------------------------- ### Overwriting Object Attributes Source: https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/usage-ar.md To prevent Elasticsearch from merging object attributes and instead overwrite them, wrap the object attribute value in a single-element array. This ensures the entire object is replaced with the new value. ```php $customer->my_attribute = [['new' => 'value']]; // note the double brackets $customer->save(); // now the value of my_attribute in Elasticsearch is {"new": "value"} $customer->my_attribute = $customer->my_attribute[0]; // could be done for consistency ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.