PHP 中運用 elasticsearch


PHP擴展安裝

1. 環境要求:PHP_VERSION >= 5.3.9,composer工具


2. 在E盤新建文件夾命名為elastic,,拷貝composer.phar到
     E:/elastic目錄下面


3. 打開命令行窗口,進入E:/elastic


4. 在命令行運行:
      php composer.phar require elasticsearch/elasticsearch


5. 此時E:/elastic目錄下會出現一個vendor目錄,安裝成功


6. 使用方法:
       require 'vendor/autoload.php'; 
      $client = new Elasticsearch\Client();



創建索引


 

  1. include('./vendor/autoload.php');  
  2. $elastic = new Elasticsearch\Client();  
  3. $index[‘index’] = ‘log’;  //索引名稱  
  4. $index[‘type’] = ‘ems_run_log’; //類型名稱  
  5. $data[‘body’][‘settings’][‘number_of_shards’] = 5;  //主分片數量  
  6. $data[‘body’][‘settings’][‘number_of_replicas’] = 0; //從分片數量  
  7. $elastic->indices()->create($index);  

 


插入索引數據

 

  1. include('./vendor/autoload.php');  
  2.   $elastic = new Elasticsearch\Client();  
  3.   $index[‘index’] = ‘log’; //索引名稱  
  4.   $index[‘type’] = ‘ems_run_log’; //類型名稱  
  5.   $index[‘id’] = 1   //不指定id,系統會自動生成唯一id  
  6.   $index[‘body’] = array(  
  7.       ‘mac’ => 'fcd5d900beca',  
  8.       ‘customer_id’ => 3,  
  9.       ‘product_id’ => 5,  
  10.       ‘version’ => 2  
  11.   );  
  12.   $elastic->index($index);  


 

查詢

 

  1. include('./vendor/autoload.php');  
  2.   $elastic = new Elasticsearch\Client();  
  3.   $index[‘index’] = ‘log’; //索引名稱  
  4.   $index[‘type’] = ‘ems_run_log’; //類型名稱  
  5.   $index[‘body’][‘query’][‘bool’][‘must’] = array(  
  6.         array(‘match’ => array(‘mac’ => ‘fcd5d900beca’)),  
  7.         array(‘match’ => array(‘product_id’ => 20))  
  8.        );  
  9.   $index[‘size’] = 10;  
  10.   $index[‘from’] = 200;  
  11.   $elastic->search($index);  
  12.   
  13.   
  14.  相當於sql語句:  
  15.   select*from ems_run_log where mac=‘fcd5d900beca’  
  16.   and product_id = 20 limit 200,10;  

 


刪除文檔

 

    1. <pre name="code" class="php">include('./vendor/autoload.php');  
    2. $elastic = new Elasticsearch\Client();  
    3. $index['index'] = 'test';  //索引名稱  
    4. $index['type'] = 'ems_test'; //類型名稱  
    5. $index['id'] = 2;   
    6. $elastic->delete($index);  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM