单独安装elasticsearch的php类库
composer require elasticsearch/elasticsearch
使用类库:
require_once( './vendor/autoload.php');
$esclient = Elasticsearch\ClientBuilder::create()
->setHosts(["192.168.8.115:9200"])
->build();
**
laravel中安装elasticsearch
**
进入laravel框架后,执行:
composer require elasticsearch/elasticsearch
1.在创建的方法中,使用如下代码:
use Elasticsearch\ClientBuilder;
$esclient = ClientBuilder::create()
->setHosts(["192.168.8.115:9200"]) //IP:端口号
->build();
2.创建索引
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => '10',
'body' => [
'testField' => 'abc',
'title' => '你好,从纵向即文档这个维度来看,每列代表文档包含了哪些单词,。'
]
];
$res=$esclient->index($params);
echo '<pre/>';
print_r($res);
3.针对数据库中某一条记录创建/更新索引
读取到数据库的数据为
d
a
t
a
。
假
设
某
条
记
录
的
值
是
data。 假设某条记录的值是
data。假设某条记录的值是data[0] 并且是 对象格式 可以使用如下代码 如果是数组只需要修 $data[0]->id为 $data[0][‘id’]。
$params = [
'index' => 'my_index_user',
'type' => 'my_type_user',
'id' => $data[0]->id,
];
unset($data[0]->id);
foreach ($data[0] as $k => $v){
$params['body'][$k] = $v;
}
$res=$esclient->index($params);
print_r($res);
3-1.读取所有数据,循环构建数组并且在循环中请求
foreach($data as $kk=>$vv){
$params = [
'index' => 'my_index_user',
'type' => 'my_type_user',
'id' => $data[$kk]->id,
];
unset($data[$kk]->id);
foreach ($data[$kk] as $k => $v){
$params['body'][$k] = $v;
}
$res=$esclient->index($params);
print_r($res);
}
4.批量索引
$params = [
'index' => 'my_indexa',
'type' => 'my_typea',
'body' => [
['index' => [ '_id' => 1]],
[
'testField' => 'abc',
'title' => '你好,从纵向即文档这个维度来看,每列代表文档包含了哪些单词,。',
'content' => '中国非常强大的哈哈哈,不错,及时这个时代的步伐,研究红色呢过名生命科学'
],
['index' => [ '_id' => 2]],
[
'testField' => '青山绿水',
'title' => '无名英雄',
'content' => '力量是非常强大'
],
['index' => [ '_id' => 3]],
[
'testField' => 'abc',
'title' => '代码的力量',
'content' => '天天上学'
]
]
];
$res=$esclient->bulk($params);
print_r($res);
4-1.读取所有数据,循环构建一个大数组,最后请求接口一次
$params = [
'index' => 'my_index_user1',
'type' => 'my_type_user1'
];
$addpar=[];
foreach($data as $key=>$val){
$params['body'][]= ['index' => [ '_id' => $val->id]];
unset($val->id);
foreach($val as $k=>$v){
$addpar[$k]=$v;
}
$params['body'][]=$addpar;
}
$res = $esclient->bulk($params);
print_r($res);
5.获取和删除
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => '10',
];
$esclient->get($params);
$esclient->delete($params);
6.单字段检索
$search_params = [
'index' => 'my_index',
'type' => 'my_type',
'body'=> [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$res=$esclient->search($search_params);
print_r($res);
7.多字段检索
$search_params = [
'index' => 'my_index',
'type' => 'my_type',
'body'=> [
'query' => [
'bool' => [
'should' => [
['match' => ['testField' => 'abc']],
['match' => ['title' => '中']]
]
]
]
]
];
$res=$esclient->search($search_params);
print_r($res);