700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > es的基本操作(创建索引 添加数据 删除数据 判断索引是否存在)

es的基本操作(创建索引 添加数据 删除数据 判断索引是否存在)

时间:2021-02-16 13:10:26

相关推荐

es的基本操作(创建索引 添加数据 删除数据 判断索引是否存在)

1、创建索引+ik分词器

/*** 创建es索引* $indexName 索引名称*/public function createEsIndex($indexName){$esClient = $this->esClient;$params = ['index' => $indexName,//索引名称'body' => ['settings' => [ //配置'number_of_shards' => 3,//主分片数'number_of_replicas' => 2//主分片的副本数],'mappings' => [//映射'_source' => [// 存储原始文档'enabled' => true],'properties' => [//配置数据结构与类型'name' => [//字段1'type' => 'text',//类型 string、integer、float、double、boolean、date"analyzer" => "ik_max_word","search_analyzer" => "ik_max_word"]]]]];// Create the index with mappings and settings now$response = $esClient->indices()->create($params);return $response;}

2、添加数据

/*** es数据的添加* $indexName 索引名称* $addData 添加的数据*/public function esDataAdd($indexName,$addData){$esClient = $this->esClient;//判断es索引是否存在$getIndexExistRes = $this->esIndexExist($indexName);if(!$getIndexExistRes){//不存在//创建es索引$this->createEsIndex($indexName);}//参数$params = ['index' => $indexName,//索引名称'type' => '_doc','id' => $addData['id'],'body' =>$addData];$addResponse = $esClient->index($params);return $addResponse;}

3、删除索引

/**删除索引* @return array* $indexName 索引名称*/public function esDelIndex($indexName){$params = ['index' => $indexName];return $this->esClient->indices()->delete($params);}

4、es搜索+ik分词器 高亮显示

/*** 搜索索引数据* $indexName 索引名称* $searchWord 搜索的词*/public function searchEsData($indexName, $searchWord){//判断es索引是否存在$getIndexExistRes = $this->esIndexExist($indexName);if (!$getIndexExistRes) {//不存在//创建es索引return '索引不存在';}//设置查询的条件$params = ['index' => $indexName,//索引(类似于库)'type' => '_doc','body' => [//查询内容'query' => ['match' => [//匹配'house_address' => $searchWord//匹配字段]],'highlight' => [//高亮'pre_tags' => ["<em style='color: red'>"],//样式自己写'post_tags' => ["</em>"],'fields' => ["house_address" => new \stdClass()]]]];$results = $this->esClient->search($params);//es搜索//处理高亮显示foreach ($results['hits']['hits'] as $k => $v) {$results['hits']['hits'][$k]['_source']['goods_name'] = $v['highlight']['goods_name'][0];}//获取数据 从二维数组中取出其中一列$getSearchData = array_column($results['hits']['hits'], '_source');return $getSearchData;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。