如何在ArangoDb AQL查询中指定数据库

How to specify the database in an ArangoDb AQL query?

本文关键字:数据库 查询 AQL ArangoDb      更新时间:2023-10-16

如果在一个特定的ArangoDB服务器上定义了多个数据库,我如何指定要运行AQL查询的数据库?

通过REST端点运行查询,该端点包括数据库名称(替换为下面的[DBNAME](,即:

/_db/[DBNAME]/_api/cursor

似乎不起作用。错误消息显示"未知路径/db/[DBNAME]/_api/cursor">

这是我必须在查询本身中指定的内容吗?

另外:我试图运行的查询是:

FOR col in COLLECTIONS() RETURN col.name

Fwiw,我还没有找到通过REST API设置"当前"数据库的方法。此外,我正在使用fuerte从C++访问REST API。

Tom Regner 在这里值得称赞,因为他提出了产生这个答案的询问。我将我的发现发布在这里,作为帮助其他可能遇到这种情况的人的答案。

我不知道这是一个fuerte错误、缺点还是只是一个我不清楚的api警告…但是。。。

为了在一个端点(例如完整端点">/_db/[DBNAME/_api/cursor'(中注册并在一个::arangodb::fuerte::Request的标头中使用前缀">/_db/[DBNAME/\",仅调用:是不够的(从arangodb 3.5.3和本次应答时可用的fuerte版本开始(

std::unique_ptr<fuerte::Request> request;
const char *endpoint = "/_db/[DBNAME/_api/cursor";
request = fuerte::createRequest(fuerte::RestVerb::Post,endpoint);
// and adding any arguments to the request using a VPackBuilder...
// in this case the query (omitted)

要将数据库名称包含在这样的请求中,您必须另外调用以下命令:

request->header.parseArangoPath(endpoint);

如果不这样做,似乎会导致有关"未知路径">的错误。

注意1:只需设置数据库成员变量,即

request->header.database = "[DBNAME]";

不起作用。

注意2:没有前导'/_db/[DBNAME]/前缀的操作,使用'current'数据库似乎可以正常工作。(至少对我来说,它似乎被困在了"_system"上,因为据我所知,似乎没有一个端点可以通过HTTP REST Api来改变这一点。(

文档现在没有太大帮助,所以如果有人正在寻找更完整的示例,请考虑以下代码。

EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
.authenticationType(AuthenticationType::Basic)
.user(?)      // enter a user with access
.password(?)  // enter the password
.connect(eventLoopService);
// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);
// enter the database name (ensure the user has access)
request->header.database = ?;
// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";
// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();
// add the payload to the request
request->addVPack(builder.slice());
// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));
// check the response code - it should be 201
unsigned int statusCode = response->statusCode();
// slice has the response data
VPackSlice slice = response->slices().front();
std::cout << slice.get("result").toJson() << std::endl;