先说一个前提
grafana 和kibana 的时间索引的字段 默认是@timestamp 直接在里面选择索引就可以做过滤选项
前提, 使用官方的php sdk composer 这里就不介绍了 php需要的 libcurl 扩展等 (当然你的php基本都有curl)
然后直接上代码吧
首先肯定要创建一个索引 如果不简历索引 默认直接写入ES的会当成字符串处理 并不会被系统识别成date类型
我们先简单建立两个基础方法
use Elasticsearch\ClientBuilder;
public function esPushIndex($data) //写入数据
{
$hosts = [
'101.19.101.211:9200'
];
$client = ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build(); // Build the client object
return $client->index($data);
}
public function esCreateIndex($params) //创建索引
{
$hosts = [
'101.19.101.211:9200'
];
$client = ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
return $client->indices()->create($params);
}
然后是创建索引
public function actionTestCreateIndex()
{
$params = [
'index' => 'science',
'body' => [
'mappings' => [
'science' => [
// '_source' => [
// 'enabled' => true
// ],
'properties' => [
"@timestamp" =>[
"format"=>"strict_date_optional_time||epoch_millis",
"type" => "date",
]
]
]
]
]
];
$res = $this->esCreateIndex($params);
return $this->successJson($res);
}
创建完索引 之后 我们尝试写入一条数据 这里注意一下, ES 接受的时间数据格式是13位的毫秒时间戳
php 自己的microtime是多了一位的, 所以具体就看代码吧
public function actionTestConfig()
{
$mtimestamp = sprintf("%.3f", microtime(true)); // 带毫秒的时间戳
$params['index'] = 'science';//(string) The name of the index (Required)
$params['type'] = 'point';//(string) The type of the document (Required)
$params['body'] = [ //(array) The document
'request_uri' => $_SERVER['PATH_INFO'] ,
'from' => "teacher",
'@timestamp' => str_replace('.', '', $mtimestamp)
] ;
$res = $this->esPushIndex($params);
return $this->successJson($res);
}
然后我们去kibana management 去简历一个 index patterns建立一个新的查询
image这个时候回默认出现@timestamp的filter 点击创建完成 ,然后回去Discover找到相应的对象就可以看到整体的请求信息和时间戳了
image然后再去操作grafana选择数据库和源 创建相应需要的图表即可
网友评论