N1QL REST API

N1QL provides a REST API to enable clients to execute N1QL statements. The REST API runs synchronously, so once execution of the statement in the request is started, results are streamed back to the client, terminating when execution of the statement finishes. In this section, you will find information about the REST endpoints, request and response parameters, and examples.

The REST endpoints are:

  • http://node:8093/query/service

  • https://node:18093/query/service (for secure access)

where node is the host name or IP address of a computer running the N1QL query engine.

The N1QL REST API query service allows you to execute a N1QL statement.

See Examples for REST API samples.

Request specification

This section describes how to specify requests.

Request format

Here is the format for GET and POST requests.

GET /query/service
POST /query/service
Request parameters

For a table of request parameters that can be passed in a request to the /query/service endpoint with examples, see Request-Level Parameters.

Named parameters

If the statement in a request contains named parameters, the request should contain the parameters described in the following table.

Example 1: A statement containing named parameters.

 SELECT detail FROM emp WHERE name = $nval AND age > $aval
Parameter Name Value

statement

SELECT detail FROM emp WHERE name = $nval AND age > $aval

$nval

"smith"

$aval

45

There should be a named parameter in the request for each query parameter in the request’s statement parameter.

The % symbol is the escape character in URIs, so when using % as a wildcard in a query, we need to escape that by replacing it with its corresponding ASCII code %25.

Example 2: A statement containing a wildcard parameter.

$ curl -v http://172.23.99.98:8093/query/service  -d 'statement=SELECT meta().id FROM `travel-sample`  WHERE type = "hotel" and meta().id LIKE $1 &args=["hotel_1002%25"]'

Results:

[
  {
    "id": "hotel_10026"
  },
  {
    "id": "hotel_10025"
  }
]
Positional parameters

If the statement in a request contains positional parameters, the request should contain the parameters described in the following table.

Here is an example of a statement containing positional parameters:

 SELECT detail FROM emp WHERE name = $1 AND hiredate > $2
Parameter Name Value

statement

SELECT detail FROM emp WHERE name = $1 AND age > $2

args

[ "smith", 45 ]

Positional parameters can also be specified in a statement using the question mark (?), so the following statement is an alternative way to specify the same query:

Parameter Name Value

statement

SELECT detail FROM emp WHERE name = ? AND age > ?

args

[ "smith", 45 ]

Consistency parameters

scan_consistency

This parameter specifies the consistency guarantee or constraint for index scanning using one of the values listed in the following table.

Value Description

not_bounded

Default value for single-statement requests.

No timestamp vector is used in the index scan. This is also the fastest mode as we eliminate the cost of obtaining the vector and any wait time for the index to catch up with the vector.

at_plus

This implements bounded consistency. The request includes a scan_vector parameter and a value, which is used as a lower bound. This can be used to implement read-your-own-writes (RYOW).

request_plus

This implements strong consistency per request. Before processing the request, a current vector is obtained. The vector is used as a lower bound for the statements in the request. If there are DML statements in the request, RYOW is also applied within the request.

If request_plus is specified in a query that runs during a failover of an index node, the query waits until the rebalance operation completes and the index data has rebalanced before returning a result.

statement_plus

This implements strong consistency per statement. Before processing each statement, a current vector is obtained and used as a lower bound for that statement.

Default behavior

The default behavior for a single statement is not_bounded. For multi-statement requests, the default behavior is not_bounded for the request overall, and RYOW within the request.

Optional: If you want to disable RYOW within a request, add a separate request_consistency parameter and set it to not_bounded.

scan_vector

See at_plus parameter in the scan_consistency parameters table above.

scan_wait

This parameter is a duration value (units of time) that specifies how much time the indexer is allowed to wait until it can satisfy the required scan_consistency and scan_vector criteria. After receiving the scan request, if the indexer is unable to catch up within that duration and initiate the scan, the indexer aborts with an error and the scan fails.

Authentication parameters

The Query API supports two types of credentials: local (or bucket) and admin. The format is an identity and password:

[local:] <bucket-name>
[admin:] <admin-name>
<password>

Note that identities can be optionally qualified. Clients passing in bucket names as the identity can prefix them with local:. This is to provide clarity and future-proofing for all current and future clients of query services.

Providing credentials in a request

Credentials can be passed via HTTP headers (HTTP basic authentication) or via the creds request parameter. If a request contains both HTTP basic authentication header and a creds parameter, the HTTP basic authentication header is ignored and only the creds parameter is used for authenticating.

HTTP headers (HTTP basic authentication) can only be used to provide a single credential. The creds request parameter contains a JSON array of user/pass objects:

creds=[{"user":"...","pass":"..."},{"user":"...","pass":"..."},...]

The creds request parameter is the only way to provide multiple credentials for a request.

Request content type

