参考文档如https://neo4j.com/docs/http-api/current/actions/
java,python的接口容易找到,但是C++的接口不太好用,看到neo4j有http api,这个能完全跨平台,所以决定使用。但是这个官方文档和网上文档很少找到完整的C++通过http api使用neo4j的例子。请大伙儿给个简单的实例启发下我?目前不考虑很高的性能。
以下是一个简单的 C++ 示例代码,它通过 HTTP API 与 Neo4j 数据库进行交互。在这个示例中,我们使用了 C++ 的 Boost 库来处理 HTTP 请求和响应,同时使用了 RapidJSON 库来解析 JSON 数据。
在开始之前,请确保已经安装了 Boost 和 RapidJSON 库,以及可以访问 Neo4j 数据库的 HTTP API。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
using namespace boost::asio;
using boost::asio::ip::tcp;
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
using rapidjson::Document;
using rapidjson::Value;
using rapidjson::StringBuffer;
using rapidjson::Writer;
std::string send_request(const std::string& request)
{
io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost", "7474");
tcp::socket socket(io_service);
connect(socket, resolver.resolve(query));
boost::asio::streambuf request_buf;
std::ostream request_stream(&request_buf);
request_stream << "POST /db/data/transaction/commit HTTP/1.1\r\n";
request_stream << "Host: localhost\r\n";
request_stream << "Accept: application/json; charset=UTF-8\r\n";
request_stream << "Content-Type: application/json\r\n";
request_stream << "Content-Length: " << request.length() << "\r\n";
request_stream << "\r\n";
request_stream << request;
write(socket, request_buf);
boost::asio::streambuf response_buf;
boost::asio::read_until(socket, response_buf, "\r\n");
std::istream response_stream(&response_buf);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
boost::asio::read_until(socket, response_buf, "\r\n\r\n");
std::stringstream ss;
ss << &response_buf;
std::string headers = ss.str();
boost::asio::streambuf::const_buffers_type cbt = response_buf.data();
std::string content(boost::asio::buffers_begin(cbt),
boost::asio::buffers_end(cbt));
return content;
}
int main()
{
// 构造 Neo4j 查询语句
Value statement(Value::kObjectType);
statement.AddMember("statement", "MATCH (n) RETURN n LIMIT 1", allocator);
Value statements(Value::kArrayType);
statements.PushBack(statement, allocator);
Value payload(Value::kObjectType);
payload.AddMember("statements", statements, allocator);
StringBuffer sb;
Writer<StringBuffer> writer(sb);
payload.Accept(writer);
std::string payload_str = sb.GetString();
// 发送 HTTP 请求
std::string response_str = send_request(payload_str);
// 解析 JSON 响应
Document response;
response.Parse(response_str.c_str());
Value& result = response["results"][0]["data"][0]["row"][0];
// 输出查询结果
std::cout << result.GetString() << std::endl;
return 0;
}