简体   繁体   中英

elasticsearch query and cURL in PHP no results

i tried to using PHP to execute the cURL request and separate curl var_dump output into different variables?but didn't shown anything in php and No errors in PHP logs.

Here is my code:

$url='curl -XGET <my_url>:9200/logstash-index-*/_search?pretty -d \'
 {

    "size": 0,
     "aggs" : {
        "langs" : {
                "terms" : { 
                   "field" : "name" ,
                    "size": 0
                          }
                  }
             }
  }\'';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$data = ob_get_contents();
ob_end_clean();
var_dump($data);

Thanks for help!

You are currently mixing up two things here, the linux cURL command and the php_curl commands.

Here is a linux command to type in a bash / sh for example :

curl -XGET <my_url>:9200/logstash-index-*/_search?pretty -d '
{
"size": 0,
 "aggs" : {
    "langs" : {
            "terms" : { 
               "field" : "name" ,
                "size": 0
                      }
              }
         }
}'

And here is the same example using php_curl :

$url = '<my_url>:9200/logstash-index-*/_search?pretty';
$data = array(
    "size" => 0,
    "aggs" => array (
        "langs" => array (
                "terms" => array ( 
                   "field" => "name" ,
                    "size" => 0
                )
        )
    )
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch) or die(curl_error());
curl_close($ch);
//var_dump($return);

//return is json_encoded, you can decode it to have an array
$array_return = json_decode($return,true);

$aggregationsArray = array(); 
foreach($array_return['aggregations']['name']['buckets'] as $person) 
{
    $aggregationsArray[$person['key']] = $person['doc_count']; 
}
var_dump($aggregationsArray);

Edit1 : Post data must be json_encoded
Edit2 : Return is json_encoded, decode it with json_decode
Edit3 : Add customized loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM