在上一篇文章,我们配置好了es,那么,我们开始配置model
<?php
namespace appadmin\code\Ta\models\elasticSearch;
use yii\elasticsearch\ActiveRecord;
class Customer extends ActiveRecord
{
public static $currentIndex;
# 定义db链接
public static function getDb()
{
return \Yii::$app->get('elasticsearch');
}
# db
public static function index()
{
return 'ta';
}
# table
public static function type()
{
return 'customer';
}
# 属性
public function attributes()
{
$mapConfig = self::mapConfig();
return array_keys($mapConfig['properties']);
}
# mapping配置
public static function mapConfig(){
return [
'properties' => [
'customer_id' => ['type' => 'long', "index" => "not_analyzed"],
'uuids' => ['type' => 'string', "index" => "not_analyzed"],
'updated_at' => ['type' => 'long', "index" => "not_analyzed"],
'emails' => ['type' => 'string',"index" => "not_analyzed"],
]
];
}
public static function mapping()
{
return [
static::type() => self::mapConfig(),
];
}
/**
* Set (update) mappings for this model
*/
public static function updateMapping(){
$db = self::getDb();
$command = $db->createCommand();
if(!$command->indexExists(self::index())){
$command->createIndex(self::index());
}
$command->setMapping(self::index(), self::type(), self::mapping());
}
public static function getMapping(){
$db = self::getDb();
$command = $db->createCommand();
return $command->getMapping();
}
}
index()方法,可以看成mysql的db
type()可以看成mysql的table,但是实质是有差别的。
mapConfig()是配置mapping,关于elasticSearch的mapping,您可以参看下面的一些资料:
https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html
http://blog.csdn.net/lvhong84/article/details/23936697
等等,您可以去搜搜。
由于我不想让elasticSearch 进行分词等操作,我只是想当成一个和数据库类似的搜索,因此,我的mapping的定义为:”index” => “not_analyzed”
当然,index部分,您可以不定义,直接用默认的方式,是会被分词的。mapping类似于一个表定义。
当model建立好,您如果定义了mapping,那么您需要执行一下方法updateMapping(),让es建立mapping,该方法执行一次就可以了。
如果您需要在mapping中添加其他的字段,那么添加后在运行一次updateMapping()
另外需要注意的是:elasticSearch的mapping是不能删除的,建了就是建了,如果要删除,您只能删除index(相当于mysql的db),然后重建mapping,因此,您最好写一个脚本,执行es的所有model的mapping。
到这里,model就讲述完了、