laravel:使用ik中文分词访问es
一,php代码
1,用composer安装elasticsearch库
[lhdop@blog dignews]$ composer require elasticsearch/elasticsearch
2, 创建索引:
//创建索引
public function create(){
//初始化一个es
$client = $this->_init_es();
$params = [
'index' => 'gsindex', //索引的名称(mysql的表名)
'body' => [
'settings' => [
'number_of_shards' => 5,//设置数据的分片数,默认为5
'number_of_replicas' => 0,//备份数,单个es服务器无需备份
],
'mappings' => [
'properties' => [
'id' => [
'type' => 'integer'
],
'title' => [
'type' => 'text', //text类型,做模糊搜索用
'analyzer'=>'ik_max_word',//较细粒度分词,写入数据用 需要安装ik并将ik放入es的plugin中
'search_analyzer'=>'ik_smart',//较细粒度分词,查询数据用 需要安装ik并将ik放入es的plugins中
],
'content' => [
'type' => 'text', //text类型,做模糊搜索用
'analyzer'=>'ik_max_word',//较细粒度分词,写入数据用 需要安装ik并将ik放入es的plugin中
'search_analyzer'=>'ik_smart',//较细粒度分词,查询数据用 需要安装ik并将ik放入es的plugins中
],
],
],
],
];
$response = $client->indices()->create($params);
print_r($response->asArray());
//return 'Hello, World!'.$msg;
}
3,索引数据
//多数据索引
public function mindex(){
//初始化一个es
$client = $this->_init_es();
$d1 = ['id'=>1,'title'=>'北京房产','content'=>'北京房产,天通苑'];
$d2 = ['id'=>2,'title'=>'沧州房产','content'=>'河北沧州房产,沧县,任丘'];
$d3 = ['id'=>3,'title'=>'石家庄房产','content'=>'河北石家庄房产,获鹿,正定'];
$d4 = ['id'=>4,'title'=>'石家庄土地','content'=>'河北石家庄土地,新华,赵县'];
$data = [$d1,$d2,$d3,$d4];
foreach ($data as $k => $one) {
$params = [
'index' => 'gsindex',
//'type' => '_doc',
//'id' => $item->id,
'body' => [
'id' => $one['id'],
'title' => $one['title'],
'content' => $one['content'],
],
];
$rs = $client -> index($params);
var_dump($rs);
}
}
4, 搜索:
//搜索多个字段
public function msearch() {
//初始化一个es
$client = $this->_init_es();
//总结:and用must,or用should
$esWhere = [];
//如果需要 同时满足多个查询条件(and查询),则复制下面参数,改title为 descs即可
/*
$esWhere['bool']['must'] = [
['match' => [
'content' =>'河北'
]],
['match' => [
'title' =>'房产'
]],
];
*/
//条件之间是or的关系
$boolshould = [];
$boolshould['bool']['should'] = [
['match' => [
'content' =>'河北'
]],
['match' => [
'title' =>'房产'
]],
];
//范围搜索
$range= ['range' => [
'id' => [
'gte' => 2 // gte 表示大于等于
]
]];
//搜索条件:id>=2,且content包含河北或title包含房产
$esWhere['bool']['must'] = [
$range,
$boolshould
];
//按id排序
$sortOrder = ['id'=>'asc'];
$where = [
'index'=>'gsindex',
'size'=>10,
'from'=>0,
//'type'=>'_doc',
'body' => [
'query' =>$esWhere,//查询条件
'sort' =>$sortOrder,//排序条件,注意 添加后 返回结果 无_score值
]
];
$client = $this->_init_es();
$rs = $client->search($where);
$data = $rs->asArray();
//print_r($rs->asArray());
$json = json_encode($data);
echo $json;
/*
foreach ($data['hits']['hits'] as $k => $one){
print_r($one);
}
*/
}
二,测试效果:
访问搜索页面的结果:
如图:
三,查看laravel版本:
[lhdop@blog dignews]$ php artisan --version
Laravel Framework 11.15.0