首先说明一点,es本身是不具有id自增的功能,我们可以通过代码去实现它。但是,非常不建议这样做,这样会造成es的压力过大,如果记录的是日志的话,很容易挂掉。
上代码
$client = ClientBuilder::create()
->setHosts(['10.254.19.179:9200'])
->build();
//创建索引
$params = [
'index' => 'test_index',
'type' => 'test_type',
'body' => []
];
return $client->index($params);
//删除索引
$params = ['index' => 'test_index'];
return $client->indices()->delete($params);
//查询索引是否存在
$params = ['index' => 'test_index'];
return $client->indices()->exists($params);
//获取索引结构
$params = ['index' => 'test_index'];
return $client->indices()->get($params);
//存数据
$params = [
'index' => 'test_index',
'type' => 'test_type',
'id' => 1,
'body' => [
'name' => 'fanbin',
'sex' => 1,
'age' => 18
]
];
return $client->indices()->delete($params);
//查询索引下的type下的总条数
$params = ['index' => 'test_index', 'type' => 'test_type'];
return $client->count($params);
//利用type总数计算数据id 实现id自增
$params = ['index' => 'test_index'];
$result = $client->indices()->exists($param);
$param['type'] = $tableName;
if (!$result) {
$param['body'] = [];
//创建索引
$client->index($param);
}
$param['id'] = $client->count($param)['count'];
if (!$param['id']) {
$param['id'] = 1;
}
$param['body'] = [
'name' => 'test_name',
'sex' => 1,
'age' => 10
];