首页 > 科技 > tp5集成ElasticSearch

tp5集成ElasticSearch

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

namespaceHome\Model; 
useThink\Model;
require'vendor/autoload.php';
useElasticsearch\ClientBuilder;classTestModelextendsModel{
tProtected $autoCheckFields =false;
tProtected $elkclient =null;
tpublicfunction __construct(){
tt$hosts =['10.27.34.1:9200'];//连接ip 端口
tt$this->elkclient =ClientBuilder::create()->setHosts($hosts)->build();
t}
tpublicfunctionAdd($index,$type,$data)
t {
t t$params =[
tt 'index'=> $index,//索引
tt 'type'=> $type,//类型
tt 'body'=> $data
tt];
t treturn $this->elkclient->index($params);
t }t

}?>

TestController.class.php 中调用

publicfunction 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"}

本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.sosokankan.com/article/1997228.html

setTimeout(function () { fetch('http://www.sosokankan.com/stat/article.html?articleId=' + MIP.getData('articleId')) .then(function () { }) }, 3 * 1000)