Post 从 C++ 程序到 Elastic Search 的数据

Post Data to Elastic Search from a C++ program

我正在尝试从 C++ 程序 post 一些 JSON 数据到 Elastic Search,我正在使用 执行 cURL 命令]系统.

#include<iostream>
#include<string>


using namespace std;

int main()
{      


    system("curl -XPOST \"http://localhost:9200/test/_doc\" -H \"Content-Type: 
    application/json\" -d\"{\"drop\" : 40, \"@timestamp\" : \"2020-05-20T03:05:30\"}\"");


    return 0;

}

它returns出现以下错误:

{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"json_parse_exception","reason":"Unexpected character ('d' (code 100)): was expecting double-quote to start field name\n at [Source: (org.elasticsearch.common.bytes.AbstractBytesReference$MarkSupportingStreamInputWrapper); line: 1, column: 3]"}},"status":400}

我不确定是什么导致了问题,因为我的 PUT 请求正在运行。

system("curl -XPUT \"http://localhost:9200/test5\" -H \"Content-Type: application/json\" -d\"{}\"");

映射是:

"mappings" : {
        "properties" : {
            "drop" : { "type":"long"},
            "@timestamp" : { 
                "type": "date",
                "format": "date_hour_minute_second"
            }
        }
    }
}

您没有在系统调用中正确转义 json 字符串。我认为是 curl 命令还是 shell 捕获它们?

您最终发送到服务器的内容看起来像 {drop : 40, @timestamp : 2020-05-20T03:05:30} 注意:drop 周围没有引号 - 正是错误消息告诉您的内容。

要修复,请尝试在

等系统调用中使用单引号将 json 括起来
 system("curl -XPOST \"http://localhost:9200/test/_doc\" -H \"Content-Type:application/json\" -d \'{\"drop\" : 40, \"@timestamp\" : \"2020-05-20T03:05:30\"}\'");