SlideShare une entreprise Scribd logo
1  sur  37
Magento Indexers Ivan Chepurnyi Magento Trainer / Lead Developer
Agenda Magento Developers Meetup Overview of Indexes Functionality Creation of own indexes
Let Imagine… Magento Developers Meetup … that Magento doesn’t have indexes: The prices in product list are calculated on the fly depending on catalog rules, tier prices for customer groups Stock availability for configurable and bundle products can be calculated only after loading the product collection Layered navigation data is build in real-time for product attributes information Anchor categories recursively collects subcategories for filtering product list
It’s all about performance… Magento Developers Meetup The main goal is minimizing amount of operations to display products to a customer
Definitions Magento Developers Meetup Indexed DataAggregated data for entity representation on the frontend lists. Indexer 	Generates index data on event or manual by process. Index EventThe moment when entity or related to it information is changed and that affects its index data. Index Process Wrapper for indexer and contains information about its mode and status Main Controller 	Forwards events to Index Process
Index Workflow Magento Developers Meetup Event Main Controller Event Events Process Manual Invoke Indexer Indexed Data
Event Types Magento Developers Meetup Save 	When indexed entity or related to it information was changed Delete When indexed entity or related to it one was deleted Mass UpdateWhen batch of entities was updated. (Update Attributes on Product Grid)
Observed Entities  Magento Developers Meetup Indexed Entities Product Product Inventory Category Tag Entities Scope Customer Group Website Store Group Store View
Index Process Magento Developers Meetup Available Statuses Pending 	Indicates that indexer is up to date Running 	Index currently in process of full rebuilding index data. Require ReindexStatus for notifying admin user, that index is not up to date and should be rebuild.
Index Process Magento Developers Meetup Indexing Modes Real-time Manual Update Index Data Event Event Require Reindex
Indexer Flow  Magento Developers Meetup Match Event Main Controller Index Process Register Event Data Reindex Data
Mage_Index Module Magento Developers Meetup Main Controller Mage_Index_Model_Indexer Process Mage_Index_Model_Process Indexer Base Mage_Index_Model_Indexer_Abstract
Index Module Indexers Modularity Magento Developers Meetup Mage_Index_Model_Indexer_Abstract Catalog Module Mage_Catalog_Model_Product_Indexer_Eav Mage_Catalog_Model_Product_Indexer_Flat Mage_Catalog_Model_Product_Indexer_Price Inventory Module Mage_CatalogIndex_Model_Indexer_Stock …
Model Mage_Index_Model_Indexer_Abstract Indexer Structure Magento Developers Meetup Resource Model Mage_Index_Model_Mysql4_Abstract Matches event data and runs appropriate method in resource model for re-indexing Works directly with database for generation of the indexed data. Usually all the data operated via MySQL queries.
What can you use? Magento Developers Meetup Mage_Index_Model_Indexer getProcessByCode($indexerCode) getProcessCollection() processEntityAction($entity, $entityType, $eventType) Mage_Index_Model_Process reindexAll() reindexEverything() setMode($mode)
What you shouldn’t do… Magento Developers Meetup Invoke reindexAll method from index model/resource model, because it is better to let admin user know when the index was rebuild. Process entity events directly with indexer, instead of passing data through the main controller. You never know which index may depend on this event.
Creating own indexer Magento Developers Meetup Defining indexer in configuration Designing index data table Implementing model  Implementing resource model Applying index on the frontend
Featured Products Magento Developers Meetup There is easier way to create featured products functionality, but it is a simple example on what should be done for creation own indexer.
Defining index in configuration Magento Developers Meetup <config> <!-- …. module configurtaions -->    <global>    <!-- …. module configurtaions -->         <index> <indexer>                 <featured_products>                     <model>your_module/indexer_featured</model>                  </featured_products>             </indexer>         </index>     </global> </config> etc/config.xml Indexer Code  Indexer Model
Designing index data table Magento Developers Meetup Adding new attribute to catalog product entity called is_featured Creating table that will contain product ids of products that are marked as featured products.
Designing index data table Magento Developers Meetup $this->addAttribute('catalog_product', 'is_featured', array(     'type' => 'int',     'label' => 'Is featured',     'input' => 'select',     'source' => 'eav/entity_attribute_source_boolean',     'user_defined' => false,     'required' => false )); Setup Script Attribute Code  Yes/No Dropdown
Designing index data table Magento Developers Meetup $table = new Varien_Db_Ddl_Table(); $table->setName($this->getTable(‘module/featured')); $table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array(     'unsigned' => true,     'nullable' => false,     'primary' => true )); $this->getConnection()->createTable($table); Setup Script Table Alias Table Column
Designing index data table Magento Developers Meetup $table = new Varien_Db_Ddl_Table(); $table->setName($this->getTable(‘module/featured')); $table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array(     'unsigned' => true,     'nullable' => false,     'primary' => true )); $this->getConnection()->createTable($table); Setup Script Table Alias Table Column
Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract {    protected $_matchedEntities = array( Mage_Catalog_Model_Product::ENTITY => array( Mage_Index_Model_Event::TYPE_SAVE,  Mage_Index_Model_Event::TYPE_MASS_ACTION         ) ); } Defining Matching Events Entity Type Event Type Event Types
Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { // … other code protected function _construct()     {         $this->_init(‘your_module/indexer_featured');     } } Defining Indexer Resource Model Resource model
Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract {   // … other code public function getName()     {         return Mage::helper(‘your_module')->__('Featured Product');     }     public function getDescription()     {         return Mage::helper(‘‘your_module')->__('Indexes something'); } } Defining Indexer Information Indexer Name in the admin Indexer Description in the admin
Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract {   // … other code protected function _registerEvent(Mage_Index_Model_Event $event)     {         /* @var $entity Mage_Catalog_Model_Product */         $entity = $event->getDataObject();         if ($entity->dataHasChangedFor('is_featured')) {             $event->setData('product_id', $entity->getId());         } elseif ($entity->getAttributesData()) {             $attributeData = $entity->getAttributesData();             if (isset($attributeData['is_featured'])) {                 $event->setData('product_ids', $entity->getProductIds());             } } } } Register Event for Processing Product Save Registering Mass Action Registering
Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract {   // … other code     protected function _processEvent(Mage_Index_Model_Event $event)     {         if ($event->getData('product_id') || $event->getData('product_ids')) {             $this->callEventHandler($event);         } } } Processing Event Calling processor in resource model Entity Type Event Type catalogProductSave($event) catalogProductMassAction($event)
Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract {    protected function _construct()     {         $this->_setResource(‘your_module');    } } Define resource connection Your module resource prefix
Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract {     // … other code     protected function _reindexEntity($productId = null)     {         $select = $this->_getReadAdapter()->select();         /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */         $attribute = Mage::getSingleton('eav/config')                                    ->getAttribute('catalog_product', 'is_featured');         $select->from($attribute->getBackendTable(), 'entity_id')             ->where('value = ?', 1)             ->where('attribute_id = ?', $attribute->getId()); Indexing Method Retrieving only featured product ids
Implementing Resource Model Magento Developers Meetup if ($productId !== null) {             if (!is_array($productId)) {                 $productId = array($productId);             }             $select->where('entity_id IN(?)', $productId);             $this->_getWriteAdapter()->delete(                 $this->getTable(‘your_module/featured'),                 array(                     'product_id IN(?)' => $productId                 )             );         } else {             $this->_getWriteAdapter()->truncate($this->getTable(‘your_module/featured'));         } Indexing Method If it is partial re-index, then delete only related indexed data Otherwise clear all indexed data
Implementing Resource Model Magento Developers Meetup $sqlStatement = $select->insertIgnoreFromSelect(             $this->getTable(‘your_module/featured'),             array('product_id')         );         $this->_getWriteAdapter()->query($sqlStatement);     } } Fulfill index data from select we created before Indexing Method
Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract {     // … other code     public function reindexAll()     {         $this->_reindexEntity();     } } Handling Events Full index re-build
Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract {     // … other code public function catalogProductSave($event)     {         $this->_reindexEntity($event->getData('product_id'));     } public function catalogProductMassAction($event)     {         $this->_reindexEntity($event->getData('product_ids'));     } } Reindexing Events Single Save Product Event Mass Save Product Event
Applying Index for the frontend Magento Developers Meetup Observing and event catalog_product_collection_apply_limitations_after Joining index table to product collection select Create sub-select filter for collection
Liked it? Magento Developers Meetup Checkout our advanced  training programs: http://www.ecomdev.org/magento-development-training-programs/advanced Follow our blog posts: http://www.ecomdev.org/blog
Questions?

Contenu connexe

Tendances

Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.jsTechMagic
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 
Présentation Flutter
Présentation FlutterPrésentation Flutter
Présentation FlutterAppstud
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Kyoung Up Jung
 
Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Amazon Web Services
 
Getting started with Jenkins
Getting started with JenkinsGetting started with Jenkins
Getting started with JenkinsEdureka!
 
SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?태환 김
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsIntroduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsEric Hogue
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 

Tendances (20)

Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Ajax cheat sheet
Ajax cheat sheetAjax cheat sheet
Ajax cheat sheet
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Présentation Flutter
Présentation FlutterPrésentation Flutter
Présentation Flutter
 
Design Pattern Cheatsheet
Design Pattern CheatsheetDesign Pattern Cheatsheet
Design Pattern Cheatsheet
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.
 
Angular
AngularAngular
Angular
 
Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration Continuous Delivery, Continuous Integration
Continuous Delivery, Continuous Integration
 
Getting started with Jenkins
Getting started with JenkinsGetting started with Jenkins
Getting started with Jenkins
 
SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?SQL Server에서 Django를 추구하면 안 되는 걸까?
SQL Server에서 Django를 추구하면 안 되는 걸까?
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsIntroduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec Jenkins
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
angular fundamentals.pdf
angular fundamentals.pdfangular fundamentals.pdf
angular fundamentals.pdf
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 

En vedette

Mage Titans USA 2016 M2 deployment
Mage Titans USA 2016  M2 deploymentMage Titans USA 2016  M2 deployment
Mage Titans USA 2016 M2 deploymentOlga Kopylova
 
Magento 2.0: Prepare yourself for a new way of module development
Magento 2.0: Prepare yourself for a new way of module developmentMagento 2.0: Prepare yourself for a new way of module development
Magento 2.0: Prepare yourself for a new way of module developmentIvan Chepurnyi
 
Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Ivan Chepurnyi
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for MagentoIvan Chepurnyi
 
Hidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price RulesHidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price RulesIvan Chepurnyi
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Ivan Chepurnyi
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
 

En vedette (7)

Mage Titans USA 2016 M2 deployment
Mage Titans USA 2016  M2 deploymentMage Titans USA 2016  M2 deployment
Mage Titans USA 2016 M2 deployment
 
Magento 2.0: Prepare yourself for a new way of module development
Magento 2.0: Prepare yourself for a new way of module developmentMagento 2.0: Prepare yourself for a new way of module development
Magento 2.0: Prepare yourself for a new way of module development
 
Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
Hidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price RulesHidden Secrets of Magento Price Rules
Hidden Secrets of Magento Price Rules
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 

Similaire à Magento Indexes

Magento Performance Toolkit
Magento Performance ToolkitMagento Performance Toolkit
Magento Performance ToolkitSergii Shymko
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processingCareer at Elsner
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWordCamp Indonesia
 
How to Create Module to Track Affiliate Conversions?
How to Create Module to Track Affiliate Conversions?How to Create Module to Track Affiliate Conversions?
How to Create Module to Track Affiliate Conversions?damienwoods
 
Intro Open Social and Dashboards
Intro Open Social and DashboardsIntro Open Social and Dashboards
Intro Open Social and DashboardsAtlassian
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data BindingEric Maxwell
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Pavel Novitsky
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)Woonsan Ko
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBo-Yi Wu
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised contentMichael Peacock
 
07 Php Mysql Update Delete
07 Php Mysql Update Delete07 Php Mysql Update Delete
07 Php Mysql Update DeleteGeshan Manandhar
 

Similaire à Magento Indexes (20)

Magento Performance Toolkit
Magento Performance ToolkitMagento Performance Toolkit
Magento Performance Toolkit
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processing
 
Framework
FrameworkFramework
Framework
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
WooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda BagusWooCommerce CRUD and Data Store by Akeda Bagus
WooCommerce CRUD and Data Store by Akeda Bagus
 
Extend sdk
Extend sdkExtend sdk
Extend sdk
 
How to Create Module to Track Affiliate Conversions?
How to Create Module to Track Affiliate Conversions?How to Create Module to Track Affiliate Conversions?
How to Create Module to Track Affiliate Conversions?
 
Intro Open Social and Dashboards
Intro Open Social and DashboardsIntro Open Social and Dashboards
Intro Open Social and Dashboards
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 
Hacking Movable Type
Hacking Movable TypeHacking Movable Type
Hacking Movable Type
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
Benefit of CodeIgniter php framework
Benefit of CodeIgniter php frameworkBenefit of CodeIgniter php framework
Benefit of CodeIgniter php framework
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised content
 
07 Php Mysql Update Delete
07 Php Mysql Update Delete07 Php Mysql Update Delete
07 Php Mysql Update Delete
 
Growing up with Magento
Growing up with MagentoGrowing up with Magento
Growing up with Magento
 

Dernier

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 

Dernier (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 

Magento Indexes

  • 1. Magento Indexers Ivan Chepurnyi Magento Trainer / Lead Developer
  • 2. Agenda Magento Developers Meetup Overview of Indexes Functionality Creation of own indexes
  • 3. Let Imagine… Magento Developers Meetup … that Magento doesn’t have indexes: The prices in product list are calculated on the fly depending on catalog rules, tier prices for customer groups Stock availability for configurable and bundle products can be calculated only after loading the product collection Layered navigation data is build in real-time for product attributes information Anchor categories recursively collects subcategories for filtering product list
  • 4. It’s all about performance… Magento Developers Meetup The main goal is minimizing amount of operations to display products to a customer
  • 5. Definitions Magento Developers Meetup Indexed DataAggregated data for entity representation on the frontend lists. Indexer Generates index data on event or manual by process. Index EventThe moment when entity or related to it information is changed and that affects its index data. Index Process Wrapper for indexer and contains information about its mode and status Main Controller Forwards events to Index Process
  • 6. Index Workflow Magento Developers Meetup Event Main Controller Event Events Process Manual Invoke Indexer Indexed Data
  • 7. Event Types Magento Developers Meetup Save When indexed entity or related to it information was changed Delete When indexed entity or related to it one was deleted Mass UpdateWhen batch of entities was updated. (Update Attributes on Product Grid)
  • 8. Observed Entities Magento Developers Meetup Indexed Entities Product Product Inventory Category Tag Entities Scope Customer Group Website Store Group Store View
  • 9. Index Process Magento Developers Meetup Available Statuses Pending Indicates that indexer is up to date Running Index currently in process of full rebuilding index data. Require ReindexStatus for notifying admin user, that index is not up to date and should be rebuild.
  • 10. Index Process Magento Developers Meetup Indexing Modes Real-time Manual Update Index Data Event Event Require Reindex
  • 11. Indexer Flow Magento Developers Meetup Match Event Main Controller Index Process Register Event Data Reindex Data
  • 12. Mage_Index Module Magento Developers Meetup Main Controller Mage_Index_Model_Indexer Process Mage_Index_Model_Process Indexer Base Mage_Index_Model_Indexer_Abstract
  • 13. Index Module Indexers Modularity Magento Developers Meetup Mage_Index_Model_Indexer_Abstract Catalog Module Mage_Catalog_Model_Product_Indexer_Eav Mage_Catalog_Model_Product_Indexer_Flat Mage_Catalog_Model_Product_Indexer_Price Inventory Module Mage_CatalogIndex_Model_Indexer_Stock …
  • 14. Model Mage_Index_Model_Indexer_Abstract Indexer Structure Magento Developers Meetup Resource Model Mage_Index_Model_Mysql4_Abstract Matches event data and runs appropriate method in resource model for re-indexing Works directly with database for generation of the indexed data. Usually all the data operated via MySQL queries.
  • 15. What can you use? Magento Developers Meetup Mage_Index_Model_Indexer getProcessByCode($indexerCode) getProcessCollection() processEntityAction($entity, $entityType, $eventType) Mage_Index_Model_Process reindexAll() reindexEverything() setMode($mode)
  • 16. What you shouldn’t do… Magento Developers Meetup Invoke reindexAll method from index model/resource model, because it is better to let admin user know when the index was rebuild. Process entity events directly with indexer, instead of passing data through the main controller. You never know which index may depend on this event.
  • 17. Creating own indexer Magento Developers Meetup Defining indexer in configuration Designing index data table Implementing model Implementing resource model Applying index on the frontend
  • 18. Featured Products Magento Developers Meetup There is easier way to create featured products functionality, but it is a simple example on what should be done for creation own indexer.
  • 19. Defining index in configuration Magento Developers Meetup <config> <!-- …. module configurtaions --> <global> <!-- …. module configurtaions --> <index> <indexer> <featured_products> <model>your_module/indexer_featured</model> </featured_products> </indexer> </index> </global> </config> etc/config.xml Indexer Code Indexer Model
  • 20. Designing index data table Magento Developers Meetup Adding new attribute to catalog product entity called is_featured Creating table that will contain product ids of products that are marked as featured products.
  • 21. Designing index data table Magento Developers Meetup $this->addAttribute('catalog_product', 'is_featured', array( 'type' => 'int', 'label' => 'Is featured', 'input' => 'select', 'source' => 'eav/entity_attribute_source_boolean', 'user_defined' => false, 'required' => false )); Setup Script Attribute Code Yes/No Dropdown
  • 22. Designing index data table Magento Developers Meetup $table = new Varien_Db_Ddl_Table(); $table->setName($this->getTable(‘module/featured')); $table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array( 'unsigned' => true, 'nullable' => false, 'primary' => true )); $this->getConnection()->createTable($table); Setup Script Table Alias Table Column
  • 23. Designing index data table Magento Developers Meetup $table = new Varien_Db_Ddl_Table(); $table->setName($this->getTable(‘module/featured')); $table->addColumn('product_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array( 'unsigned' => true, 'nullable' => false, 'primary' => true )); $this->getConnection()->createTable($table); Setup Script Table Alias Table Column
  • 24. Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { protected $_matchedEntities = array( Mage_Catalog_Model_Product::ENTITY => array( Mage_Index_Model_Event::TYPE_SAVE, Mage_Index_Model_Event::TYPE_MASS_ACTION ) ); } Defining Matching Events Entity Type Event Type Event Types
  • 25. Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { // … other code protected function _construct() { $this->_init(‘your_module/indexer_featured'); } } Defining Indexer Resource Model Resource model
  • 26. Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { // … other code public function getName() { return Mage::helper(‘your_module')->__('Featured Product'); } public function getDescription() { return Mage::helper(‘‘your_module')->__('Indexes something'); } } Defining Indexer Information Indexer Name in the admin Indexer Description in the admin
  • 27. Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { // … other code protected function _registerEvent(Mage_Index_Model_Event $event) { /* @var $entity Mage_Catalog_Model_Product */ $entity = $event->getDataObject(); if ($entity->dataHasChangedFor('is_featured')) { $event->setData('product_id', $entity->getId()); } elseif ($entity->getAttributesData()) { $attributeData = $entity->getAttributesData(); if (isset($attributeData['is_featured'])) { $event->setData('product_ids', $entity->getProductIds()); } } } } Register Event for Processing Product Save Registering Mass Action Registering
  • 28. Implementing Model Magento Developers Meetup class Your_Module_Model_Indexer_Featuredextends Mage_Index_Model_Indexer_Abstract { // … other code protected function _processEvent(Mage_Index_Model_Event $event) { if ($event->getData('product_id') || $event->getData('product_ids')) { $this->callEventHandler($event); } } } Processing Event Calling processor in resource model Entity Type Event Type catalogProductSave($event) catalogProductMassAction($event)
  • 29. Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract { protected function _construct() { $this->_setResource(‘your_module'); } } Define resource connection Your module resource prefix
  • 30. Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract { // … other code protected function _reindexEntity($productId = null) { $select = $this->_getReadAdapter()->select(); /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */ $attribute = Mage::getSingleton('eav/config') ->getAttribute('catalog_product', 'is_featured'); $select->from($attribute->getBackendTable(), 'entity_id') ->where('value = ?', 1) ->where('attribute_id = ?', $attribute->getId()); Indexing Method Retrieving only featured product ids
  • 31. Implementing Resource Model Magento Developers Meetup if ($productId !== null) { if (!is_array($productId)) { $productId = array($productId); } $select->where('entity_id IN(?)', $productId); $this->_getWriteAdapter()->delete( $this->getTable(‘your_module/featured'), array( 'product_id IN(?)' => $productId ) ); } else { $this->_getWriteAdapter()->truncate($this->getTable(‘your_module/featured')); } Indexing Method If it is partial re-index, then delete only related indexed data Otherwise clear all indexed data
  • 32. Implementing Resource Model Magento Developers Meetup $sqlStatement = $select->insertIgnoreFromSelect( $this->getTable(‘your_module/featured'), array('product_id') ); $this->_getWriteAdapter()->query($sqlStatement); } } Fulfill index data from select we created before Indexing Method
  • 33. Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract { // … other code public function reindexAll() { $this->_reindexEntity(); } } Handling Events Full index re-build
  • 34. Implementing Resource Model Magento Developers Meetup class Your_Module_Model_Mysql4_Indexer_Featured extends Mage_Index_Model_Mysql4_Abstract { // … other code public function catalogProductSave($event) { $this->_reindexEntity($event->getData('product_id')); } public function catalogProductMassAction($event) { $this->_reindexEntity($event->getData('product_ids')); } } Reindexing Events Single Save Product Event Mass Save Product Event
  • 35. Applying Index for the frontend Magento Developers Meetup Observing and event catalog_product_collection_apply_limitations_after Joining index table to product collection select Create sub-select filter for collection
  • 36. Liked it? Magento Developers Meetup Checkout our advanced training programs: http://www.ecomdev.org/magento-development-training-programs/advanced Follow our blog posts: http://www.ecomdev.org/blog