今日目标
在项目中使用Elasticsearch-PHP的API
项目:用户管理系统
现在有一个项目是做一个用户管理系统,要求可以对用户的信息实现增删改查,用户的信息包括
<姓名(name),性别(sex),年龄(age),身份证号(idcard)>
元数据数据字典
_index:info_manager
_type : user
_id:自动生成
插入用户
$data = [
'name' => $request->name,
'sex' => $request->sex,
'age' => $request->age,
'idcard' => $request->idcard,
'created_at' => date('Y-m-d H:i:s', time()),
'updated_at' => date('Y-m-d H:i:s', time()),
];
$params = [
'index' => $this->index,
'type' => $this->type,
'body' => $data,
];
$exists = app('es')->search([
'index' => $this->index,
'type' => $this->type,
'body' => [
'query' => [
'match' => [
'idcard' => $request->idcard,
],
],
],
]);
if ($exists['hits']['hits']) {
return '已经存在该用户';
}
$response = app('es')->index($params);
if ($response['result'] == 'created') {
return '创建成功';
}
return '创建失败';
}
查找姓名为“张三”的用户
public function get(Request $request)
{
$exists = app('es')->search([
'index' => $this->index,
'type' => $this->type,
'body' => [
'query' => [
'match' => [
'name' => $request->name,
//'idcard' => $request->idcard,
],
],
],
]);
if ($exists['hits']['hits']) {
return $exists['hits']['hits'];
}
return '不存在该用户';
}
- 响应
[
{
"_index": "info_manager",
"_type": "user",
"_id": "SBQ5qHwBQ6qKqx4bjNy_",
"_score": 4.60517,
"_source": {
"name": "张三",
"sex": "男",
"age": "28",
"idcard": "61062164545212444121221",
"created_at": "2021-10-22 13:38:36",
"updated_at": "2021-10-22 13:38:36"
}
}
]
修改id为xx的用户年龄
public function update(Request $request)
{
$exists = app('es')->exists([
'index' => $this->index,
'type' => $this->type,
'id' => $request->id,
]);
if ($exists) {
$response = app('es')->update([
'index' => $this->index,
'type' => $this->type,
'id' => $request->id,
'body' => [
'doc' => [
'age' => $request->age,
],
],
]);
return $response;
}
return '资源不存在';
}
列出所有用户
public function list(Request $request)
{
$params = [
'index' => $this->index,
'type' => $this->type,
];
$response = app('es')->search();
return $response['hits']['hits'];
}
删除id为xx的用户
public function del(Request $request)
{
$params = [
'index' => $this->index,
'type' => $this->type,
'id' => $request->id,
];
$response = app('es')->delete($params);
return $response;
}
明日计划
进一步学习在项目中使用es实现一些较复杂的功能,分页查询,统计等
总结
项目中是可以用ES实现数据库的各种操作,但感觉对比数据库的使用,好像稍微有些麻烦,比如每次需要去指定index和type,这个可以通过封装去实现,或者去使用其他封装好的,更贴近数据库使用习惯的插件去使用
网友评论