model模型
namespace app\models;
use yii\elasticsearch\ActiveRecord;
class EsStore extends ActiveRecord {
/**
* @return array the list of attributes for this record
*/
public function attributes() {
// path mapping for '_id' is setup to field 'id'
return ['id', 'name','keyword','desc'];
}
/**
* @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. redis or sql)
*/
public function getOrders() {
return $this->hasMany(Order::className(), ['customer_id' => 'id'])->orderBy('id');
}
/**
* Defines a scope that modifies the `$query` to return only active(status = 1) customers
*/
public static function active($query) {
$query->andWhere(['status' => 1]);
}
}
1、yii2中向es添加数据
$name = "郑州房价最新动态";
$keyword = ["房价",'地价']; //多个字段可以使用数组
$desc = "关注郑州房价最新动态,了解楼盘最新行情。主安家做前期准备";
$id = 4;
$customer = new EsStore();
$customer->primaryKey = $id; // in this case equivalent to $customer->id = 1;
$customer->setAttributes(['name' => $name,'keyword'=>$keyword,'desc'=>$desc], false);
$customer->save(false);
2、普通查询语句
$customer = EsStore::find()->where(['name'=>'郑州'])->asArray()->all();
3、高亮查询
$query = [
'match' => ['keyword'=>'房价']
];
$highlight = [
'pre_tags' => '<em>',
'post_tags' => '</em>',
'fields' => ['keyword'=>new \stdClass()]
];
$customer = EsStore::find()->query($query)->highlight($highlight)->asArray()->all();
封装现成的类:
Class Book extends yii\elasticsearch\ActiveRecord
{
public static function index(){
return "Catalog"
}
public static function type(){
return "Book";
}
/**
* @return array This model's mapping
*/
public static function mapping()
{
return [
static::type() => [
'properties' => [
'id' => ['type' => 'long'],
'name' => ['type' => 'string'],
'author_name' => ['type' => 'string', "index"=>"not_analyzed"],
'publisher_name' => ['type' => 'string', "index"=>"not_analyzed"],
'created_at' => ['type' => 'long'],
'updated_at' => ['type' => 'long'],
'status' => ['type' => 'long'],
'suppliers' => [
'type' => 'nested',
'properties' => [
'id' => ['type' => 'long'],
'name' => ['type' => 'string', 'index' => 'not_analyzed'],
]
]
]
],
];
}
/**
* 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(), [
'settings' => [ 'index' => ['refresh_interval' => '1s'] ],
'mappings' => static::mapping(),
//'warmers' => [ /* ... */ ],
//'aliases' => [ /* ... */ ],
//'creation_date' => '...'
]);
}
/**
* Delete this model's index
*/
public static function deleteIndex()
{
$db = static::getDb();
$command = $db->createCommand();
$command->deleteIndex(static::index(), static::type());
}
public static function updateRecord($book_id, $columns){
try{
$record = self::get($book_id);
foreach($columns as $key => $value){
$record->$key = $value;
}
return $record->update();
}
catch(\Exception $e){
//handle error here
return false;
}
}
public static function deleteRecord($book_id)
{
try{
$record = self::get($book_id);
$record->delete();
return 1;
}
catch(\Exception $e){
//handle error here
return false;
}
}
public static function addRecord(Book $book){
$isExist = false;
try{
$record = self::get($book->id);
if(!$record){
$record = new self();
$record->setPrimaryKey($book->id);
}
else{
$isExist = true;
}
}
catch(\Exception $e){
$record = new self();
$record->setPrimaryKey($book->id);
}
$suppliers = [
['id' => '1', 'name' => 'ABC'],
['id' => '2', 'name' => 'XYZ'],
];
$record->id = $book->id;
$record->name = $book->name;
$record->author_name = $image->author_name;
$record->status = 1;
$record->suppliers = $suppliers;
try{
if(!$isExist){
$result = $record->insert();
}
else{
$result = $record->update();
}
}
catch(\Exception $e){
$result = false;
//handle error here
}
return $result;
}
}
Adding filters in query
$filters = [];
$filters['bool']['must'][]['term']['status'] = 1;
//nested filters
$filter = [];
$filter['nested']['path'] = 'suppliers';
$filter['nested']['query']['bool']['must'][]['match']['suppliers.name'] = 'XYZ';
$filter['nested']['query']['bool']['must'][]['match']['suppliers.id'] = 1;
$filters['bool']['must'][] = $filter;
if($filters){
$query->query($filters);
}
Adding sorting in results
$query->orderBy = ['id' => ['order' => 'desc']];
分页
try{
$pages = new Pagination(['totalCount' => $query->count() , "defaultPageSize" => $limit]);
$offset = ($page-1)*$limit;
$query->offset($offset)->limit($limit);
$command = $query->createCommand();
$rows = $command->search();
}
catch(\Exception $e){
$message = $e->getMessage();
return $this->render("/site/error",['name'=> "Search Results",'message' => "Search service is currently not working, Please try again later."]);
}
$aggregations = $rows['aggregations'];
$provider = new ArrayDataProvider([
'allModels' => $rows['hits']['hits'],
'pagination' => [
'pageSize' => $limit,
],
]);
参考文献:http://www.aurigait.com/how-to-use-elastic-search-in-yii2/
yii2中es操作:https://zhuowenji1.gitbooks.io/elasticsearch/content/an_zhuang_yii2.html