Elasticsearch 与 Thinkphp 增删改查操作 - Traveler - 开源中国

【新睿云 】云服务器0元/年 >>>   

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。另外,还有下面的一些分析器,这些分析器,可以进入官网进行深入研究。

这些分析器中,重点在于如何对待搜索的目标进行分词(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"
}

下次补齐    有需要的 留言 


Original url: Access
Created at: 2018-10-18 14:33:19
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论