Elasticsearch 建模
mappings有點類似我們定義MySQL的數據庫表結構的時候,需要指定每個字段的名字,其數據類型一樣。當然,這個定義過程,也指明瞭這個表結構一共含有多少個字段了。對於ES而言,就相當於指定了一個document有多少field,每個field的數據類型,注意,這個比MySQL定義表過程,還多了一個有用的操作,就是指定每個字段可用的分析器(analyzer). 當然,不指定的話,就是採用默認的standard analyzer,當然你也可以指定某個字段不需要分析器(not_analyzed).
ES支持的數據類型:
- 簡單數據類型: string, date, long, double,integer,boolean 以及ip等等
- 層級結構類型:JSON型的object,嵌套類型 (都是JSON)
- 特殊結構類型:geo_point, geo_shape以及completion。
這些數據類型,可以在創建索引的時候,指定
下面,再來說說分析器analyzer。
ES系統默認提供了很多的分析器,最著名的是standard analyzer。另外,還有下面的一些分析器,這些分析器,可以進入官網進行深入研究。
- Simple Analyzer
- Whitespace Analyzer
- Stop Analyzer
- Keyword Analyzer
- Pattern Analyzer
- Language Analyzers
- Fingerprint Analyzer
這些分析器中,重點在於如何對待搜索的目標進行分詞(token)。
下面,將通過一個簡單的例子,來說說mapping的操作,以及基於standard analyzer
curl -XPUT "localhost:9210/Test" -d '
{
"mappings": {
"Test_Type" : {
"properties" : {
"session" : {"type" :"string","index":"not_analyzed"},
"id":{"type": "long"},
"text" : {"type" :"string","analyzer": "chinese"},
"username" : {"type" :"string","analyzer": "chinese"},
"times":{"type": "date","format":"yyyy-MM-dd HH:mm:ss"},
"type":{"type": "long"}
}
}
}
}'
Elasticsearch 從TP中添加數據
引入客戶端構建器
use Elasticsearch\ClientBuilder;
id 可指定也可無 ,會自動生成id
<?php
namespace Home\Model;
use Think\Model;
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
class TestModel extends Model {
Protected $autoCheckFields = false;
Protected $elkclient = null;
public function __construct(){
$hosts = ['10.27.34.1:9200']; //連接ip 端口
$this->elkclient = ClientBuilder::create()->setHosts($hosts) ->build();
}
public function Add($index,$type,$data)
{
$params = [
'index' => $index,//索引
'type' => $type,//類型
'body' => $data
];
return $this->elkclient->index($params);
}
}
?>
TestController.class.php 中調用
public function add(){
if(IS_POST){
$post_data = I('post.');
$result = D('Test')->Add($post_data);
if($result){
$this-> success("添加成功!",U('index'));
}else{
$this -> error("添加失敗!");
}
}
$this -> display();
}
傳入的數據格式
array(16) {
["session"]=>
string(4) "Test"
["serverid"]=>
string(1) "1"
["starttime"]=>
string(10) "2017-05-03"
["endtime"]=>
string(10) "2017-05-10"
["username"]=>
string(4) "Test"
["agentname"]=>
string(4) "Test"
["ip"]=>
string(11) "192.168.2.1"
}
下次補齊 有需要的 留言