本文討論如何創(chuàng)建一個索引器(Indexer)重建索引(Reindex)。Magento 2 索引中最主要的是索引器。為了代碼演示我們繼續(xù)使用 HelloWorld 模塊。
Magento 系統(tǒng)使用索引來變換數(shù)據(jù)如產(chǎn)品、分類等進(jìn)而提高店鋪的性能。當(dāng)數(shù)據(jù)變化時,變換的數(shù)據(jù)也必須同步更新或重建索引。Magento 使用非常精致的架構(gòu)在很多數(shù)據(jù)表中存儲大量的店鋪數(shù)據(jù)(包括產(chǎn)品、價格、用戶、店鋪等數(shù)據(jù))。為了優(yōu)化店鋪性能,Magento 使用索引器把累積的數(shù)據(jù)存儲到特定數(shù)據(jù)表。
比如,你將一個產(chǎn)品的價格從¥8.99改到¥6.99,這時要讓前臺頁面正常顯示 Magento 就必須重建價格索引。
如果不使用索引,Magneto就必須實時計算每一個產(chǎn)品的價格——要計算的有客戶購物車產(chǎn)品規(guī)則、批量價、折扣價、階梯價等。這樣產(chǎn)品的價格計算會花費很長時間,長時間的等待造成的結(jié)果可能就是消費者放棄購物。
創(chuàng)建自定義索引器步驟:
- 1 添加索引器配置文件
- 2 添加 Mview 配置文件
- 3 定義索引器類
- 4 運行測試
添加索引器配置文件
文件: app/code/Aqrun/HelloWorld/etc/indexer.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
<indexer id="aqrun_helloworld_indexer"
view_id="aqrun_helloworld_indexer"
class="Aqrun\HelloWorld\Model\Indexer\Test"
>
<title translate="true">Aqrun HelloWorld Indexer</title>
<description translate="true">你好世界自定義索引器</description>
</indexer>
</config>
上面代碼中我們使用 indexer 節(jié)點定義了一個新的索引器:
- id 屬性是索引器的唯一標(biāo)識??梢栽诿钚惺褂眠@個ID來檢查狀態(tài)、模式或重建對應(yīng)的索引
- view_id 是視圖元素的ID,視圖元素會在 mview 配置文件中進(jìn)行定義
- class 屬性指定我們要處理索引方法的類名
簡單的索引還有兩個子節(jié)點:
- title 節(jié)點是顯示在索引器列表中的文字
- description 節(jié)點索引器列表中的說明文字
添加 Mview 配置文件
mview.xml 文件是用于跟蹤指定的實體在數(shù)據(jù)庫中的變化,并運行指定的方法處理這些變化
文件: app/code/Aqrun/HelloWorld/etc/mview.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Mview/etc/mview.xsd">
<view id="aqrun_helloworld_indexer"
class="Aqrun\HelloWorld\Model\Indexer\Test"
group="indexer" >
<subscriptions>
<table name="catalog_product_entity" entity_column="entity_id"/>
</subscription>
</view>
</config>
代碼中定義了有ID屬性的 view 節(jié)點,ID屬性關(guān)聯(lián)索引器,class 屬性指定了實現(xiàn)有 execute() 方法的類。這個方法會在訂閱的數(shù)據(jù)表有更新時執(zhí)行。
定義數(shù)據(jù)表需要用到表名和表的字段,這些參數(shù)也會傳給 execute() 方法。本例我們指定的表是 catalog_product_entity。因此無論何時不管是一個還是多個產(chǎn)品被保存,都會執(zhí)行 Aqrun\HelloWorld\Model\Indexer\Test 類的 execute() 方法。
定義索引器類
根據(jù)上面的 indexer.xml 和 mview.xml 配置文件,定義索引器為: Aqrun\HelloWorld\Model\Indexer\Test
文件: app/code/Aqrun/HelloWrold/Model/Indexer/Test.php
<?php
namespace Aqrun\HelloWorld\Model\Indexer;
class Test implements \Magento\Framework\Indexer\ActionInterface,
\Magento\Framework\Mview\ActionInterface
{
/**
* 被 mview 調(diào)用,允許在 "Update on schedule" 模式下處理索引
* @param int[] $ids
*/
public function execute($ids){
//code
}
/**
* 會處理所有的數(shù)據(jù)并重建索引
* 在使用命令行重建索引時會執(zhí)行
*/
public function executeFull(){
//code
}
/**
* 作用于一組實體的變化(如批量操作)
* @param array $ids
*/
public function executeList(array $ids){
//code
}
/**
* 作用于單個實體
* @param int $id
*/
public function executeRow($id){
// code
}
}
你可以在索引器類方法中添加代碼向索引器表更新數(shù)據(jù)
接下來,清空緩存并到后臺菜單 system > Index Management 查看代碼結(jié)果

重建索引使用命令:
php bin/magento indexer:redinex