A newer version of this documentation is available.

View Latest

N1QL REST API

  • concept
    +

    Overview

    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://10.144.210.101:8093/query/service \
      -u Administrator:password \
      -d 'statement=SELECT meta().id
          FROM `travel-sample`.inventory.hotel
          WHERE 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.

    Example 3. 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 describes the response HTTP status codes.

    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.

    Definitions

    This section describes the properties returned by this REST API.

    Response body

    The response body has the following structure:

    Name Description Schema

    requestID

    A unique identifier for the response.

    string (UUID)

    clientContextID
    Optional

    The client context ID of the request, if one was supplied — see client_context_id in Request parameters.

    string

    signature
    Optional

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

    Examples

    *.*
    field_name: field_type, …​

    object

    results

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

    [ object ] array

    status

    The status of the request.

    enum (success, running, errors, completed, stopped, timeout, fatal)

    errors
    Optional

    An array 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.

    [ Conditions ] array

    warnings
    Optional

    An array 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.

    [ Conditions ] array

    metrics

    An object containing metrics about the request.

    controls
    Optional

    An object containing runtime information provided along with the request. Present only if controls was set to true in the Request parameters.

    Conditions

    Errors and warnings have the following format:

    Name Description Schema

    code
    Required

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

    integer

    msg
    Required

    A message describing the error or warning in detail. This property is always present in every condition returned in the Query REST API or captured in a log.

    string

    name
    Optional

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

    Examples

    indexing.scan.io_failure
    query.execute.index_not_found

    string

    sev
    Optional

    One of the following N1QL severity levels, listed in order of severity:

    1. Severe

    2. Error

    3. Warn

    4. Info

    integer

    temp
    Optional

    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.

    boolean

    Additional elements not listed here might also be present. Clients and consumers of the REST API or the logs must accommodate any additional elements.

    Metrics

    Name Description Schema

    elapsedTime

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

    string

    executionTime

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

    string

    resultCount

    The total number of objects in the results.

    integer (unsigned)

    resultSize

    The total number of bytes in the results.

    integer (unsigned)

    mutationCount
    Optional

    The number of mutations that were made during the request.

    integer (unsigned)

    sortCount
    Optional

    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".

    integer (unsigned)

    usedMemory
    Optional

    The amount of document memory used to execute the request. This property is only returned if a memory quota was set for the query.

    integer (unsigned)

    errorCount
    Optional

    The number of errors that occurred during the request.

    integer (unsigned)

    warningCount
    Optional

    The number of warnings that occurred during the request.

    integer (unsigned)

    Additional elements not listed here might also be present. Clients and consumers of the REST API or the logs must accommodate any additional elements.

    Controls

    Name Description Schema

    scan_consistency

    The value of the query setting Scan Consistency used for the query.

    string

    use_cbo

    Whether the cost-based optimizer was enabled for the query.

    boolean

    memoryQuota

    The memory quota for the request, in MB. This property is only returned if a memory quota was set for the query.

    integer (unsigned)

    stmtType

    The type of query statement.

    Example

    SELECT

    string

    Additional elements not listed here might also be present. Clients and consumers of the REST API or the logs must accommodate any additional elements.