For POST requests, you can specify the parameters in the request body in URL-encoded format or JSON format. For GET requests, you specify the parameters in the request URL in URL-encoded format. For URL-encoded parameters, the format is consistent with the syntax for variables according to the RFC 6570.

Response

This section has two subsections: Response HTTP Status Codes and Response Body.

Response HTTP status code

Normal status code:

200 OK — The request completed with or without errors. Any errors or warnings that occurred during the request will be in the response body.

Possible error codes:

400 Bad Request — The request cannot be processed for one of the following reasons:

  • The statement contains a N1QL syntax error.

  • The request has a missing or unrecognized HTTP parameter.

  • The request is badly formatted (for example, the request body contains a JSON syntax error).

401 Unauthorized — The credentials provided with the request are missing or invalid.

403 Forbidden — There is a read-only violation. Either there was an attempt to create or update in a GET request or a POST request where readonly is set or the client does not have the authorization to modify an object (index, keyspace or namespace) in the statement.

404 Not Found — The statement in the request references an invalid namespace or keyspace.

405 Method Not Allowed — The REST method type in the request is unsupported.

409 Conflict — There is an attempt to create an object (keyspace or index) that already exists.

410 Gone — The server is shutting down gracefully. Previously made requests are being completed, but no new requests are being accepted.

500 Internal Server Error — There was an unforeseen problem processing the request.

503 Service Unavailable — There is an issue (that is possibly temporary) preventing the request being processed; the request queue is full or the data store is not accessible.

Response body

The response body has the following structure:

{
"requestID": UUID,
"clientContextID": string,
"signature":
{
	*.* |
	( field_name:    field_type,
	...
	)
	},

"results":
	[
	json_value,
	...
	],
"errors":
	[
	{ "code": int, "msg":  string }, ...
	],
"warnings":
	[
	{ "code": int, "msg": string }, …
	],
"status":  "success",
"metrics":
	{
	"elapsedTime": string,
	"executionTime": string,
	"resultCount": unsigned int,
	"resultSize": unsigned int,
	"mutationCount": unsigned int,
	"sortCount": unsigned int,
	"errorCount": unsigned int,
	"warningCount": unsigned int
	}
}
requestID UUID A unique identifier for the response.

clientContextID

string

The clientContextID of the request, if one was supplied (see client_context _id in Request Parameters).

signature

object

The schema of the results. Present only when the query completes successfully.

results

list

A list of all the objects returned by the query. An object can be any JSON value.

status

enum

The status of the request. Possible values are: success, running, errors, completed, stopped, timeout, fatal.

errors

list

A list of 0 or more error objects. If an error occurred during processing of the request, it will be represented by an error object in this list.

error.code

int

A number that identifies the error.

error.msg

string

A message describing the error in detail.

warnings

list

A list of 0 or more warning objects. If a warning occurred during processing of the request, it is represented by a warning object in this list.

warning.code

int

A number that identifies the warning.

warning.msg

string

A message describing the warning in full.

metrics

object

An object containing metrics about the request.

metrics.elapsedTime

string

The total time taken for the request, that is the time from when the request was received until the results were returned.

metrics.executionTime

string

The time taken for the execution of the request, that is the time from when query execution started until the results were returned.

metrics.resultCount

unsigned int

The total number of objects in the results.

metrics.resultSize

unsigned int

The total number of bytes in the results.

metrics.mutationCount

unsigned int

The number of mutations that were made during the request.

metrics.sortCount

unsigned int

The number of objects that were sorted. Present only if the request includes ORDER BY.

If a query includes ORDER BY, LIMIT, or OFFSET clauses, an application can use the sortCount value to give the overall number of results in a message such as "page 1 of N".

metrics.errorCount

unsigned int

The number of errors that occurred during the request.

metrics.warningCount

unsigned int

The number of warnings that occurred during the request.

Request error and warning format

Errors and warnings have the following format:

{
	"code" : int,
	"msg" : string,
	"name": string,
	"sev" : int,
	"temp" : bool
}

code: A unique number for the error or warning. The code ranges are partitioned by component. The codes can also include parts that indicate severity and transience. code is always present in every condition returned in the Query REST API or captured in a log.

msg: A detailed description of the condition. msg is always present in every condition returned in the Query REST API or captured in a log.

The following elements are optional and can be present in a condition returned in the Query REST API or captured in a log. Additional elements not listed here might also be present. Clients and consumers of the REST API or the logs must accommodate any additional elements.

name: Unique name that has a 1:1 mapping to the code. Uniquely identifies the condition. name is helpful for pattern matching and can have meaning making it more memorable than the code). The name should be fully qualified. Here are some examples:

  • indexing.scan.io_failure

  • query.execute.index_not_found

sev: One of the following N1QL severity levels (listed in order of severity):

  1. Severe

  2. Error

  3. Warn

  4. Info

temp: Indicates if the condition is transient (for example, the queue is full). If the value is false, it tells clients and users that a retry without modification produces the same condition.