使用PHP中的curl获得Elasticsearch结果
我在AWS上设置了一个Ubuntu 18.04实例,并在其上安装了Elasticsearch版本7。我还为它分配了一个FQDN 我举了一个例子,把莎士比亚的全部作品都放在上面。我安装了 从我的Mac,使用终端,我ssh’ed到AWS实例(使用其FQDN),并从终端执行以下操作:使用PHP中的curl获得Elasticsearch结果,php,
elasticsearch,curl,Php,
elasticsearch,Curl,我在AWS上设置了一个Ubuntu 18.04实例,并在其上安装了Elasticsearch版本7。我还为它分配了一个FQDN 我举了一个例子,把莎士比亚的全部作品都放在上面。我安装了 从我的Mac,使用终端,我ssh’ed到AWS实例(使用其FQDN),并从终端执行以下操作: curl -H "Content-Type: application/json" -XGET '127.0.0.1:9200/shakespeare/_search?pretty' -d' > { >
curl -H "Content-Type: application/json" -XGET '127.0.0.1:9200/shakespeare/_search?pretty' -d'
> {
> "query":
> {
> "match_phrase": {
> "text_entry":"to be or not to be"
> }
> }
> }'
我得到一个答案:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 13.889601,
"hits" : [
{
"_index" : "shakespeare",
"_type" : "_doc",
"_id" : "34229",
"_score" : 13.889601,
"_source" : {
"type" : "line",
"line_id" : 34230,
"play_name" : "Hamlet",
"speech_number" : 19,
"line_number" : "3.1.64",
"speaker" : "HAMLET",
"text_entry" : "To be, or not to be: that is the question:"
}
}
]
}
}
我尝试编写一个PHP脚本,做同样的事情,如下所示:
<?php
$query = '{
"query":
{"match_phrase":{
"text_entry":"to be or not to be"
}
}
}';
$url = 'http://myserver.com:9200?shakespeare/_search?pretty';
$method = "GET";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$result = array('info' => curl_getinfo($ch), 'op_result' => json_decode(curl_exec($ch), TRUE));
print_r($result);
有什么想法吗?把你的卷发放到Postman中,用PHP生成代码
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '127.0.0.1:9200/shakespeare/_search?pretty');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "\n{\n\"query\":\n {\n \"match_phrase\": {\n \"text_entry\":\"to be or not to be\"\n }\n }\n}");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
您不会手动编写HTTP请求,是吗?我强烈建议使用for this,而不是
curl
。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '127.0.0.1:9200/shakespeare/_search?pretty');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "\n{\n\"query\":\n {\n \"match_phrase\": {\n \"text_entry\":\"to be or not to be\"\n }\n }\n}");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);