NAV

Introduction

Welcome to the Kuzzle SDK Documentation!

Here is the list of currently implemented SDKs:

Kuzzle

This is the main entry point to communicate with Kuzzle. Every other objects inherits properties from this one.

Constructors

Connects to a Kuzzle instance.

var kuzzle = new Kuzzle('localhost', {
  defaultIndex: 'some index',
  autoReconnect: true,
  headers: {someheader: "value"},
  port: 7512
});

// A callback is also available and will be invoked once connected to the Kuzzle instance:
kuzzle = new Kuzzle('localhost', function (err, res) {
  // ...
});
KuzzleOptions options = new KuzzleOptions();

options.setDefaultIndex("some index")
  .setAutoReconnect(true),
  .setHeaders(new JSONObject().put("someheader", "value"))
  .setPort(7512);

Kuzzle kuzzle = new Kuzzle("localhost", options, new ResponseListener<Void>() {
 @Override
 public void onSuccess(Void object) {
   // invoked once connected, object contains the kuzzle instance
 }

 @Override
 public void onError(JSONObject error) {
   // Handle connection error
 }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost', [
  'defaultIndex' => 'some index',
  'port' => 7512
]);

Kuzzle(host, [options], [callback])

Arguments Type Description
host string The server name (or the IP address) of a Kuzzle instance
options JSON object Optional Kuzzle connection configuration
callback function Optional callback

Available options:

Option Type Description Default
autoQueue boolean Automatically queue all requests during offline mode false
autoReconnect boolean Automatically reconnect after a connection loss true
autoReplay boolean Automatically replay queued requests on a reconnected event false
autoResubscribe boolean Automatically renew all subscriptions on a reconnected event true
connect string Manually or automatically connect to the Kuzzle instance auto
defaultIndex string Set the default index to use
headers JSON object Common headers for all sent documents
metadata JSON object Common metadata, will be sent to all future requests
offlineMode string Offline mode configuration manual
port integer Kuzzle network port 7512
queueTTL integer Time a queued request is kept during offline mode, in milliseconds 120000
queueMaxSize integer Number of maximum requests kept during offline mode 500
replayInterval integer Delay between each replayed requests, in milliseconds 10
reconnectionDelay integer number of milliseconds between reconnection attempts 1000
sslConnection boolean Switch Kuzzle connection to SSL mode false

Notes:

  • the offlineMode option only accepts the manual and auto values

Callback response

If the connection succeeds, resolves to the Kuzzle object itself. If the connect option is set to manual, the callback will be called after the connect method is resolved.

Properties

Property name Type Description get/set
autoQueue boolean Automatically queue all requests during offline mode get/set
autoReconnect boolean Automatically reconnect after a connection loss get
autoReplay boolean Automatically replay queued requests on a reconnected event get/set
autoResubscribe boolean Automatically renew all subscriptions on a reconnected event get/set
defaultIndex string Kuzzle’s default index to use get
headers JSON object Common headers for all sent documents. get/set
host string Target Kuzzle host name/address get/set
jwtToken string Token used in requests for authentication. get/set
metadata JSON object Common metadata, will be sent to all future requests get/set
offlineQueue JSON object Contains the queued requests during offline mode get/set
offlineQueueLoader function Called before dequeuing requests after exiting offline mode, to add items at the beginning of the offline queue get/set
port integer Kuzzle network port 7512
queueFilter function Called during offline mode. Takes a request object as arguments and returns a boolean, indicating if a request can be queued get/set
queueMaxSize integer Number of maximum requests kept during offline mode get/set
queueTTL integer Time a queued request is kept during offline mode, in milliseconds get/set
replayInterval integer Delay between each replayed requests get/set
reconnectionDelay integer number of milliseconds between reconnection attempts get

Notes:

  • if connect is set to manual, the connect method will have to be called manually
  • the kuzzle instance will automatically queue all requests, and play them automatically once a first connection is established, regardless of the connect or offline mode option values.
  • multiple methods allow passing specific metadata. These metadata will be merged with the global Kuzzle object metadata when sending the request, with the request specific metadata taking priority over the global ones.
  • the queueFilter property is a function taking a JSON object as an argument. This object is the request sent to Kuzzle, following the Kuzzle API format
  • if queueTTL is set to 0, requests are kept indefinitely
  • The offline buffer acts like a FIFO queue, meaning that if the queueMaxSize limit is reached, older requests are discarded to make room for new requests
  • if queueMaxSize is set to 0, an unlimited number of requests is kept until the buffer is flushed
  • the offlineQueueLoader must be set with a function, taking no argument, and returning an array of objects containing a query member with a Kuzzle query to be replayed, and an optional cb member with the corresponding callback to invoke with the query result
  • the host and port properties can be changed, but it will only be in effect at the next connect call

Offline mode

Working with an unstable network connection implies to handle what an application should be doing while being offline.
Our goal is to provide our users with the right tools to handle such situations.

There are two ways to handle a network disconnection

  • Stop all further communication with Kuzzle and invalidate the current instance and all its children. The application will have to manually instantiate a new Kuzzle object once the network has recovered. To do so, simply pass the autoReconnect option to false when starting a new Kuzzle instance.
  • Reconnect automatically to Kuzzle when possible, and enter offline mode. This is the default behavior.

Offline mode simply refers to the time between a disconnected and a reconnected event.

Handling subscriptions

During offline mode, all subscriptions are kept indefinitely, with no maximum subscriptions retained.

By default, upon reconnection, all subscription are renewed. This behavior can be changed by setting the autoResubscribe to false. In that case, each subscription must be renewed manually using the Room.renew method.

Queuing requests while offline

Requests can be queued while being offline, to be replayed once the network connection has been reestablished.
By default, there is no request queuing.

You can:

  • Queue all requests automatically when going offline by setting the autoQueue option to true
  • Start and stop queuing manually, by using the startQueuing and stopQueuing methods

The queue itself can be configured using the queueTTL and queueMaxSize options.

Filter requests to be queued

After request queuing is activated, by default, all requests are queued.

You can decide to filter some of these requests with the queueFilter property. This property must be set with a function taking the request to be queued as an argument, and it must return a boolean telling the Kuzzle SDK if the request can be queued or not.

Additionally, almost all methods accept a queuable option. If set to false, the request will be discarded if the SDK is disconnected, and it will be played immediately with no queuing otherwise. This option bypasses the queueFilter property.

Handling network reconnection

Once a reconnected event is fired, you may replay the content of the queue with the replayQueue method. Or you can let the SDK replay it automatically upon reconnection, by setting the autoReplay option to true.

Requests are sent to Kuzzle with the replayInterval delay between each one of them.

Requests submitted while replaying the queue are delayed until the queue is empty, to ensure all requests are played in the right order.

Taking control of the offline queue

You can be notified about what’s going on about the offline queue, with the offlineQueuePush and the offlineQueuePop events.

The offlineQueuePush event is fired whenever a request is queued. It provides to its listeners an object containing a query property, describing the queued request, and an optional cb property containing the corresponding callback, if any.

The offlineQueuePop event is fired whenever a request has been removed from the queue, either because the queue limits have been reached, or because the request has been replayed. It provides the removed request to its listeners.

The offlineQueueLoader property allows loading requests to the queue, before any previously queued request. It is invoked every time the SDK starts dequeuing requests.
This property must be set with a function returning an array of objects with the following accessible properties: a query property, containing the request to be replayed, and an optional cb property pointing to the callback to invoke after the completion of the request.

Finally, if the provided methods don’t give you enough control over the offline queue, you can access and edit the queue directly with the offlineQueue property.

Automatic offline-mode

You can set the offlineMode option to auto. This configures the offline mode behavior with the following options:

  • autoReconnect = true
  • autoQueue = true
  • autoReplay = true
  • autoResubscribe = true

Event Handling

The Kuzzle object listens to global events fired by Kuzzle. To subscribe or unsubscribe on these events, simply plug a callback function to the event you want to act upon, using the functions addListener and removeListener.

Here is the list of these special events:

Event Name Description
connected Fired when the SDK has successfully connected to Kuzzle
disconnected Fired when the current session has been unexpectedly disconnected
error Fired when the SDK has failed to connect to Kuzzle. Does not trigger offline mode.
jwtTokenExpired Fired when Kuzzle rejected a request because the authentication token expired.
Provides the request and its associated callback to its listeners
loginAttempt Fired when a login attempt completes, either with a success or a failure result.
Provides a JSON object with the login status to its listeners (see the login method documentation)
offlineQueuePop Fired whenever a request is removed from the offline queue.
Provides the removed request to its listeners
offlineQueuePush Fired whenever a request is added to the offline queue.
Provides to its listeners an object containing a query property, describing the queued request, and an optional cb property containing the corresponding callback
queryError Fired whenever Kuzzle responds with an error
reconnected Fired when the current session has reconnected to Kuzzle after a disconnection, and only if autoReconnect is set to true

Note: listeners are called in the order of their insertion.

addListener

  var listenerId = kuzzle.addListener('connected', function (room, subscription) {
    // Actions to perform when receiving a 'subscribed' global event
  });
String listenerId = kuzzle.addListener(Event.connected, new EventListener() {
  @Override
  public void trigger(Object... args) {
    // Actions to perform when receiving a 'subscribed' global event
  }
});
<?php

$kuzzle->addListener('jwtTokenExpired', function() {
  // Actions to perform when receiving a 'jwtTokenExpired' global event
});

Adds a listener to a Kuzzle global event. When an event is fired, listeners are called in the order of their insertion.

addListener(event, listener)

Arguments Type Description
event string One of the event described in the Event Handling section of this documentation
listener function The function to call each time one of the registered event is fired

Return value

Returns a string containing an unique listener ID.

checkToken

// Using callbacks (NodeJS or Web Browser)
kuzzle.checkToken(token, function (err, res) {
  // ...
});

// Using promises (NodeJS only)
kuzzle.checkTokenPromise(token)
  .then(res => {
    // ...
  });
kuzzle.checkToken("some jwt token", new ResponseListener<TokenValidity>() {
  @Override
  public void onSuccess(TokenValidity tokenInfo) {
    if (tokenInfo.isValid()) {
      // tokenInfo.getExpiresAt() returns the expiration timestamp
    }
    else {
      // tokenInfo.getState() returns the invalidity reason
    }
  }
});
<?php

$result = $kuzzle->checkToken('some jwt token');

/*
$result = [
  'expiresAt' => 1468257834099, //timestamp in milliseconds
  'valid' => true
];
*/

Callback response if the token is valid:

{
  "expiresAt": 1454588077399,
  "valid": true
}

Callback response if the token is invalid:

{
  "valid": false,
  "state": "<invalidity reason>"
}

Checks the validity of a JSON Web Token.

checkToken(token, callback)

Arguments Type Description
token string The token to check
callback function Callback handling the response

Note: this method sends an unauthenticated API call to Kuzzle, meaning it ignores the JWT Token property, even if it has been set.

Callback response

A JSON object with a valid boolean property.
If the token is valid, a expiresAt property is set with the expiration timestamp. If not, a state property is set explaining why the token is invalid.

collection

var collection = kuzzle.collection('collection', 'index');

// or using a default index:
var
  kuzzle = new Kuzzle('localhost', {defaultIndex: 'index'});

collection = kuzzle.collection('collection');
Collection collection = kuzzle.collection("collection", "index");

// or using a default index:
kuzzle.setDefaultIndex("index");
Collection collection = kuzzle.collection("collection");
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

// or using a default index:
$kuzzle = new Kuzzle('localhost', [
  'defaultIndex' => 'some index'
]);
$dataCollection = $kuzzle->collection('collection', 'index');

Instantiates a new Collection object.

collection(collection, [index])

Arguments Type Description
collection string The name of the data collection you want to manipulate
index string The name of the index containing the data collection

If no index is provided, the factory will take the default index set in the main Kuzzle instance. If no default index has been set, an error is thrown.

The index argument takes precedence over the default index.

Return value

Returns a Collection object.

connect

kuzzle.connect();
kuzzle.connect();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Connects to the Kuzzle instance using the provided host in the constructor. Has no effect if connect is set to auto, unless disconnect has been called first.

Return value

Returns the Kuzzle object to allow chaining.

Callback response

If a callback has been provided to the Kuzzle constructor, it will be called with the Kuzzle instance once successfully connected

disconnect

kuzzle.disconnect();
kuzzle.disconnect();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Closes the current connection.

flushQueue

kuzzle.flushQueue();
kuzzle.flushQueue();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Empties the offline queue without replaying it.

Return value

Returns the Kuzzle object to allow chaining.

getAllStatistics

// Using callbacks (NodeJS or Web Browser)
kuzzle.getAllStatistics(function (err, stats) {
  stats.forEach(function (frame) {
    // loop through all returned frames
  });
});

// Using promises (NodeJS only)
kuzzle
  .getAllStatisticsPromise()
  .then(stats => {
    stats.forEach(function (frame) {
      // loop through all returned frames
    });
  });
kuzzle.getAllStatistics(new ResponseListener<JSONArray>() {
  @Override
  public void onSuccess(JSONArray object) {
    // loop through all returned frames
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
};
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$stats = $kuzzle->getAllStatistics();

foreach($stats as $frame) {
  // loop through all returned frames
}

Callback response example:

[{ "connections": { "socketio": 1 },
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "mqtt": 37, "socketio": 17 },
    "failedRequests": { "socketio": 1 },
    "timestamp": "1453110641308" },
  { "connections": { "socketio": 1 },
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "socketio": 34 },
    "failedRequests": { "socketio": 3 },
    "timestamp": "1453110642308" },
  { "connections": {},
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "socketio": 40 },
    "failedRequests": {},
    "timestamp": "1453110643308" }]

Kuzzle monitors active connections, and ongoing/completed/failed requests.
This method returns all available statistics from Kuzzle.

getAllStatistics([options], callback)

Arguments Type Description
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

The response is an array of JSON objects, each one of them being a statistic frame.

getAutoRefresh

// Using callbacks (node.js or browser)
kuzzle.getAutoRefresh('myIndex', function (err, autoRefresh) {
  console.log(autoRefresh);     // true|false
});

// Using promises (node.js)
kuzzle
  .getAutoRefreshPromise('myIndex')
  .then(autoRefresh => {
    console.log(autoRefresh);   // true|false
  });
kuzzle.getAutoRefresh("myIndex", new ResponseListener<Boolean>() {
  @Override
  public void onSuccess(Boolean autoRefresh) {
    // autoRefresh var contains the autoRefresh status of myIndex.
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
}
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$result = $kuzzle->getAutoRefresh('myIndex');

// $result = true | false

The autoRefresh flag, when set to true, will make Kuzzle perform a refresh request immediately after each write request, forcing the documents to be immediately visible to search.

The getAutoRefresh function returns the current autoRefresh status for the given index.

getAutoRefresh([index], [options], callback)

Arguments Type Description
index string Optional index to query. If no set, defaults to Kuzzle.defaultIndex
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

The response is a boolean reflecting the index autoRefreshstatus.

getJwtToken

var jwtToken = kuzzle.getJwtToken();
String jwtToken = kuzzle.getJwtToken();
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
// ...
$token = $kuzzle->getJwtToken();

Get internal jwtToken used to request kuzzle.

getJwtToken()

Return value

Returns the jwtToken property to export previous kuzzle logged connection.

getMyRights

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .getMyRights(function(error, result) {
    // result is a JSON object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .getMyRightsPromise()
  .then((result) => {
    // result is a JSON object
  });

kuzzle
  .security
  .getMyRights(new ResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject rights) {
        // result is a JSON object
    }

    @Override
    public void onError(JSONObject error) {
        // Handle error
    }
  });
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$result = $kuzzle->security()->getMyRights();

// $result is an array

Callback response example:

[
  {
    controller: 'my-controller', action: 'my-action', index: '*', collection: '*',
    value: 'allowed'
  },
  {
    controller: 'another-controller', action: '*', index: 'my-index', collection: '*',
    value: 'conditional'
  }
]

Gets the rights of the current user

getMyRights([options], callback)

Arguments Type Description
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a JSON object.

getServerInfo

// Using callbacks (NodeJS or Web Browser)
kuzzle.getServerInfo(function (err, stats) {
  // ...
});

// Using promises (NodeJS only)
kuzzle.getServerInfoPromise()
  .then(infos => {
  // ...  
  });
kuzzle.getServerInfo(new ResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject result) {
    // Handle success
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$result = $kuzzle->getServerInfo();

// $result is an array

Callback response example:

{
  "kuzzle": {
    "api": {
      "routes": {
        "admin": [
          "deleteCollection",
          "putMapping",
          "getMapping",
          "getStats",
          "getLastStats",
          "getAllStats",
          "truncateCollection",
          "putRole",
          "deleteIndexes",
          "createIndex",
          "deleteIndex",
          "removeRooms"
        ],
        "auth": [
          "login"
        ],
        "bulk": [
          "import"
        ],
        "read": [
          "search",
          "get",
          "count",
          "listCollections",
          "now",
          "listIndexes",
          "serverInfo"
        ],
        "subscribe": [
          "on",
          "join",
          "off",
          "count",
          "list"
        ],
        "write": [
          "create",
          "publish",
          "createOrUpdate",
          "update",
          "delete",
          "deleteByQuery",
          "createCollection"
        ]
      },
      "version": "1.0"
    },
    "memoryUsed": 99901440,
    "nodeVersion": "v4.2.1",
    "plugins": {
      "kuzzle-plugin-auth-passport-local": {
        "activated": true,
        "hooks": [
          "auth:loadStrategies"
        ],
        "name": "kuzzle-plugin-auth-passport-local"
      },
      "kuzzle-plugin-logger": {
        "activated": true,
        "hooks": [
          "log:silly",
          "log:verbose",
          "log:info",
          "log:debug",
          "log:warn",
          "log:error",
          "data:*",
          "subscription:*",
          "websocket:*",
          "prepare:*",
          "cleanDb:done",
          "cleanDb:error",
          "server:*",
          "rabbit:started",
          "rabbit:error",
          "rabbit:stopped",
          "internalBroker:*",
          "room:new",
          "room:remove",
          "workerGroup:loaded",
          "profiling:*"
        ],
        "name": "kuzzle-plugin-logger",
        "version": "1.0.6"
      },
      "kuzzle-plugin-socketio": {
        "activated": true,
        "hooks": [
          "protocol:broadcast",
          "protocol:joinChannel",
          "protocol:leaveChannel"
        ],
        "name": "kuzzle-plugin-socketio",
        "version": "1.0.4"
      }
    },
    "system": {
      "cpus": [
        {
          "model": "Intel(R) Core(TM) i5-4310M CPU @ 2.70GHz",
          "speed": 800,
          "times": {
            "idle": 8859265400,
            "irq": 500,
            "nice": 4325300,
            "sys": 115447100,
            "user": 497028200
          }
        },
        {
          "model": "Intel(R) Core(TM) i5-4310M CPU @ 2.70GHz",
          "speed": 2701,
          "times": {
            "idle": 8848628800,
            "irq": 400,
            "nice": 3648100,
            "sys": 115458300,
            "user": 495154300
          }
        },
        {
          "model": "Intel(R) Core(TM) i5-4310M CPU @ 2.70GHz",
          "speed": 1300,
          "times": {
            "idle": 8875594600,
            "irq": 4200,
            "nice": 3956800,
            "sys": 98348100,
            "user": 538083800
          }
        },
        {
          "model": "Intel(R) Core(TM) i5-4310M CPU @ 2.70GHz",
          "speed": 2701,
          "times": {
            "idle": 8801022600,
            "irq": 0,
            "nice": 3946300,
            "sys": 97387200,
            "user": 552344400
          }
        }
      ],
      "memory": {
        "free": 1651486720,
        "total": 16729739264
      }
    },
    "uptime": "161016.824s",
    "version": "0.9.2"
  },
  "services": {
    "internalCache": {
      "memoryPeak": "4.88M",
      "memoryUsed": "4.88M",
      "mode": "standalone",
      "type": "redis",
      "version": "3.0.2"
    },
    "readEngine": {
      "api": "1.7",
      "lucene": "4.10.4",
      "nodes": {
        "count": {
          "client": 0,
          "data_only": 0,
          "master_data": 1,
          "master_only": 0,
          "total": 1
        },
        "fs": {
          "available": "5.5gb",
          "available_in_bytes": 5996474368,
          "free": "7.4gb",
          "free_in_bytes": 8013250560,
          "total": "36.5gb",
          "total_in_bytes": 39237341184
        },
        "jvm": {
          "max_uptime": "1.9d",
          "max_uptime_in_millis": 171087444,
          "mem": {
            "heap_max": "990.7mb",
            "heap_max_in_bytes": 1038876672,
            "heap_used": "51.8mb",
            "heap_used_in_bytes": 54394592
          },
          "threads": 75,
          "versions": [
            {
              "count": 1,
              "version": "1.8.0_66-internal",
              "vm_name": "OpenJDK 64-Bit Server VM",
              "vm_vendor": "Oracle Corporation",
              "vm_version": "25.66-b01"
            }
          ]
        },
        "os": {
          "available_processors": 4,
          "cpu": [
            {
              "cache_size": "3kb",
              "cache_size_in_bytes": 3072,
              "cores_per_socket": 16,
              "count": 1,
              "mhz": 2701,
              "model": "Core(TM) i5-4310M CPU @ 2.70GHz",
              "total_cores": 4,
              "total_sockets": 4,
              "vendor": "Intel"
            }
          ],
          "mem": {
            "total": "15.5gb",
            "total_in_bytes": 16729739264
          }
        },
        "plugins": [],
        "process": {
          "cpu": {
            "percent": 0
          },
          "open_file_descriptors": {
            "avg": 190,
            "max": 190,
            "min": 190
          }
        },
        "versions": [
          "1.5.2"
        ]
      },
      "spaceUsed": "14.5kb",
      "status": "red",
      "type": "elasticsearch",
      "version": "1.5.2"
    }
  }
}

Retrieves information about Kuzzle, its plugins and active services.

getServerInfo([options], callback)

Arguments Type Description
options JSON object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a JSON object containing server information.

getStatistics

Without argument, retrieves the last statistic frame in an array:

// Using callbacks (NodeJS or Web Browser)
kuzzle.getStatistics(function (err, stats) {
  // ...
});

// Using promises (NodeJS only)
kuzzle
  .getStatisticsPromise()
  .then(stats => {
    // ...
  });
kuzzle.getStatistics(new ResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject object) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$result = $kuzzle->getStatistics();

// $result is an array

Callback response:

[{ "connections": { "socketio": 1 },
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "mqtt": 37, "socketio": 17 },
    "failedRequests": { "socketio": 1 },
    "timestamp": "1453110641308" }]

When providing a timestamp, retrieves all frames recorded after that timestamp:

// Date can be either in ISO format or a timestamp (utc, in milliseconds)
var ts = Date.parse('2015-10-26T12:19:10.213Z');

// Using callbacks (NodeJS or Web Browser)
kuzzle.getStatistics(ts, function (err, stats) {
  // ...
});

// Using promises (NodeJS only)
kuzzle
  .getStatisticsPromise(ts)
  .then(stats => {
    // ...
  });
// Date can be either in ISO format or a timestamp (utc, in milliseconds)
kuzzle.getStatistics("2015-11-15T13:36:45.558Z", new KuzzleResponseListener<JSONArray>() {
  @Override
  public void onSuccess(JSONArray results) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
};
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
// Date can be either in ISO format or a timestamp (utc, in milliseconds)
$date = time() * 1000;
$result = $kuzzle->getStatistics($date);

// $result is an array

Callback response:

[{ "connections": { "socketio": 1 },
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "mqtt": 37, "socketio": 17 },
    "failedRequests": { "socketio": 1 },
    "timestamp": "1453110641308" },
  { "connections": { "socketio": 1 },
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "socketio": 34 },
    "failedRequests": { "socketio": 3 },
    "timestamp": "1453110642308" },
  { "connections": {},
    "ongoingRequests": { "rest": 0, "socketio": 0 },
    "completedRequests": { "socketio": 40 },
    "failedRequests": {},
    "timestamp": "1453110643308" }]

Kuzzle monitors active connections, and ongoing/completed/failed requests.
This method allows getting either the last statistics frame, or a set of frames starting from a provided timestamp.

getStatistics([timestamp], [options], callback)

Arguments Type Description
timestamp Epoch time Optional starting time from which the frames are to be retrieved
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Note: Kuzzle statistics are cleaned up regularly. If the timestamp is set too far in the past, then this method will return all available statistics.

Callback response

Resolves to an array containing one or more statistics frame(s), as JSON objects.

listCollections

// Using callbacks (NodeJS or Web Browser)
kuzzle.listCollections('index', {type: 'stored', from: 0, size: 42}, function (err, collections) {
  // ...
});

// Using promises (NodeJS only)
kuzzle
  .listCollectionsPromise('index', {type: 'stored'})
  .then(collections => {
    // ...
  });
kuzzle.listCollections("index", new ResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject object) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$collections = $kuzzle->listCollections('index', [
  'type' => 'stored',
  'from' => 0,
  'size' => 42
]);

Callback response:

[
  {"name": "realtime_1", "type": "realtime"},
  {"name": "realtime_2", "type": "realtime"},
  {"name": "realtime_...", "type": "realtime"},
  {"name": "realtime_n", "type": "realtime"},
  {"name": "stored_1", "type": "stored"},
  {"name": "stored_2", "type": "stored"},
  {"name": "stored_...", "type": "stored"},
  {"name": "stored_n", "type": "stored"}
]

Retrieves the list of known data collections contained in a specified index.

listCollections([index], [options], callback)

Arguments Type Description
index string Index containing the collections to be listed
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true
from integer Determines the starting point of the pagination. By default, start at the beggining 0
size integer Determines the size of the returned result set. By default, no limit is applied undefined
type string Get either stored collections or realtime ones. By default, list all collections all

If no index argument is provided, the defaultIndex property is used. If no default index is found, this method throws an error.

Callback response

Resolves to a JSON object containing the list of stored and/or realtime collections on the provided index.

listIndexes

// Using callbacks (NodeJS or Web Browser)
kuzzle.listIndexes(function (err, indexes) {
  // ...
});

// Using promises (NodeJS only)
kuzzle
  .listIndexesPromise()
  .then(indexes => {
    // ...
  });
kuzzle.listIndexes(new ResponseListener<String[]>() {
  @Override
  public void onSuccess(String[] result) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$indexes = $kuzzle->listIndexes();

Callback response:

[ "index", "another index", "..."]

Retrieves the list of indexes stored in Kuzzle.

listIndexes([options], callback)

Arguments Type Description
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

The response is an array of index names.

login

// Expiration time is expressed as a string following the
// time conversion library: https://www.npmjs.com/package/ms
 var expiresIn = "1h";

// Using callbacks (NodeJS or Web Browser)
kuzzle.login("local", {username: "username", password: "password"}, expiresIn, function (err, res) {
  // ...
});

// Using promises (NodeJS only)
kuzzle.loginPromise("local", {username: "username", password: "password"}, expiresIn)
  .then(res => {
    // ...
  });
JSONObject credentials = new JSONObject()
  .put("username", "John Doe")
  .put("password", "my secret password");

kuzzle.login("local", credentials, 30000, new ResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject result) {
    // ...
  }

  @Override
  public void onError() {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

// Expiration time is expressed as a string following the
// time conversion library: https://www.npmjs.com/package/ms
$expiresIn = "1h";

try {
  $result = $kuzzle->login('local', [
    'username' => 'myusername',
    'password' => 'secret'
  ], $expiresIn);

  // ...
}
catch (ErrorException $e) {
  // Handle error
}

Log a user according to a strategy and credentials.

If the Kuzzle response contains a JWT Token, the SDK token is set and the loginAttempt event is fired immediately with the following object: { success: true } This is the case, for instance, with the local authentication strategy.

If the request succeeds but there is no token, then it means that the chosen strategy is a two-steps authentication method, like OAUTH. In that case, the loginAttempt event is not fired. To complete the login attempt, the setJwtToken method must be called either with a token or with an appropriate Kuzzle response.

If the login attempt fails, the loginAttempt event is fired with the following response:
{ success: false, error: 'error message' }

login(strategy, [credentials], [expiresIn], [callback])

Arguments Type Description
strategy string Authentication strategy (local, facebook, github, …)
credentials JSON object Optional login credentials, depending on the strategy
expiresIn <varies> Login expiration time
callback function Optional callback handling the response

Note: If the expiresIn argument is not set, the default token expiration value will be taken from the Kuzzle server configuration.

By default, kuzzle embed the plugin kuzzle-plugin-auth-passport-local which provide local stored password authentication strategy. This strategy require username and password as credentials

Callback response

Resolves to a JSON object containing the Kuzzle response.

logout

// Using callbacks (NodeJS or Web Browser)
kuzzle.logout(function (err, res) {
  // ...
});

// Using promises (NodeJS only)
kuzzle.logoutPromise()
  .then(res => {
    // ...
  });
kuzzle.logout(new ResponseListener<Void>() {
  @Override
  public void onSuccess(Void result) {
    // ...
  }

  @Override
  public void onError() {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

try {
  $kuzzle->logout();
  // everything went fine
}
catch (ErrorException $e) {

}

Logs the user out.

logout([callback])

Arguments Type Description
callback function Optional callback handling the response

This method empties the jwtToken property

Return value

Returns the Kuzzle object to allow chaining.

Callback response

Resolves to the Kuzzle object itself once the logout process is complete, either successfully or not.
The Kuzzle object will unset the property jwtToken if the user is successfully logged out.

memoryStorage

A MemoryStorage singleton.

now

// Using callbacks (NodeJS or Web Browser)
kuzzle.now(function (err, res) {
  // 'res' contains the Kuzzle timestamp (utc, in milliseconds)
});

// Using promises (NodeJS only)
kuzzle.nowPromise().then(res => {
  // 'res' contains the Kuzzle timestamp (utc, in milliseconds)
});
kuzzle.now(new ResponseListener<Date>() {
  @Override
  public void onSuccess(Date object) {
    // 'object' contains the Kuzzle timestamp (utc, in milliseconds)
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$kuzzleTime = $kuzzle->now();

// $kuzzleTime instanceof DateTime

Callback response:

1447151167622

Retrieves the current Kuzzle time.

now([options], callback)

Arguments Type Description
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Returns a integer containing the current Kuzzle time, encoded as an UTC Epoch time in milliseconds.

query

// Using callbacks (NodeJS or Web Browser)
kuzzle.query({controller: 'document', action: 'search'}, {match: { message: 'this is a test' }}, function (err, res) {
  // ...
});

// Using promises (NodeJS only)
kuzzle
  .queryPromise({controller: 'document', action: 'search'}, {match: { message: 'this is a test' }})
  .then(result => {

  });
QueryArgs args = new QueryArgs();
args.controller = "document";
args.action = "search";
kuzzle.query(args, new JSONObject(), new OnQueryDoneListener() {
  @Override
  public void onSuccess(JSONObject object) {

  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$queryArgs = [
  'controller' => 'document',
  'action' => 'search'
];

$query = [
  'filter' => [
    'equals' => ['field' => 'value']
  ]
];

try {
  $response = $kuzzle->query($queryArgs, $query);
  // var_dump($response['result']['hits']);
}
catch (ErrorException $e) {

}

Callback response:

{ "error": null,
  "result": {
    "_shards": {
      "failed": 0,
      "successful": 5,
      "total": 5
    },
    "_source": {},
    "action": "search",
    "collection": "foo",
    "controller": "read",
    "hits": {
      "hits": [],
      "max_score": 0,
      "total": 0
    },
    "requestId": "bf87b930-7c02-11e5-ab10-dfa9e9fd2e07",
    "timed_out": false,
    "took": 1
  }
}

Base method used to send queries to Kuzzle, following the API Reference

query(queryArgs, query, [options], [callback])

Argument Type Description
queryArgs JSON object Query base arguments
query JSON object Query to execute
options JSON object Optional parameters
callback function Optional callback

Expected queryArgs content:

Option Type Description Required?
controller string API Controller argument required
action string API Controller action required
index string Index concerned by the action optional
collection string Data collection concerned by the action optional

Available options:

Option Type Description Default
metadata JSON object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Kuzzle object to allow chaining.

Callback response

Resolves to a JSON object containing the raw Kuzzle response.

refreshIndex

kuzzle.refreshIndex('myIndex');
kuzzle.refreshIndex("myIndex");
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

try {
  $kuzzle->refreshIndex('myIndex');
}
catch (ErrorException $e) {

}

When writing or deleting documents in Kuzzle’s database layer, the update needs to be indexed before being reflected in the search index.
By default, this operation can take up to 1 second.

Given an index, the refresh action forces a refresh, on it, making the documents visible to search immediately.

refreshIndex([index], [options], [callback])

Argument Type Description
index string Optional. The index to refresh. If not set, defaults to kuzzle.defaultIndex.
options JSON object Optional parameters
callback function Optional. Callback handling the response.

Available options:

Option Type Description Default
queuable boolean Mark this request as (not)queuable true

Return value

Returns the Kuzzle object to allow chaining.

Callback response

The response is a JSON structure matching the response from Elasticsearch.

removeAllListeners

// Removes all listeners on the "unsubscribed" global event
kuzzle.removeAllListeners('disconnected');

// Removes all listeners on all global events
kuzzle.removeAllListeners();
// Removes all listeners on the "unsubscribed" global event
kuzzle.removeAllListeners(Event.disconnected);

// Removes all listeners on all global events
kuzzle.removeAllListeners();
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

// Removes all listeners on the "jwtTokenExpired" global event
$kuzzle->removeAllListeners('jwtTokenExpired');

// Removes all listeners on all global events
$kuzzle->removeAllListeners();

Removes all listeners, either from a specific event or from all events

removeAllListeners([event])

Arguments Type Description
event string One of the event described in the Event Handling section of this documentation

Return value

Returns the Kuzzle object to allow chaining.

removeListener

kuzzle.removeListener('disconnected', listenerId);
kuzzle.removeListener(Event.disconnected, "listenerId");
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$kuzzle->removeListener('jwtTokenExpired', $listenerId);

Removes a listener from an event.

removeListener(event, listenerID)

Arguments Type Description
event string One of the event described in the Event Handling section of this documentation
listenerID string The ID returned by addListener

Return value

Returns the Kuzzle object to allow chaining.

replayQueue

kuzzle.replayQueue();
kuzzle.replayQueue();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Replays the requests queued during offline mode. Works only if the SDK is not in a disconnected state, and if the autoReplay option is set to false.

Return value

Returns the Kuzzle object to allow chaining.

security

A Security singleton.

setAutoRefresh

kuzzle.setAutoRefresh('myIndex', true);
kuzzle.setAutoRefresh("myIndex", true);
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$kuzzle->setAutoRefresh('myIndex', true);

The autoRefresh flag, when set to true, will make Kuzzle perform a refresh request immediately after each write request, forcing the documents to be immediately visible to search.

Given an index, the setAutoRefresh function updates its autoRefresh status.

setAutoRefresh([index], autoRefresh, [options], [callback])

Argument Type Description
index string Optional The index to set the autoRefresh for. If not set, defaults to kuzzle.defaultIndex.
autoRefresh boolean The value to set for the autoRefresh setting.
options JSON object Optional parameters
callback function Optional Callback handling the response

Available options:

Option Type Description Default
queuable boolean Makr this request as (non)queuable true

Return value

Returns the Kuzzle object to allow chaining.

Callback response

The response is a boolean reflecting the new autoRefresh status.

setDefaultIndex

kuzzle.setDefaultIndex('index');
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$kuzzle->setDefaultIndex('myIndex');

Set the default data index. Has the same effect than the defaultIndex constructor option.

Return value

Returns the Kuzzle object to allow chaining.

updateSelf

var newContent = {
  firstname: 'My Name Is',
  lastname: 'Jonas'
};


// Using callbacks (NodeJS or Web Browser)
kuzzle
  .updateSelf(newContent, function (err, updatedUser) {

  });

// Using promises (NodeJS)
kuzzle
  .updateSelfPromise(newContent)
  .then(updatedUser => {

  });
JSONObject newContent = new JSONObject()
  .put("firstname", "My Name Is")
  .put("lastname", "Jonas");

kuzzle
  .updateSelf(newContent, new ResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php
use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$kuzzle = new Kuzzle('localhost');
$newContent = [
  'firstname' => 'My Name Is',
  'lastname' => 'Jonas'
];

try {
  $updatedUser = $kuzzle->updateSelf($newContent);
  // $updatedUser instanceof User
}
catch (ErrorException $e) {

}

updateSelf(content, [options], [callback])

Performs a partial update on the current user.

Arguments Type Description
content JSON Object A plain javascript object representing the user
options string (Optional) Optional arguments
callback function (Optional) Callback handling the response

Available options:

Filter Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Kuzzle object to allow chaining.

Callback response

Resolves to the updated user plain object.

setHeaders

kuzzle.setHeaders({someContent: 'someValue'}, true);
JSONObject headers = new JSONObject().put("someContent", "someValue");

kuzzle.setHeaders(headers, true);
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$newHeaders = [
  'someContent' => 'someValue'
];

$kuzzle->setHeaders($newHeaders);

This is a helper function returning itself, allowing to easily chain calls.

setHeaders(content, [replace])

Arguments Type Description
content JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns the Kuzzle object to allow chaining.

setJwtToken

// Directly with a JWT Token
kuzzle.setJwtToken('some jwt token');

/*
 Or with a Kuzzle response.
 For instance, the final OAUTH2 response is obtained with a redirection from Kuzzle,
 and it can be provided to this method directly
 */
kuzzle.setJwtToken(authenticationResponse);
// Directly with a JWT Token
kuzzle.setJwtToken("some jwt token");

/*
 Or with a Kuzzle response.
 For instance, the final OAUTH2 response is obtained with a redirection from Kuzzle,
 and it can be provided to this method directly.

 Here, "authenticationResponse" is an instance of JSONObject
 */
kuzzle.setJwtToken(authenticationResponse)
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

// Directly with a JWT Token
$kuzzle->setJwtToken('some jwt token');


/*
 Or with a Kuzzle response.
 For instance, the final OAUTH2 response is obtained with a redirection from Kuzzle,
 and it can be provided to this method directly
 */
 $kuzzle->setJwtToken($authenticationResponse);

Sets the internal JWT token which will be used to request kuzzle.

If the provided token is correct, a loginAttempt event is fired with the following object:
{ success: true }

If not, the loginAttempt event is fired with the following response:
{ success: false, error: 'error message' }

setJwtToken(jwtToken)

setJwtToken(kuzzleResponse)

Arguments Type Description
jwtToken string Previously generated JSON Web Token
kuzzleResponse JSON object Final Kuzzle response from a 2-steps authentication process

Return value

Returns the Kuzzle object to allow chaining.

unsetJwtToken

kuzzle.unsetJwtToken();
kuzzle.unsetJwtToken();
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

$kuzzle->unsetJwtToken();

Unsets the internal JWT token used for authentication, and stops all existing subscriptions

Return value

Returns the Kuzzle object to allow chaining.

startQueuing

kuzzle.startQueuing();
kuzzle.startQueuing();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Starts the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.

Return value

Returns the Kuzzle object to allow chaining.

stopQueuing

kuzzle.stopQueuing();
kuzzle.stopQueuing();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Stops the requests queuing. Works only during offline mode, and if the autoQueue option is set to false.

Return value

Returns the Kuzzle object to allow chaining.

whoAmI

// Using callbacks (NodeJS or Web Browser)
kuzzle.whoAmI(function (err, result) {
  // "result" is a User object
});

// Using promises (NodeJS only)
kuzzle.whoAmIPromise()
  .then(res => {
    // "res" is a User object
  });
kuzzle.whoAmI(new ResponseListener<User>() {
  @Override
  public void onSuccess(User myself) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php
use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$kuzzle = new Kuzzle('localhost');

try {
  $me = $kuzzle->whoAmI();
  // $me instanceof User
}
catch (ErrorException $e) {

}

Retrieves current user object.

whoAmI(callback)

Arguments Type Description
callback function Callback handling the response

Callback response

An instantiated User object.

Collection

In Kuzzle, you manipulate documents and subscriptions, both related to data collections.

A data collection is a set of data managed by Kuzzle. It acts like a data table for persistent documents, or like a room for pub/sub messages.

Constructors

var dataCollection = new Collection(kuzzle, "my-collection", "my-index")
  Collection myCollection = new Collection(kuzzle, "my-collection", "my-index");
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Collection;

$kuzzle = new Kuzzle('localhost');
$dataCollection = new Collection($kuzzle, 'my-collection', 'my-index');

Collection(kuzzle, collection, index)

Arguments Type Description
kuzzle object Kuzzle object
collection string The name of the data collection you want to manipulate
index string Name of the index containing the data collection

Note: It’s recommended to instantiate a Collection object by calling Kuzzle.collection rather than using the constructor directly

Properties

Property name Type Description get/set
kuzzle object linked kuzzle instance get
index object Name of the index containing the data collection get
collection string The name of the data collection handled by this instance get
headers object Headers for all sent documents. get/set

Note: the headers property is inherited from the main Kuzzle object and can be overrided

collectionMapping

var dataMapping = kuzzle
  .collection('collection', 'index')
  .collectionMapping({someField: {type: 'string', index: 'analyzed'}})
  .apply();
CollectionMapping dataMapping = kuzzle
  .collection("collection", "index")
  .collectionMapping(new JSONObject().put("someFiled", new JSONObject().put("type", "string").put("index", "analyzed"))
  .apply();
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\DataMapping;

$mapping = [
  'someField' => [
    'type' => 'string',
    'index' => 'analyzed'
  ]
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $dataMapping = $dataCollection->collectionMapping($mapping);

  // $dataMapping instanceof DataMapping
  $dataMapping->apply();
}
catch (ErrorException $e) {

}

Creates a new CollectionMapping object, using its constructor.

collectionMapping([mapping])

Arguments Type Description
mapping JSON Object Optional mapping

Return value

Returns the newly created CollectionMapping object.

count

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .count({}, function (err, res) {
    // ...
  });

// Using promises (NodeJS only)
kuzzle
 .collection('collection', 'index')
 .countPromise({})
 .then(res => {
   // ...
 });
JSONObject filters = new JSONObject();

kuzzle
  .collection("collection", "index")
  .count(filters, new ResponseListener<Integer>() {
    @Override
    public void onSuccess(Integer object) {
      // Handle success
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;

$filters = [];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $count = $dataCollection->count($filters);
}
catch (ErrorException $e) {
}

Callback response:

12

Returns the number of documents matching the provided set of filters.

count(filters, [options], callback)

Arguments Type Description
filters JSON Object Filters in ElasticSearch Query DSL format
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to the matched documents count as a integer.

create

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .create(function (error, result) {
    // callback called once the create operation has completed
    // => the result is a JSON object containing the raw Kuzzle response
  });

// Using promises (NodeJS only)
kuzzle
 .collection('collection', 'index')
 .createPromise()
 .then(result => {
   // promise resolved once the create operation has completed
   // => the result is a JSON object containing the raw Kuzzle response
 });
kuzzle
  .collection("collection", "index")
  .create(new ResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject object) {
      // callback called once the create operation has completed
      // => the result is a JSON object containing the raw Kuzzle response
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $result = $dataCollection->create();
}
catch (ErrorException $e) {

}

Callback response:

{
  "status": 200,
  "error": null,
  "requestId": "cf1fc8b4-fd87-46c3-b0a2-3d9d2fb7d401",
  "controller": "write",
  "action": "createCollection",
  "collection": "newly created collection",
  "index": "index",
  "metadata": {},
  "state": "done",
  "scope": null,
  "result": {}
}

Create a new empty data collection, with no associated mapping.

create([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to a JSON object containing the raw Kuzzle response.

createDocument

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .createDocument('foobar', {title: 'foo', content: 'bar'}, {updateIfExist: true}, function (err, res) {
    // callback called once the create action has been completed
    // => the result is a Document object
  });

// Using promises (NodeJS only)
kuzzle
 .collection('collection', 'index')
 .createDocumentPromise('foobar', {title: 'foo', content: 'bar'}, {updateIfExist: true})
 .then(res => {
   // promise resolved once the create action has been completed
   // => the result is a Document object
 });
Document myDocument = new Document(collection);
myDocument.setContent("title", "foo");
myDocument.setContent("content", "bar");

kuzzle
  .collection("collection", "index")
  .createDocument(myDocument, new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document object) {
      // callback called once the create action has been completed
      // => the result is a Document object
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';
$documentContent = [
  'title' => 'foo',
  'content' => 'bar'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $document = $dataCollection->createDocument($documentContent, $documentId);

  // $document instanceof Document
}
catch (ErrorException $e) {

}

Create a new document in Kuzzle.

createDocument(Document, [options], [callback])

createDocument([id], content, [options], [callback])

Arguments Type Description
Document object Document object
id string Optional document identifier
content JSON object Content of the document to create
options JSON object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the peristence layer indexation to return (available with Elasticsearch 5.x and above) undefined
updateIfExist boolean If the same document already exists: throw an error if sets to false. Update the existing document otherwise false

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to a Document object containing the newly created document.

delete

deleteDocument

// Deleting one document using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .deleteDocument('document unique ID', function (err, res) {
    // callback called once the delete action has been completed
  });

// Deleting one document using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .deleteDocumentPromise('document unique ID')
  .then(res => {
    // promises resolved once the delete action has been completed
  });

// Deleting multiple documents using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .deleteDocument({filter: {equals: {title: 'foo'}}}, function (err, res) {
    // callback called once the delete with query has been completed
  });

// Deleting multiple documents using promises (NodeJS)
 kuzzle
 .collection('collection', 'index')
 .deleteDocumentPromise({filter: {equals: {title: 'foo'}}})
 .then(res => {
   // promise resolved once the delete by query has been completed
 });
// Deleting one document
kuzzle
  .collection("collection", "index")
  .deleteDocument("document unique ID", new ResponseListener<String>() {
    @Override
    public void onSuccess(String object) {
      // The resulting string contains the deleted document ID
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });

// Deleting multiple documents
JSONObject equalsFilter = new JSONObject()
  .put("filter", new JSONObject()
  .put("equals",
    new JSONObject().put("title", "foo")
  ));

kuzzle
  .collection("collection", "index")
  .deleteDocument(equalsFilter, new ResponseListener<String[]>() {
    @Override
    public void onSuccess(String[] object) {
      // The resulting object contains the list of deleted document IDs
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

// Deleting one document
try {
  $result = $dataCollection->deleteDocument('documentId');
}
catch (ErrorException $e) {

}

// Deleting multiple documents
$filters = [
  'filter' => [
    'equals' => ['field' => 'value']
  ]
];

try {
  $result = $dataCollection->deleteDocument($filters);
}
catch (ErrorException $e) {

}

Callback response:

[ "AVCoeBkimsySTKTfa8AX" ]

Delete either a stored document, or all stored documents matching search filters.

deleteDocument(documentId, [options], [callback])

deleteDocument(filters, [options], [callback])

Arguments Type Description
documentId string Unique document identifier
filters JSON object Filters in ElasticSearch Query DSL format
options JSON object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the peristence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to an array containing the deleted document IDs.

document

var document = kuzzle
  .collection('collection', 'index')
  .document('id', {some: 'content'})
  .save();
Document document = kuzzle
  .collection("collection", "index")
  .document("id", new JSONObject().put("some", "content"))
  .save();
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';
$documentContent = [
  'title' => 'foo',
  'content' => 'bar'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');
$document = $dataCollection->document($documentId, $documentContent);

// $document instanceof Document

try {
  $document->save();
}
catch (ErrorException $e) {

}

Creates a new Document object, using its constructor.

document([id], [content])

Arguments Type Description
id string Optional document unique ID
content JSON object Optional document content

Return value

Returns the newly created Document object.

fetchDocument

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .fetchDocument('documentId', function (error, result) {
    // result is a Document object
  });

// Using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .fetchDocumentPromise('documentId')
  .then(result => {
    // result is a Document object
  });
kuzzle
  .collection("collection", "index")
  .fetchDocument("documentId", new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document object) {
      // result is a Document object
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $document = $dataCollection->fetchDocument($documentId);

  // $document instanceof Document
}
catch (ErrorException $e) {

}

Retrieves a single stored document using its unique document ID.

fetchDocument(documentId, [options], callback)

Arguments Type Description
documentId string Unique document identifier
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a Document object.

fetchAllDocuments

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .fetchAllDocuments(function (error, result) {
    // result is an object containing the total number of documents
    // and an array of Document objects
  });

// Using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .fetchAllDocumentsPromise()
  .then(result => {
    // result is an object containing the total number of documents
    // and an array of Document objects
  });
kuzzle
  .collection("collection", "index")
  .fetchAllDocuments(new ResponseListener<DocumentList>() {
    @Override
    public void onSuccess(DocumentList object) {
      // result is an object containing the total number of documents
      // and an array of Document objects
      for (Document doc : result.getDocuments()) {
        // Get documents
      }

      result.getTotal(); // return total of documents returned
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;
use \Kuzzle\Util\SearchResult;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $result = $dataCollection->fetchAllDocuments();

  // $result instanceof SearchResult

  foreach($result->getDocuments() as $document) {
    // $result instanceof Document
  }
}
catch (ErrorException $e) {

}

Callback response:

{ "total": 3,
  "documents": [<Document>, <Document>, <Document>]
}

Retrieves all documents stored in this data collection.

fetchAllDocuments([options], callback)

Arguments Type Description
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
from integer Upper bounds for paginated results. 0
queuable boolean Mark this request as (not) queuable true
size integer Lower bounds for paginated results. 10

Callback response

Resolves to an object containing:

  • the total number of retrieved documents
  • a array of Document objects

getMapping

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .getMapping(function (error, result) {
    // result is a CollectionMapping object
  });

// Using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .getMappingPromise()
  .then(result => {
    // result is a CollectionMapping object
  });
kuzzle
  .collection("collection", "index")
  .getMapping(new ResponseListener<CollectionMapping>() {
    @Override
    public void onSuccess(CollectionMapping object) {
      // result is a CollectionMapping object
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\DataMapping;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $mapping = $dataCollection->getMapping();

  // $mapping instanceof DataMapping
}
catch (ErrorException $e) {

}

Retrieves the current mapping of this collection.

getMapping([options], callback)

Arguments Type Description
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a CollectionMapping object.

publishMessage

kuzzle
  .collection('collection', 'index')
  .publishMessage({foo: 'bar', baz: 'qux'});
JSONObject message = new JSONObject().put("some", "content");
JSONObject metadata = new JSONObject().put("metadata", "are volatile information");
Options opts = new Options().setMetadata(metadata);

kuzzle
  .collection("collection", "index")
  .publish(message, opts);
<?php

use \Kuzzle\Kuzzle;

$message = [
  'field' => 'value'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $result = $dataCollection->publishMessage($message);
}
catch (ErrorException $e) {

}

Publish a realtime message

publishMessage(Document, [options], [callback])

publishMessage(content, [options], [callback])

Arguments Type Description
Document object Document object
content JSON Object Content of the document to publish
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to a raw Kuzzle response in JSON format.

replaceDocument

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .replaceDocument('documentId', {title: 'foo', content: 'bar'}, function (error, result) {
    // result is a Document object
  });

// Using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .replaceDocumentPromise('documentId', {title: 'foo', content: 'bar'})
  .then(result => {
    // result is a Document object
  });
JSONObject newContent = new JSONObject("new", "document content");

kuzzle
  .collection("collection", "index")
  .replaceDocument("documentId", newContent, new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document document) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';
$documentContent = [
  'field' => 'value'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $document = $dataCollection->replaceDocument($documentId, $documentContent);

  // $document instanceof Document
}
catch (ErrorException $e) {

}

Replace an existing document with a new one.

replaceDocument(documentId, content, [options], [callback])

Arguments Type Description
documentId string Unique document identifier
content JSON Object Content of the document to create
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the peristence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to an updated Document object.

room

var room = kuzzle
  .collection('collection', 'index')
  .room()
  .renew({in: {field: ['some', 'new', 'filter']}}, function (err, res) {
    // handle notifications
  });
JSONObject filters = new JSONObject()
  .put("in",
    new JSONObject("field")
      .put(new JSONArray()
        .put("some")
        .put("filter")
      )
  );

Room room = kuzzle.collection("collection", "index")
  .room()
  .renew(filters, new ResponseListener<NotificationResponse>() {
    @Override
      public void onSuccess(NotificationResponse object) {
        // handle notifications
      }

      @Override
      public void onError(JSONObject error) {
        // Handle notifications error
      }
  });
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Creates a new Room object, using its constructor.

room([options])

Arguments Type Description
options object Subscription configuration

Return value

Returns the newly created Room object.

var filter = {
  filter: {
    and: [
      {
        in: {
          status: ['idle', 'wantToHire', 'toHire', 'riding'],
        }
      },
      {
        in:{
          type: ['cab']
        }
      },
      {
        geo_distance: {
          distance: '10km',
          pos: {
            lat: '48.8566140', lon: '2.352222'
          }
        }
      }
    ]
  },
  aggregations: {
    aggs_name: {
      terms: {
        field: "field_name"
      }
    }
  }
};

kuzzle
  .collection('collection', 'index')
  .search(filter, function (err, res) {
    res.documents.forEach(document => {
      console.log(document.toString());
    });
  });

// Using promises (NodeJS only)
kuzzle
  .collection('collection', 'index')
  .searchPromise({})
  .then(res => {
    res.documents.forEach(document => {
      console.log(document.toString());
    });
  });
JSONObject filter = new JSONObject()
  .put("filter", new JSONObject()
    .put("and", new JSONArray()
      .put(
        new JSONObject().put("in",
          new JSONObject().put("status",
            new JSONArray()
              .put("idle")
              .put("wantToHire")
              .put("toHire")
              .put("riding")
          )
        )
      )
      .put(
        new JSONObject().put("in",
          new JSONObject()
            .put("type", new JSONArray().put("cab"))
        )
      )
      .put(
        new JSONObject().put("geo_distance",
          new JSONObject()
            .put("distance", "10km")
            .put("pos",
              new JSONObject()
                .put("lat", "48.8566140")
                .put("lon", "2.352222")
            )
        )
      )
    )
  )
  .put("aggregations", new JSONObject()
    .put("aggs_name", new JSONObject()
      .put("terms", new JSONObject()
        .put("field", "field_name")
      )
    )
  );

kuzzle
  .collection("collection", "index")
  .search(userFilter, new ResponseListener<DocumentList>() {
    @Override
    public void onSuccess(DocumentList result) {
      for (Document doc : result.getDocuments()) {
        // Get documents
      }

      result.getTotal(); // return total of documents returned

      result.getAggregations(): // return a JSONObject representing the aggregations response
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;
use \Kuzzle\Util\SearchResult;

$filters = [
  'filter' => [
    'and' => [
      [
        'in' => [
          'status' => ['idle', 'wantToHire', 'toHire', 'riding'],
        ]
      ],
      [
        'in' => [
          'type' => ['cab']
        ]
      ],
      [
        'geo_distance' => [
          'distance' => '10km',
          'pos' => [
            'lat' => '48.8566140',
            'lon' => '2.352222'
          ]
        ]
      ]
    ]
  ],
  'aggregations' => [
    'aggs_name' => [
      'terms' => [
        'field' => 'field_name'
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $searchResult = $dataCollection->search($filters);

  // $searchResult instanceof SearchResult
  $searchResult->getTotal();

  foreach($searchResult->getDocuments() as $document) {
    // $document instanceof Document
  }

  // return an array representing the aggregations response
  $searchResult->getAggregations();
}
catch (ErrorException $e) {

}

Callback response:

{ "total": 3,
  "documents": [<Document>, <Document>, <Document>],
  "aggregations": {
    "aggs_name": {"aggregation": "object"}
  }
}

Executes a search on the data collection.

search(filters, [options], callback)

Arguments Type Description
filters JSON object Filters in ElasticSearch Query DSL format
options JSON object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a JSON object containing:

  • the total number of matched documents
  • an array of Document objects
  • an array of aggregations objects if some are provided in the request (see the Elasticsearch documentation for more details)

setHeaders

kuzzle
  .collection('collection', 'index')
  .setHeaders({
    someContent: 'someValue',
    metadata: { someMetaData: ['with', 'some', 'values']}
  }, true);
JSONObject headers = new JSONObject()
  .put("someContent", "someValue")
  .put("metadata", new JSONObject()
    .put("someMetaData", new JSONArray()
      .put("with")
      .put("some")
      .put("values")
    )
  );

kuzzle
  .collection("collection", "index")
  .setHeaders(content, true);
<?php

use \Kuzzle\Kuzzle;

$headers = [
  'someContent' => 'someValue'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');
$dataCollection->setHeaders($headers, true);

This is a helper function returning itself, allowing to easily set headers while chaining calls.

setHeaders(content, [replace])

Arguments Type Description
content JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns the Collection object to allow chaining.

subscribe

kuzzle
  .collection('collection', 'index')
  .subscribe({equals: {title: 'foo'}}, function (error, result) {
    // called each time a new notification on this filter is received
    // check the Room/Notifications section of this documentation
    // to get notification examples
  })
  .onDone(function (err, roomObject) {
    // Handles the subscription result. Can be chained.
  });
JSONObject filter = new JSONObject()
  .put("and", new JSONArray()
    .put(
      new JSONObject().put("in",
        new JSONObject().put("status",
          new JSONArray()
            .put("idle")
            .put("wantToHire")
            .put("toHire")
            .put("riding")
        )
      )
    )
    .put(
      new JSONObject().put("in",
        new JSONObject()
          .put("type", new JSONArray().put("cab"))
      )
    )
    .put(
      new JSONObject().put("geo_distance",
        new JSONObject()
          .put("distance", "10km")
          .put("pos",
            new JSONObject()
              .put("lat", "48.8566140")
              .put("lon", "2.352222")
          )
      )
    )
  );

kuzzle
  .collection("collection", "index")
  .subscribe(filter, new ResponseListener<NotificationResponse>() {
    @Override
    public void onSuccess(NotificationResponse object) {
      // called each time a new notification on this filter is received

      // check the Room/Notifications section of this documentation
      // to get notification examples
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  })
  .onDone(new ResponseListener<Room>() {
    @Override
    public void onSuccess(Room response) {
      // Handle subscription success
    }

    @Override
    public void onError(JSONObject error) {
      // Handle subscription error
    }
  });
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Subscribes to this data collection with a set of filters.

subscribe(filters, [options], callback)

Arguments Type Description
filters JSON Object Filters
options object (Optional) Subscription configuration. Passed to the Room constructor.
callback function Callback to call every time a notification is received on this subscription

Return value

Returns an object exposing the following method:
onDone(callback)

The callback argument is called when the subscription ends, either successfully or with an error.

truncate

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .truncate(function (error, result) {
    // callback called once the truncate operation has completed
    // => the result is a JSON object containing the raw Kuzzle response
  });

// Using promises (NodeJS only)
kuzzle
 .collection('collection', 'index')
 .truncatePromise()
 .then(result => {
   // promise resolved once the truncate operation has completed
   // => the result is a JSON object containing the raw Kuzzle response
 });
kuzzle
  .collection("collection", "index")
  .truncate(new ResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject object) {
      // callback called once the truncate operation has completed
      // => the result is a JSON object containing the raw Kuzzle response
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $dataCollection->truncate();
}
catch (ErrorException $e) {

}

Callback response:

{
  "status": 200,
  "error": null,
  "requestId": "8fdc0efb-6fc7-427d-a3a1-fd8cf5eabc20",
  "controller": "admin",
  "action": "truncateCollection",
  "collection": "name of the truncated collection",
  "index": "name of the index containing the truncated collection",
  "metadata": {},
  "state": "done",
  "result": { "acknowledged": true }
}

Truncate the data collection, removing all stored documents but keeping all associated mappings.

This method is a lot faster than removing all documents using a query.

truncate([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to a JSON object containing the raw Kuzzle response.

updateDocument

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .collection('collection', 'index')
  .updateDocument('documentId', {title: 'foo', content: 'bar'}, function (error, result) {
    // result is a Document object
  });

// Using promises (NodeJS)
kuzzle
  .collection('collection', 'index')
  .updateDocumentPromise('documentId', {title: 'foo', content: 'bar'})
  .then(result => {
    // result is a Document object
  });
JSONObject newTitle = new JSONObject().put("title", "a shiny new title");

kuzzle
  .collection("collection", "index")
  .updateDocument("documentId", newTitle, new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document result) {
      // result is an updated Document object
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';
$documentContent = [
  'newField' => 'foo'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

try {
  $document = $dataCollection->updateDocument($documentId, $documentContent);

  // $document instanceof Document
}
catch (ErrorException $e) {

}

Update parts of a document, by replacing some fields or adding new ones. Note that you cannot remove fields this way: missing fields will simply be left unchanged.

updateDocument(documentId, content, [options], [callback])

Arguments Type Description
documentId string Unique document identifier
content JSON object Content of the document to create
options JSON object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the persistence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns the Collection object to allow chaining.

Callback response

Resolves to an up-to-date Document object.

CollectionMapping

When creating a new data collection in the persistent data storage layer, Kuzzle uses a default mapping. It means that, by default, you won’t be able to exploit the full capabilities of our persistent data storage layer (currently handled by ElasticSearch), and your searches may suffer from below-average performances, depending on the amount of data you stored in a collection and the complexity of your database.

The CollectionMapping object allow to get the current mapping of a data collection and to modify it if needed.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 CollectionMapping objects are returned by the method
 Collection.getMapping

 You may also use the Collection.collectionMapping() method:
 */
var mapping = kuzzle.collection('collection', 'index').collectionMapping();

mapping = kuzzle.collection('collection', 'index').collectionMapping(mapping);
CollectionMapping dataMapping = new CollectionMapping(dataCollection);

JSONObject mapping = new JSONObject();
JSONObject type = new JSONObject();
type.put("type", "string");
mapping.put("foo", type);

CollectionMapping dataMapping = new CollectionMapping(dataCollection, mapping);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\DataMapping;

$mapping = [
  'someField' => [
    'type' => 'string',
    'index' => 'analyzed'
  ]
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

$dataMapping = $dataCollection->collectionMapping($mapping);
// $dataMapping instanceof DataMapping

CollectionMapping(Collection, [mapping])

Arguments Type Description
Collection JSON Object An instantiated Collection object
mapping JSON Object Optional mapping

Properties

Property name Type Description get/set
headers JSON Object Common headers for all sent documents. get/set
mapping object Easy-to-understand list of mappings per field get/set

Note: the headers property is inherited from the provided Collection object and can be overrided

apply

// Using callbacks (NodeJS or Web Browser)
dataMapping.apply(function (error, result) {
  // called once the mapping action has been completed
});

// Using promises (NodeJS)
dataMapping.applyPromise().then(function (error, result) {
  // resolved once the mapping action has been completed
});
dataMapping.apply(new ResponseListener<CollectionMapping>() {
   @Override
   public void onSuccess(CollectionMapping object) {
     // called once the mapping action has been completed
   }

   @Override
   public void onError(JSONObject error) {
     // Handle error
   }
});
<?php

use \Kuzzle\DataMapping;

// ...

/**
 * @var $dataMapping DataMapping
 */
$dataMapping->apply();

Applies the new mapping to the data collection.

apply([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns this CollectionMapping object to allow chaining.

Callback response

Resolves to this updated CollectionMapping object.

refresh

// Using callbacks (NodeJS & Web Browser)
dataMapping.refresh(function (error, result) {
  // called once the mapping has been retrieved from Kuzzle
});

// Using promises (NodeJS)
dataMapping.refreshPromise().then(result => {
  // resolved once the mapping has been retrieved from Kuzzle
});
dataMapping.refresh(new ResponseListener<CollectionMapping>() {
   @Override
   public void onSuccess(CollectionMapping object) {
     // called once the mapping has been retrieved from Kuzzle
   }

   @Override
   public void onError(JSONObject error) {
     // Handle error
   }
});
<?php

use \Kuzzle\DataMapping;

// ...

/**
 * @var $dataMapping DataMapping
 */
$dataMapping->refresh();

Instantiates a new CollectionMapping object with an up-to-date content.

refresh([options], callback)

Arguments Type Description
options JSON Object Optional parameters
callback function Callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to this updated CollectionMapping object.

set

dataMapping.set('field', {type: 'string', index: 'analyzed', null_value: ''});
JSONObject mapping = new JSONObject();
mapping.put("type", "string");
mapping.put("index", "analyzed");
mapping.put("null_value", "");

dataMapping.set("field", mapping);
<?php

use \Kuzzle\DataMapping;

// ...

$field = 'field';
$mapping = [
  'type' => 'string',
  'index' => 'analyzed',
  'null_value' => ''
];

/**
 * @var $dataMapping DataMapping
 */
$dataMapping->set($field, $mapping);

Adds or updates a field mapping.

set(field, mapping)

Arguments Type Description
field string Name of the field from which the mapping is to be added or updated
mapping JSON Object Mapping for this field, following the Elasticsearch Mapping format

Return value

Returns this CollectionMapping object to allow chaining.

setHeaders

dataMapping.setHeaders({someContent: 'someValue'}, true);
JSONObject headers = new JSONObject();
headers.put("someContent", "someValue");
dataMapping.setHeaders(headers, true);
<?php

use \Kuzzle\DataMapping;

// ...

$headers = [
  'someContent' => 'someValue'
];

/**
 * @var $dataMapping DataMapping
 */
$dataMapping->setHeaders($headers);

This is a helper function returning itself, allowing to easily chain calls.

setHeaders(content, [replace])

Arguments Type Description
content JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns this CollectionMapping object to allow chaining.

Document

Kuzzle handles documents, either as realtime messages or as stored documents. Document is the object representation of one of these documents.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 Document objects are returned by various Collection methods.

 You may also use the Collection.document() method:
 */
var document = kuzzle.collection('collection', 'index').document('id');

document = kuzzle
  .collection('collection', 'index')
  .document({content: 'some content'});

document = kuzzle
  .collection('collection', 'index')
  .document('id', {content: 'some content'});
Document document = new Document(collection);

Document document = new Document(collection, "id");

JSONObject content = new JSONObject();
content.put("content", "some content");
Document document = new Document(collection, content);

Document document = new Document(collection, "id", content);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Document;

$documentId = 'foobar';
$documentContent = [
  'title' => 'foo',
  'content' => 'bar'
];

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->collection('collection', 'index');

// You can use the factory embeded in DataCollection object
$document = $dataCollection->document($documentId, $documentContent);

// or directly with public constructor
$document = new Document($dataCollection, $documentId, $documentContent);

Document(Collection, [documentId], [content])

Arguments Type Description
Collection object An instantiated Collection object
content JSON Object Initializes this document with the provided content
documentId string ID of an existing document.

Note: this constructor won’t make any call to Kuzzle. When providing only a document ID, the refresh method should be called to retrieve the corresponding document content.

Properties

Property name Type Description get/set
collection string The data collection associated to this document get
content JSON Object The content of the document get/set
headers JSON Object Common headers for all sent documents. get/set
id string Unique document identifier get/set
version integer Current document version get

Notes:

  • setting a new value to the content property is equivalent to calling setContent(data, false)
  • setting a new value to the id property will force this value for this document
  • the headers property is inherited from the provided Collection object and can be overrided

delete

// Using callbacks (NodeJS or Web Browser)
document.delete(function (error, result) {
  // called once the delete action has been completed
});

// Using promises (NodeJS)
document.deletePromise().then(result => {
  // called once the delete action has been completed
});
document.delete(new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document object) {
      // called once the delete action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

try {
  $result = $document->delete();
} catch (ErrorException $e) {

}

Deletes this document in Kuzzle.

delete([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the persistence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Callback response

Resolves to the deleted document ID

publish

document.publish();
document.publish();
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

try {
  $document->publish();
} catch (ErrorException $e) {

}

Publishes the content of this document as a real-time message.

publish([options])

Arguments Type Description
options JSON Object Optional parameters

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true

Return value

Returns this Document object to allow chaining.

refresh

// Using callbacks (NodeJS or Web Browser)
document.refresh(function (error, result) {
  // called once the refresh action has been completed
});

// Using promises (NodeJS)
document.refreshPromise().then(result => {
  // called once the refresh action has been completed
});
document.refresh(new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document object) {
      // called once the refresh action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

try {
  $document = $document->refresh();
} catch (ErrorException $e) {

}

Creates a new Document object with the last version of this document stored in Kuzzle.

refresh([options], callback)

Arguments Type Description
options JSON Object Optional parameters
callback function Callback

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a new Document object containing the last document version.

save

// Using callbacks (NodeJS or Web Browser)
document.save(function (error, result) {
  // called once the save action has been completed
});

// Using promises (NodeJS)
document.savePromise().then(result => {
  // called once the save action has been completed
});
document.save(new ResponseListener<Document>() {
    @Override
    public void onSuccess(Document object) {
      // called once the save action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

try {
  $document->save();
} catch (ErrorException $e) {

}

Saves this document into Kuzzle.

If this is a new document, this function will create it in Kuzzle and the id property will be made available.
Otherwise, this method will replace the latest version of this document in Kuzzle by the current content of this object.

save([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Optional callback

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
queuable boolean Mark this request as (not) queuable true
refresh string If set to wait_for, Kuzzle will wait the persistence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns this Document object to allow chaining.

Callback response

Resolves to this Document object once the document has been saved.

setContent

document.setContent({newContent: 'someValue'}, true);
JSONObject content = new JSONObject().put("content", "some content");

document.setContent(content, true);
<?php

use \Kuzzle\Document;

// ...

$documentContent = [
  'field' => 'value'
];

/**
 * @var $document Document
 */
$document->setContent($documentContent);

Replaces the current content with new data.
This is a helper function returning itself, allowing to easily chain calls.

setContent(data, [replace])

Arguments Type Description
data JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns this Document object to allow chaining.

setHeaders

document.setHeaders({someContent: 'someValue'}, true);
JSONObject headers = new JSONObject().put("someContent", "someValue");

document.setHeaders(headers, true);
<?php

use \Kuzzle\Document;

// ...

$headers = [
  'header' => 'value'
];

/**
 * @var $document Document
 */
$document->setHeaders($headers);

This is a helper function returning itself, allowing to easily chain calls.

setHeaders(content, [replace])

Arguments Type Description
content JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns this Document object to allow chaining.

subscribe

document
  .subscribe(function (error, notification) {
    // called each time a change occurs on this document
  })
  .onDone(function (error, roomObject) {
    // Handles the subscription result
  });

document
  .subscribe({subscribeToSelf: true, metadata: { myId: 'someId'}}, function (error, notification) {
    // called each time a change occurs on this document
  })
  .onDone(function (error, roomObject) {
    // Handles the subscription result
  });
Room room = document.subscribe(new ResponseListener<NotificationResponse>() {
    @Override
    public void onSuccess(NotificationResponse object) {
      // called each time a change occurs on this document
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  })
  .onDone(new ResponseListener<Room>() {
    @Override
    public void onSuccess(Room response) {
      // Handle subscription success
    }

    @Override
    public void onError(JSONObject error) {
      // Handle subscription error
    }
  });
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Listens to changes occuring on this document. Throws an error if this document has not yet been created in Kuzzle.

subscribe([options], callback)

Arguments Type Description
options object Subscription configuration. Passed to the Room constructor.
callback function Callback that will be called each time a change has been detected on this document

Return value

Returns an object exposing the following method:
onDone(callback)

The callback argument is called when the subscription ends, either successfully or with an error.

MemoryStorage

Kuzzle’s memory storage is a separate data store from the database layer. It is internally based on Redis. You can access most of Redis functions (all lowercased), except:

  • cluster based functions
  • script based functions
  • cursors functions

Here is the list of non implemented commands:

client cluster config debug echo eval evalsha flushall migrate monitor move psubscribe pubsub punsubscribe quit readonly readwrite role script select shutdown slaveof slowlog subscribe sync unsubscribe scan sscan hscan zscan

You can find a list of all redis command at: http://redis.io/commands

Constructors

/*
 Constructor is not exposed in the JS/Node SDK. You may get the instantiated
 MemoryStorage object by calling Kuzzle.memoryStorage
 */
var memoryStorage = kuzzle.memoryStorage;
// using the static instance
MemoryStorage memoryStorage = kuzzle.memoryStorage;

// or instantiating a new MemoryStorage object
MemoryStorage memoryStorage = new MemoryStorage(kuzzle);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\MemoryStorage;

$kuzzle = new Kuzzle('localhost');

// using the static instance
$memoryStorage = $kuzzle->memoryStorage();

// or instantiating a new MemoryStorage object
$memoryStorage = new MemoryStorage($kuzzle);

Example

Here is an example with the ping command.

var memoryStorage = kuzzle.memoryStorage;

memoryStorage.ping((err, res) => {
    // Handle result
});
// using the static instance
MemoryStorage memoryStorage = kuzzle.memoryStorage;

memoryStorage.setListener(new ResponseListener<JSONObject>() {

    @Override
    public void onSuccess(JSONObject result) {
        // Handle success
    }

    @Override
    public void onError(JSONObject error) {
        // Handle error
    }

});
memoryStorage.ping();
<?php

use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');
$memoryStorage = $kuzzle->memoryStorage();

try {
  $result = $memoryStorage->ping();
} catch (ErrorException $e) {

}

Room

This object is the result of a subscription request, allowing to manipulate the subscription itself.

In Kuzzle, you don’t exactly subscribe to a room or a topic but, instead, you subscribe to documents.
What it means is that, to subscribe, you provide to Kuzzle a set of matching filters. Of course, providing an empty filter results in subscribing to all changes occurring on a data collection, emulating the behavior of a traditional topic.

Once you have subscribed, depending on the subscription configuration you provided, you may receive the following notifications:

  • a pub/sub message matches your criteria (real-time)
  • a matching document is about to be created or deleted (real-time)
  • a matching document is created, updated or deleted (once the change is effective in the database)
  • a user enters or leaves the room

You may subscribe multiple times to the same room, with identical or different subscription parameters, and with different callbacks. This allow dispatching notifications across the right parts of your application, instead of having to maintain an all-purpose notification consumer (but you can do that, too).

Notifications

Document notification example:

{
  "status": 200,
  "error": null,
  "requestId": "bc41ced6-38fc-42b9-8fd5-22ae0774aac2",
  "controller": "name of the controller that generated the notification",
  "action": "name of the action that generated the notification",
  "collection": "collection name",
  "index": "index name",
  "metadata": {},
  "state": "done",
  "scope": "in",
  "result": {
    "_source": {
      "message content": "this is an example"
    }
  }
}

User notification example:

{
  "error": null,
  "status": 200,
  "roomId": "ID of the room concerned by this notification",
  "requestId": "5897cd2f-a8a2-40b2-aa43-b31898172008",
  "controller": "subscribe",
  "action": "on",
  "protocol": "protocol used by the notifying user",
  "timestamp": 1453193069592,
  "metadata": {
    "optional": "user informations"
  },
  "result": {
    "roomId": "ID of the room concerned by this notification",
    "count": 42
  }
}

To subscribe, you must provide a callback that will be called each time a new notification is received.

On the right panel you can see a document and a user notification examples.

Document notification rundown

Notification field Type Description Possible values
result._source JSON object Content of the document or real-time message that generated the notification
scope string Indicates if the document enters or exits the subscription scope in, out
state string Tells if the document is about to be changed, or if the change is effective pending, done

User notification rundown

Notification field Type Description Possible values
action string Indicates if the user enters or leaves the subscribed room on, off
metadata JSON object If provided during subscription, contains application specific informations
result.count integer Updated number of users subscribing to this room

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 Room objects are returned by Collection.subscribe and
 Document.subscribe methods.

 You may also use the Collection.room() method:
 */
var room = kuzzle.collection('collection', 'index').room();

room = kuzzle
  .collection('collection', 'index')
  .room({subscribeToSelf: false});
Room room = new Room(dataCollection);

RoomOptions options = new RoomOptions().setSubscribeToSelf(false);
Room room = new Room(dataCollection, options);
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Creates a Room object.

Room(Collection, [options])

Arguments Type Description
Collection object an instantiated Kuzzle Collection object
options object Optional subscription configuration

Available options:

Option Type Description Default
metadata JSON Object Additional information passed to notifications to other users null
scope string Filter document notifications depending on their scope status. You may receive entering documents (scope: in), leaving documents (scope: out), all documents changes (scope: all) or filter these notifications completely (scope: none). This filter does not affect pub/sub messages or user events. all
state string Filter document notifications depending on the state of the modifying request. You may receive real-time notifications when a document is about to be changed (state: pending), or be notified when the change has been fully written in the database (state: done), or both (state: all). This filter does not affect pub/sub messages or user events. done
subscribeToSelf boolean (Don’t) subscribe to notifications fired as a consequence of our own queries true
users string Filter notifications fired upon a user entering the room (user: in), leaving the room (user: out), or both (user: all). Setting this variable to none prevents receiving these notifications none

Properties

Property name Type Description get/set
collection string The subscribed data collection get
filters JSON object The current set of filters of this room get/set
headers JSON Object Common headers for all sent documents. get/set
metadata JSON Object Additional information passed to notifications to other users get/set
subscribeToSelf boolean (Don’t) subscribe to notifications fired as a consequence of our own queries get/set
roomId string Unique room identifier get

Notes:

  • the headers property is inherited from the provided Collection object and can be overridden
  • updating the metadata property takes effect after renew is called
  • by default, the global Kuzzle metadata properties are sent along with the subscription request. If a metadata option is provided during subscription, it will be merged with the global metadata for the subscription only. In case of conflicts, subscription metadata take priority over the global metadata.

count

// Using callbacks (NodeJS or Web Browser)
room.count(function (error, result) {
  // ...
});

// Using promises (NodeJS)
room.countPromise().then(result => {
  // ...
});
room.count(new ResponseListener<Integer>() {
 @Override
 public void onSuccess(Integer result) throws Exception {
   //  ...
 }

 @Override
 public void onError(JSONObject error) throws Exception {
   // Handle error
 }
});
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Callback response

1

Return the number of subscribers on that room

count(callback)

Arguments Type Description
callback function Callback handling the response

Callback response

Resolves to a integer containing the number of users subscribing to this room.

renew

room.renew({in: {field: ['some', 'new', 'filter']}}, function (err, res) {
  // called each time a change is detected on documents matching this filter

  // check the Room/Notifications section of this documentation
  // to get notification examples
}, function (err, res) {
  // handles the subscription result
});
JSONObject filter = new JSONObject()
  .put("and", new JSONArray()
    .put(
      new JSONObject().put("in",
        new JSONObject().put("status",
          new JSONArray()
            .put("idle")
            .put("wantToHire")
            .put("toHire")
            .put("riding")
        )
      )
    )
    .put(
      new JSONObject().put("in",
        new JSONObject()
          .put("type", new JSONArray().put("cab"))
      )
    )
    .put(
      new JSONObject().put("geo_distance",
        new JSONObject()
          .put("distance", "10km")
          .put("pos",
            new JSONObject()
              .put("lat", "48.8566140")
              .put("lon", "2.352222")
          )
      )
    )
  );

room.renew(filters, new ResponseListener<NotificationResponse>() {
 @Override
 public void onSuccess(NotificationResponse result) throws Exception {
   // called each time a change is detected on documents matching this filter

   // check the Room/Notifications section of this documentation
   // to get notification examples
 }

 @Override
 public void onError(JSONObject error) throws Exception {
   // Handle error
 }
}, new ResponseListener<Room>() {
  // Handle the subscription result
});
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Renew the subscription. Force a new subscription using the same filters if no new ones are provided. Unsubscribes first if this Room object was already listening to events.

renew([filters], notificationCallback, subscriptionCallback)

Arguments Type Description
filters JSON Object Filters
notificationCallback function Function called each time a notification is received
subscriptionCallback function Function called with the subscription result

setHeaders

room.setHeaders({someContent: 'someValue'}, true);
JSONObject headers = new JSONObject();
headers.put("someContent", "someValue");
room.setHeaders(headers, true);
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Returns itself

This is a helper function returning itself, allowing to easily chain calls.

setHeaders(content, [replace])

Arguments Type Description
content JSON Object New content
replace boolean true: replace the current content with the provided data, false: merge it

Note: by default, the replace argument is set to false

Return value

Returns this Room object to allow chaining.

unsubscribe

room.unsubscribe();
room.unsubscribe();
<?php

// not implemented (this SDK uses HTTP and is thus stateless)

Cancels the current subscription.

Return value

Returns this Room object to allow chaining.

Security

The Security component lets you handle users permissions in Kuzzle.

Please refer to our Kuzzle permissions guide for more information.

Constructors

/*
 Constructor is not exposed in the JS/Node SDK. You may get the instantiated
 Security object by calling Kuzzle.security
 */
var kuzzleSecurity = kuzzle.security;
// using the static instance
Security security = kuzzle.security;

// or instantiating a new Security object
Security security = new Security(kuzzle);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Security;

$kuzzle = new Kuzzle('localhost');

// using the static instance
$security = $kuzzle->security();

// or instantiating a new Security object
$security = new Security($kuzzle);

Security(Kuzzle)

Arguments Type Description
Kuzzle object An instantiated Kuzzle object

Properties

There are no exposed properties for this object.

createRole

var roleDefinition = {
  controllers: {
    "*": {
      actions: {
        "*": true
      }
    }
  }
};

// You can chose to replace the given role if already exists
var options = {
  replaceIfExist: true
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .createRole('myrole', roleDefinition, options, function(error, response) {
    // result is a Role object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createRolePromise('myrole', roleDefinition, options)
  .then((response) => {
    // result is a Role object
  });
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("*", new JSONObject()
      .put("actions", new JSONObject()
        .put("*", true)
      )
    )
  )
);

Options opts = new Options().setReplaceIfExist(true);

kuzzle
  .security
  .createRole("myrole", roleDefinition, opts, new ResponseListener<Role>() {
    @Override
    public void onSuccess(Role role) {
      // the result is an instantiated Role object
    }

    @Override
    public void onError(JSONObject error) {

    }
  })
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;

$roleId = 'myRole';
$roleDefinition = [
  'controllers' => [
    '*' => [
      'actions' => [
        '*' => true
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $role = $security->createRole($roleId, $roleDefinition);

  // $role instanceof Role
}
catch (ErrorException $e) {
  // error occurred
}

Create a new role in Kuzzle.

createRole(id, content, [options], callback)

Arguments Type Description
id string Unique role identifier
content JSON Object A plain JSON object representing the role
options string (Optional) Optional arguments
callback function Callback handling the response

Available options:

Filter Type Description Default
replaceIfExist boolean If the same role already exists: throw an error if sets to false. Replace the existing role otherwise false
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a Role object.

createProfile

var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

// You can chose to replace the given profile if already exists
var options = {
  replaceIfExist: true
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .createProfile('myprofile', profileDefinition, options, function(error, response) {
    // result is a Profile object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createProfilePromise('myprofile', profileDefinition, options)
  .then((response) => {
    // result is a Profile object
  });
JSONObject role1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject role2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );
JSONObject profileDefinition = new JSONObject()
  .put("policies", new JSONArray()
    .put(role1)
    .put(role2)
  );

Options opts = new Options().setReplaceIfExist(true);

kuzzle
  .security
  .createProfile("myprofile", profileDefinition, opts, new ResponseListener<Profile>() {
    @Override
    public void onSuccess(Profile profile) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;

$profileId = 'myProfile';
$profileDefinition = [
  'policies' => [
    [
      'roleId' => 'myRole'
    ],
    [
      'roleId' => 'anonymous',
      'restrictedTo' => [
        ['index' => 'my-second-index', 'collection' => ['my-collection']]
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $profile = $security->createProfile($profileId, $profileDefinition);

  // $profile instanceof Profile
}
catch (ErrorException $e) {

}

Create a new profile in Kuzzle.

createProfile(id, content, [options], callback)

Arguments Type Description
id string Unique profile identifier
content JSON Object A plain JSON object representing the profile
options string (Optional) Optional arguments
callback function Callback handling the response

Available options:

Filter Type Description Default
replaceIfExist boolean If the same profile already exists: throw an error if sets to false. Replace the existing profile otherwise false
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a Profile object.

createUser

var userContent = {
  // A "profile" field is required to bind a user to an existing profile
  profileIds: ['admin'],

  // The "local" authentication strategy requires a password
  password: 'secretPassword',

  // You can also set custom fields to your user
  firstname: 'John',
  lastname: 'Doe'
};

// You can chose to replace the given user if already exists
var options = {
  replaceIfExist: true
};


// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .createUser('myuser', userContent, options, function(error, response) {
    // result is a User object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createUserPromise('myuser', userContent, options)
  .then((response) => {
    // result is a User object
  });
JSONObject newUser = new JSONObject()
  // A "profile" field is required to bind a user to an existing profile
  .put("profileIds", new JSONArray().put("admin"))
  // The "local" authentication strategy requires a password
  .put("password", "secret password")
  // You can also set custom fields to your user
  .put("firstname", "John")
  .put("lastname", "Doe");

Options opts = new Options().setReplaceIfExist(true);

kuzzle
  .security
  .createUser("myNewUser", newUser, opts, new ResponseListener<User>() {
    @Override
    public void onSuccess(User user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';
$userDefinition = [
  'profileIds' => ['myProfile'],
  'password' => 'secret',
  'firstname' => 'John',
  'lastname' => 'Doe'
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $user = $security->createUser($userId, $userDefinition);

  // $user instanceof User
}
catch (ErrorException $e) {

}

Create a new user in Kuzzle.

createUser(id, content, [options], [callback])

Arguments Type Description
id string Unique user identifier, will be used as username
content JSON Object A plain JSON object representing the user
options string (Optional) Optional arguments
callback function Callback handling the response

Available options:

Filter Type Description Default
replaceIfExist boolean If the same user already exists: throw an error if sets to false. Replace the existing user otherwise false
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a User object.

createRestrictedUser

var userContent = {
  // The "local" authentication strategy requires a password
  password: 'secretPassword',

  // You can also set custom fields to your user
  firstname: 'John',
  lastname: 'Doe'
};


// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .createRestrictedUser('myuser', userContent, options, function(error, response) {
    // result is a User object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createRestrictedUserPromise('myuser', userContent, options)
  .then((response) => {
    // result is a User object
  });
JSONObject newUser = new JSONObject()
  // The "local" authentication strategy requires a password
  .put("password", "secret password")
  // You can also set custom fields to your user
  .put("firstname", "John")
  .put("lastname", "Doe");

Options opts = new Options().setReplaceIfExist(true);

kuzzle
  .security
  .createRestrictedUser("myNewUser", newUser, opts, new ResponseListener<User>() {
    @Override
    public void onSuccess(User user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';
$userDefinition => [
  'password' => 'secret',
  'firstname' => 'John',
  'lastname' => 'Doe'
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $user = $security->createRestrictedUser($userId, $userDefinition);

  // $user instanceof User
}
catch (ErrorException $e) {

}

Create a new restricted user in Kuzzle. This function allows anonymous users for instance to create a “restricted” user with predefined rights.

createRestrictedUser(id, content, [options], [callback])

Arguments Type Description
id string Unique user identifier, will be used as username
content JSON Object A plain JSON object representing the user
options string (Optional) Optional arguments
callback function Callback handling the response

Available options:

Filter Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a User object.

deleteProfile

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .deleteProfile('myprofile', function(error, result) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .deleteProfilePromise('myprofile')
  .then((result) => {

  });
kuzzle
  .security
  .deleteProfile("myprofile", new ResponseListener<String>() {
    @Override
    public void onSuccess(String profileName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;

$profileId = 'myProfile';

$kuzzle = new Kuzzle('localhost');

try {
  $kuzzle->security()->deleteProfile($profileId);
}
catch (ErrorException $e) {

}

Delete profile.

deleteProfile(id, [options], [callback])

Arguments Type Description
id string Unique profile identifier to delete
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves the profile id which has been deleted.

deleteRole

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .deleteRole('myrole', function(error, result) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .deleteRolePromise('myrole')
  .then((result) => {

  });
kuzzle
  .security
  .deleteRole("myrole", new ResponseListener<String>() {
    @Override
    public void onSuccess(String roleName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;

$roleId = 'myRole';

$kuzzle = new Kuzzle('localhost');

try {
  $kuzzle->security()->deleteRole($roleId);
}
catch (ErrorException $e) {

}

Delete role.

deleteRole(id, [options], [callback])

Arguments Type Description
id string Unique role identifier to delete
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves the role id which has been deleted.

deleteUser

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .deleteUser('myuser', function(error, result) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .deleteUserPromise('myuser')
  .then((result) => {

  });
kuzzle
  .security
  .deleteUser("myuser", new ResponseListener<String>() {
    @Override
    public void onSuccess(String userName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

try {
  $kuzzle->security()->deleteUser($userId);
}
catch (ErrorException $e) {

}

Delete user.

deleteUser(id, [options], [callback])

Arguments Type Description
id string Unique user identifier to delete
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves the user id which has been deleted.

fetchProfile

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .fetchProfile('myprofile', function(error, result) {
    // result is a Profile object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .fetchProfilePromise('myprofile')
  .then((result) => {
    // result is a Profile object
  });

kuzzle
  .security
  .fetchProfile("myprofile", new ResponseListener<Profile>() {
    @Override
    public void onSuccess(Profile profile) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;

$profileId = 'myProfile';

$kuzzle = new Kuzzle('localhost');

try {
  $profile = $kuzzle->security()->fetchProfile($profileId);

  // $profile instanceof Profile
}
catch (ErrorException $e) {

}

Retrieves a single stored profile using its unique ID.

fetchProfile(id, [options], callback)

Arguments Type Description
id string Unique profile identifier
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a Profile object.

fetchRole

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .fetchRole('myrole', function(error, result) {
    // result is a Role object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .fetchRolePromise('myrole')
  .then((result) => {
    // result is a Role object
  });

kuzzle
  .security
  .fetchRole("myrole", new ResponseListener<Role>() {
    @Override
    public void onSuccess(Role role) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;

$roleId = 'myRole';

$kuzzle = new Kuzzle('localhost');

try {
  $role = $kuzzle->security()->fetchRole($roleId);

  // $role instanceof Role
}
catch (ErrorException $e) {

}

Retrieves a single stored role using its unique ID.

fetchRole(id, [options], callback)

Arguments Type Description
id string Unique role identifier
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a Role object.

fetchUser

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .fetchUser('myuser', function(error, result) {
    // result is a User object
  })

// Using promises (NodeJS)
kuzzle
  .security
  .fetchUserPromise('myuser')
  .then((result) => {
    // result is a User object
  })
kuzzle
  .security
  .fetchUser("myuser", new ResponseListener<User>() {
    @Override
    public void onSuccess(User user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

try {
  $user = $kuzzle->security()->fetchUser($userId);

  // $user instanceof User
}
catch (ErrorException $e) {

}

Retrieves a single stored user using its unique ID.

fetchUser(id, [options], callback)

Arguments Type Description
id string Unique user identifier
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a User object.

getUserRights

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .getUserRights('id', function(error, result) {
    // result is a JSON object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .getUserRightsPromise('id')
  .then((result) => {
    // result is a JSON object
  });

kuzzle
  .security
  .getUserRights("id", new ResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject rights) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

try {
  $rights = $kuzzle->security()->getUserRights($userId);

}
catch (ErrorException $e) {

}

Callback response example

[
  {
    controller: 'my-controller', action: 'my-action', index: '*', collection: '*',
    value: 'allowed'
  },
  {
    controller: 'another-controller', action: '*', index: 'my-index', collection: '*',
    value: 'conditional'
  }
]

Gets the rights of the currently logged user.

getUserRights(id, [options], callback)

Arguments Type Description
id String Id of the user
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a JSON object.

isActionAllowed

kuzzle.security.getMyRights((err, rights) => {
    if (!err) {
        kuzzle.security.isActionAllowed(rights, 'read', 'get', 'index1', 'collection1');
    }
});
kuzzle.security.getMyRights(new ResponseListener<JSONArray>() {
    @Override
    public void onSuccess(JSONArray rights) {
        Rights rights = kuzzle.security.isActionAllowed(rights, "read", "get", "index1", "collection1");
    }

    @Override
    public void onError(JSONObject error) {
     // ...
    }
});
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Security;

$kuzzle = new Kuzzle('localhost');

try {
  $rights = $kuzzle->security()->getMyRights();

  switch ($kuzzle->security()->isActionAllowed($rights, 'read', 'get', 'index1', 'collection1')) {
    case Security::ACTION_ALLOWED:
      // code...
      break;
    case Security::ACTION_DENIED:
      // code...
      break;
    case Security::ACTION_CONDITIONAL:
      // code...
      break;
  }
}
catch (ErrorException $e) {

}

Tells whether an action is allowed, denied or conditional based on the rights provided as the first argument. - allowed is returned when an action is authorized without condition - conditional is returned when the authorization depends on a closure - denied is returned when the action is forbidden An action is defined as a couple of action and controller (mandatory), plus an index and a collection(optional).

isActionAllowed(rights, controller, action, index, collection)

Arguments Type Description
rights JSON array Rights list
controller String The controller
action String The action
index String The index
collection String The collection

Return value

Returns either allowed, denied or conditional.

profile

var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

var profile = kuzzle.security.profile('myprofile', profileDefinition);
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject policy2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );
JSONObject profileDefinition = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)
    .put(policy2)
  );

Profile profile = kuzzle.security.profile("myprofile", profileDefinition);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;

$profileId = 'myProfile';
$profileDefinition = [
  'policies' => [
    [
      'roleId' => 'myRole'
    ],
    [
      'roleId' => 'anonymous',
      'restrictedTo' => [
        ['index' => 'my-second-index', 'collection' => ['my-collection']]
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

$profile = $security->profile($profileId, $profileDefinition);

// $profile instanceof Profile

Instantiate a new Profile object.

profile(id, content)

Arguments Type Description
id string Unique profile identifier
content JSON Object Profile content

Return value

Returns the Profile object.

role

var roleDefinition = {
  controllers: {
    "*": {
      actions: {
        "*": true
      }
    }
  }
};

var role = kuzzle.security.role('role', roleDefinition);
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("*", new JSONObject()
      .put("actions", new JSONObject()
        .put("*", true)
      )
    )
  )
);

Role role = kuzzle.security.role("myrole", roleDefinition);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;

$roleId = 'myRole';
$roleDefinition = [
  'controllers' => [
    '*' => [
      'actions' => [
        '*' => true
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

$role = $security->role($roleId, $roleDefinition);

// $role instanceof Role

Instantiate a new Role object.

role(id, content)

Arguments Type Description
id string Unique role identifier
content JSON Object Role content

Return value

Returns the Role object.

searchProfiles

var filters = {
   // filter can contains an array `roles` with a list of role id
  policies:  ['myrole', 'admin'],
  // filter can handler pagination with properties `from` and `size`
  from: 0,
  size: 10
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .searchProfiles(filters, function(error, result) {
    // result is a JSON Object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .searchProfilesPromise(filters)
  .then((result) => {
    // result is a JSON Object
  });
JSONObject filters = new JSONObject()
  // filter can contains a "roles" array with a list of role IDs
  .put("policies", new JSONArray().put("myrole", "admin"))
  // search results can be paginated
  .put("from", 0)
  .put("size", 10);

kuzzle
  .security
  .searchProfiles(filters, new ResponseListener<SecurityDocumentList>() {
    @Override
    public void onSuccess(SecurityDocumentList profiles) {
      // Contains a profiles list
      for(Profile profile : profiles.getDocuments()) {

      }

      // And the total number of profiles, regardless of pagination
      profiles.getTotal();
    }

    @Override
    public void onError(JSONObject error) {

    }
  });

<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;
use \Kuzzle\Util\ProfilesSearchResult;

$filters = [
  'policies' => [
      'admin',
      'myrole'
  ]
];

$options = [
  'from' => 0,
  'size' => 1
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $result = $security->searchProfiles($filters, $options);

  // $result instanceof ProfilesSearchResult

  foreach($result->getProfiles() as $profile) {
    // $profile instanceof Profile
  }
}
catch (ErrorException $e) {

}

Callback response:

{
  "total": 124,
  "documents": [
    // array of Profile
  ]
}

Executes a search on profiles according to a filter

searchProfiles(filters, [options], callback)

Arguments Type Description
filters JSON Object List of filters to retrieves roles
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
from number Starting offset 0
queuable boolean Mark this request as (not) queuable true
size integer Number of hits to return 20

Available filters:

Filter Type Description Default
roles array Contains an array roles with a list of role id undefined

Callback response

Resolves to a JSON Object

searchUsers

var filter = {
  filter: {
    and: [
      {
        terms: {
          profileIds: ['anonymous', 'default'],
        }
      },
      {
        geo_distance: {
          distance: '10km',
          pos: {
            lat: '48.8566140', lon: '2.352222'
          }
        }
      }
    ]
  }
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .searchUsers(filters, function(error, result) {
    // result is a JSON Object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .searchUsersPromise(filters)
  .then((result) => {
    // result is a JSON Object
  });
JSONObject filter = new JSONObject()
  .put("filter", new JSONObject()
    .put("and", new JSONArray()
      .put("terms", new JSONObject()
        .put("profileIds", new JSONArray().put("anonymous").put("default"))
      )
      .put("geo_distance", new JSONObject()
        .put("distance", "10km")
        .put("pos", new JSONObject()
          .put("lat", "48.8566140")
          .put("lon", "2.352222")
        )
      )
    )
  );

kuzzle
  .security
  .searchUsers(filters, new ResponseListener<SecurityDocumentList>() {
    @Override
    public void onSuccess(SecurityDocumentList users) {
      // users.getDocuments() returns an users list
      for(User user : users.getDocuments()) {

      }

      // users.getTotal() returns the number of matched users, regardless of pagination
      users.getTotal();
    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;
use \Kuzzle\Util\UsersSearchResult;

$filters = [
  'filter' => [
    'and' => [
      [
        'terms' => [
          'profileIds' => ['anonymous', 'default'],
        ]
      ],
      [
        'geo_distance' => [
          'distance' => '10km',
          'pos' => [
            'lat' => '48.8566140',
            'lon' => '2.352222'
          ]
        ]
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $result = $security->searchUsers($filters);

  // $result instanceof UsersSearchResult

  foreach($result->getUsers() as $user) {
    // $user instanceof User
  }
}
catch (ErrorException $e) {

}

Callback response:

{
  "total": 124,
  "documents": [
    // array of User
  ]
}

Executes a search on users according to a filter

searchUsers(filters, [options], callback)

Arguments Type Description
filters JSON Object Filters
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a JSON Object

searchRoles

var filters = {
   // filter can contains an array `controllers` with a list of controller name
  controllers:  ['read', 'write'],
  // filter can handler pagination with properties `from` and `size`
  from: 0,
  size: 10
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .searchRoles(filters, function(error, result) {
    // result is a JSON Object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .searchRolesPromise(filters)
  .then((result) => {
    // result is a JSON Object
  });
JSONObject filter = new JSONObject()
  .put("controllers", new JSONArray()
    .put("read")
    .put("write")
  )
  .put("from", 0)
  .put("size", 10);


kuzzle
  .security
  .searchRoles(filter, new ResponseListener<SecurityDocumentList>() {
    @Override
    public void onSuccess(SecurityDocumentList roles) {
      // roles.getDocuments() returns a roles list
      for(Role role : roles.getDocuments()) {

      }

      // roles.getTotal() returns the number of matched roles, regardless of pagination
      roles.getTotal();
    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;
use \Kuzzle\Util\RolesSearchResult;

$filters = [
  'controllers' => [
    'read',
    'write'
  ],
  'size' => 10,
  'from' => 0
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $result = $security->searchRoles($filters);

  // $result instanceof RolesSearchResult

  foreach($result->getRoles() as $role) {
    // $role instanceof Role
  }
}
catch (ErrorException $e) {

}

Callback response:

{
  "total": 124,
  "documents": [
    // array of Role
  ]
}

Executes a search on roles according to a filter

searchRoles(filters, [options], callback)

Arguments Type Description
filters JSON Object List of filters to retrieves roles
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
from number Starting offset 0
queuable boolean Mark this request as (not) queuable true
size number  Number of hits to return 20

Available filters:

Filter Type Description Default
indexes array List of indexes id related to the searched role undefined

Callback response

Resolves to a JSON Object

updateProfile

var newContent = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};
// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .updateProfile("profile ID", newContent, function (err, updatedProfile) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .updateProfilePromise("profile ID", newContent)
  .then(updatedProfile => {

  });
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject policy2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );

JSONObject newContent = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)
    .put(policy2)
  );

kuzzle
  .security
  .updateProfile("profile ID", newContent, new ResponseListener<Profile>() {
    @Override
    public void onSuccess(Profile profile) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;

$profileId = 'myProfile';
$profileDefinition = [
  'policies' => [
    [
      'roleId' => 'myRole'
    ],
    [
      'roleId' => 'anonymous',
      'restrictedTo' => [
        ['index' => 'my-second-index', 'collection' => ['my-collection']]
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $profile = $security->updateProfile($profileId, $profileDefinition);

  // $profile instanceof Profile
}
catch (ErrorException $e) {

}

updateProfile(id, content, [options], [callback])

Performs a partial update on an existing profile.

Arguments Type Description
id string Unique role identifier
content JSON Object A plain JSON object representing the profile
options string (Optional) Optional arguments
callback function (Optional) Callback handling the response

Available options:

Filter Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves to an updated Profile object

updateRole

var roleDefinition = {
  controllers: {
    "read": {
      actions: {
        "get": true
      }
    }
  }
};

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .updateRole("role ID", roleDefinition, function (err, updatedRole) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .updateRolePromise("profile ID", roleDefinition)
  .then(updatedRole => {

  });
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("*", new JSONObject()
      .put("actions", new JSONObject()
        .put("*", true)
      )
    )
  )
);

kuzzle
  .security
  .updateRole("Role ID", roleDefinition, new ResponseListener<Role>() {
    @Override
    public void onSuccess(Role role) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;

$roleId = 'myRole';
$roleDefinition = [
  'controllers' => [
    '*' => [
      'actions' => [
        '*' => true
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $role = $security->updateRole($roleId, $roleDefinition);

  // $role instanceof Role
}
catch (ErrorException $e) {

}

updateRole(id, content, [options], [callback])

Performs a partial update on an existing role.

Arguments Type Description
id string Unique role identifier
content JSON Object A plain JSON object representing the role
options string (Optional) Optional arguments
callback function (Optional) Callback handling the response

Available options:

Filter Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves to an updated Role object

updateUser

var newContent = {
  firstname: 'My Name Is',
  lastname: 'Jonas'
};


// Using callbacks (NodeJS or Web Browser)
kuzzle
  .security
  .updateUser("User ID", newContent, function (err, updatedUser) {

  });

// Using promises (NodeJS)
kuzzle
  .security
  .updateUserPromise("User ID", newContent)
  .then(updatedUser => {

  });
JSONObject newContent = new JSONObject()
  .put("firstname", "My Name Is")
  .put("lastname", "Jonas");

kuzzle
  .security
  .updateUser("User ID", newContent, new ResponseListener<User>() {
    @Override
    public void onSuccess(User user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';
$userDefinition = [
  'firstname' => 'My Name Is',
  'lastname' => 'Jonas'
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

try {
  $user = $security->updateUser($userId, $userDefinition);

  // $user instanceof User
}
catch (ErrorException $e) {

}

updateUser(id, content, [options], [callback])

Performs a partial update on an existing user.

Arguments Type Description
id string Unique role identifier
content JSON Object A plain JSON object representing the user
options string (Optional) Optional arguments
callback function (Optional) Callback handling the response

Available options:

Filter Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Security object to allow chaining.

Callback response

Resolves to an updated User object

user

var userContent = {
  // A "profileIds" field is required to bind a user to an existing profile
  profileIds: ['some profile'],

  // The "local" authentication strategy requires a password
  password: 'secretPassword',

  // You can also set custom fields to your user
  firstname: 'John',
  lastname: 'Doe'
};

var user = kuzzle.security.user('myuser', userContent);
JSONObject userContent = new JSONObject()
    // A "profileIds" field is required to bind a user to an existing profile
    .put("profileIds", new JSONArray().put('someProfile'))
    // The "local" authentication strategy requires a password
    .put("password", "a password")
    // You can also set custom fields to your user
    .put("firstname", "John")
    .put("lastname", "Doe");

User user = kuzzle.security.user("userId", userContent);  
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';
$userDefinition = [
  // A "profileIds" field is required to bind a user to an existing profile
  'profileIds' => ['myProfile'],
  // The "local" authentication strategy requires a password
  'password' => 'secret',
  'firstname' => 'John',
  'lastname' => 'Doe'
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

$user = $security->user($userId, $userDefinition);
// $user instanceof User

Instantiates a new User object.

user(id, content)

Arguments Type Description
id string Unique user identifier
content JSON Object User content

Return value

Returns the User object.

~ Role

Role is the object representation of a set of right policies.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 Role objects are returned by Security.role method:
 */
var roleDefinition = {
  controllers: {
    "*": {
      actions: {
        "*": true
      }
    }
  }
};

var role = kuzzle.security.role('myrole', roleDefinition);
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("*", new JSONObject()
      .put("actions", new JSONObject()
        .put("*", true)
      )
    )
  )
);

Role role = new Role(kuzzle.security, "role ID", roleDefinition);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Role;

$roleId = 'myRole';
$roleDefinition = [
  'controllers' => [
    '*' => [
      'actions' => [
        '*' => true
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

// Using the Security factory:
$role = $security->role($roleId, $roleDefinition);

// Or directly with the constructor:
$role = new Role($security, $roleId, $roleDefinition);

Instantiates a new Role object.

Role(Security, id, content)

Arguments Type Description
Security Security An instantiated Security object
id string Unique role identifier
content JSON Object Role content

Note: this constructor won’t make any call to Kuzzle.

Return value

Returns the Role object.

Properties

Property name Type Description get/set
content JSON object Raw role content get
id string Unique profile identifier get

delete

// Using callbacks (NodeJS or Web Browser)
role.delete(function(error, deletedId) {
  // ...
});

// Using promises (NodeJS)
role.deletePromise()
  .then(deletedId => {
    // ...
  });
role.delete(new ResponseListener<String>() {
  @Override
  public void onSuccess(String deletedId) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\Role;

// ...

/*
 * @var $role Role
 */
try {
  $role->delete();
}
catch(ErrorException $e) {
  // error occurred
}

Deletes the role from Kuzzle’s database layer.

delete([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to the id of the deleted role.

save

// Using callbacks (NodeJS or Web Browser)
role
  .save(function(error, result) {
    // result is a Role object
  });

// Using promises (NodeJS)
role
  .savePromise()
  .then((result) => {
    // result is a Role object
  });
role.save(new ResponseListener<Role> {
  @Override
  public void onSuccess(Role savedRole) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\Role;

// ...

/*
 * @var $role Role
 */

try {
  $role = $role->save();

  // $role instanceof Role
}
catch (ErrorException $e) {
  // error occured
}

Creates or replaces the role in Kuzzle’s database layer.

save([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Role object to allow chaining.

Callback response

Resolves to a Role object.

setContent

var roleDefinition = {
  controllers: {
    "*": {
      actions: {
        "*": true
      }
    }
  }
};

role = role.setContent(roleDefinition);
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("*", new JSONObject()
      .put("actions", new JSONObject()
        .put("*", true)
      )
    )
  )
);

role.setContent(roleDefinition);
<?php

use Kuzzle\Security\Role;

// ...

$roleDefinition = [
  'controllers' => [
    '*' => [
      'actions' => [
        '*' => true
      ]
    ]
  ]
];

/*
 * @var $role Role
 */
$role->setContent($roleDefinition);

Replaces the content of the Role object.

setContent(data)

Arguments Type Description
data JSON Object Role content

Return value

Returns the Role object.

update

var updateContent = {
  controllers: {
    "document": {
      actions: {
        "get": true
      }
    }
  }
};

// Using callbacks (NodeJS or Web Browser)
role.update(updateContent, function(err, updatedRole) {
  // the updatedRole variable is the updated Role object
})

// Using promises (NodeJS)
role
  .updatePromise(updateContent)
  .then(updatedRole => {
    // the updatedRole variable is the updated Role object
  });
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("document", new JSONObject()
      .put("actions", new JSONObject()
        .put("get", true)
      )
    )
  )
);

role.update(roleDefinition, new ResponseListener<Role>() {
  @Override
  public void onSuccess(Role updatedRole) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\Role;

// ...

$roleDefinition = [
  'controllers' => [
    'document' => [
      'actions' => [
        'get' => true
      ]
    ]
  ]
];

/*
 * @var $role Role
 */

try {
  $role = $role->update($roleDefinition);

  // $role instanceof Role
}
catch (ErrorException $e) {
  // error occured
}

Updates the role object Kuzzle’s database layer.

To get more information on Kuzzle permissions, please refer to our Kuzzle Permissions guide.

update(content, [options], [callback])

Arguments Type Description
content JSON Object New role content
options JSON Object Optional parameters
callback function Optional callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Role object to allow chaining.

Callback response

Resolves to the updated version of this object

~ Profile

Profile is the object representation of a profile, which is a set of one or many Role objects.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 Profile objects are returned by Security.profile method:
 */
var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

var role = kuzzle.security.profile('myprofile', profileDefinition);
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject policy2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );
JSONObject roles = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)
    .put(policy2)
  );

Profile profile = new Profile(kuzzle.security, "profileId", roles);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\Profile;

$profileId = 'myProfile';
$profileDefinition = [
  'policies' => [
    [
      'roleId' => 'myRole'
    ],
    [
      'roleId' => 'anonymous',
      'restrictedTo' => [
        ['index' => 'my-second-index', 'collection' => ['my-collection']]
      ]
    ]
  ]
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();


// Using the Security factory:
$profile = $security->profile($profileId, $profileDefinition);

// Or directly with the constructor:
$profile = new Profile($security, $profileId, $profileDefinition);

Instantiates a new Profile object.

Profile(Security, id, content)

Arguments Type Description
Security Security An instantiated Security object
id string Unique profile identifier
content JSON Object Profile content

Note: this constructor won’t make any call to Kuzzle.

Return value

Returns to the Profile object.

Properties

Property name Type Description get/set
content JSON object Raw profile content get
id string Unique profile identifier get

addPolicy

profile.addPolicy({
  'roleId': 'some role id',
  'restrictedTo': [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ]
});
JSONObject policy = new JSONObject()
  .put("roleId", "some role id")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections", new JSONArray().put("foo").put("bar"))
    )
  );

profile.addPolicy(policy);

// you may also add a role ID directly
profile.addPolicy("some role id");

Adds a role to the profile.

addPolicy(id)

addPolicy(policy)

Arguments Type Description
id string Unique id corresponding to the new associated role
policy JSON Object policy instance corresponding to the new associated role and its restrictions

Return value

Returns the Profile object to allow chaining calls.

delete

// Using callbacks (NodeJS or Web Browser)
profile
  .delete(function(error, result) {
    // result is the id of deleted profile
  });

// Using promises (NodeJS)
profile
  .deletePromise()
  .then((result) => {
    // result is the id of deleted profile
  });
profile
  .delete(new ResponseListener<String>() {
    @Override
    public void onSuccess(String deleteId) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
<?php

use Kuzzle\Security\Profile;

// ...

/*
 * @var $profile Profile
 */
try {
  $profile->delete();
}
catch(ErrorException $e) {

}

Deletes this profile from Kuzzle.

delete([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to the id of the deleted profile.

getPolicies

for (policy of profile.getPolicies()) {
  // policy is a JSON object
}
for(JSONArray policy : profile.getPolicies()) {
  // policy is a JSON object
}
<?php

use Kuzzle\Security\Profile;
use Kuzzle\Security\Policy;

// ...

/*
 * @var $profile Profile
 */
foreach($profile->getPolicies() as $policy) {
  // $policy instanceof Policy
}

Returns this profile associated roles.

Return value

An array of associated roles

save

var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

var profile = kuzzle.security.profile('myprofile', profileDefinition);

// Using callbacks (NodeJS or Web Browser)
profile
  .save(function(error, result) {
    // result is a Profile object
  });

// Using promises (NodeJS)
profile
  .savePromise()
  .then(result => {
    // result is a Profile object
  });
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject policy2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );

JSONObject roles = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)
    .put(policy2)
  );

Profile profile = kuzzle.security.profile("myprofile", roles);

profile.save(new ResponseListener<Profile>() {
  @Override
  public void onSuccess(Profile savedProfile) {

  }

  @Overrid public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\Profile;

// ...

/*
 * @var $profile Profile
 */

try {
  $profile = $profile->save();

  // $profile instanceof Profile
}
catch (ErrorException $e) {

}

Creates or replaces the profile in Kuzzle.

save([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Profile object to allow chaining.

Callback response

Resolves to a Profile object.

setContent

var profile = kuzzle.security.fetchProfile('myprofile');
var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

profile = profile.setContent(profileDefinition);
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject policy2 = new JSONObject()
  .put("roleId", "default")
  .put("restrictedTo", new JSONArray()
    .put(new JSONObject().put("index", "index1"))
    .put(new JSONObject()
      .put("index", "index2")
      .put("collections",new JSONArray().put("foo").put("bar"))
    )
  );

JSONObject newContent = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)
    .put(policy2)
  );

profile.setContent(newRolesList);
<?php

use Kuzzle\Security\Profile;

// ...

$profileDefinition = [
  'policies' => [
    [
      'roleId' => 'anonymous',
      'restrictedTo' => [
        ['index' => 'my-second-index', 'collection' => ['my-collection']]
      ]
    ]
  ]
];

/*
 * @var $profile Role
 */
$profile->setContent($profileDefinition);

Replaces the content of the Profile object.

setContent(data)

Arguments Type Description
data JSON Object Profile content

Return value

Returns the Profile object.

setPolicies

policy = { "roleId": "roleId" };

// Replaces the profile policies set with the given entry.
profile.setPolicies([policy]);
// Binding role IDs to a profile
profile.setPolicies({"role1 ID", "role2 ID", "role3 ID"});

// Binding policies definition to a profile
profile.setPolicies({
  new JSONObject().put('roleId', 'role1 ID'),
  new JSONObject().put('roleId', 'role2 ID'),
  new JSONObject().put('roleId', 'role3 ID')
});

Replaces the roles associated to the profile.

setPolicies(Array policyIDs)

setPolicies(Array policyDefinitions)

Arguments Type Description
policyIDs array of strings Policy IDs to add
policyDefinitions array of JSON objects Policy definitions to add

Return value

Returns the Profile object.

update

var updateContent = {
  policies: [
    {roleId: 'myrole'},
  ]
};

// Using callbacks (NodeJS or Web Browser)
profile.update(updateContent, function(err, updatedProfile) {
  // the updatedProfile variable is the updated Profile object
})

// Using promises (NodeJS)
profile
  .updatePromise(updateContent)
  .then(updatedProfile => {
    // the updatedProfile variable is the updated Profile object
  });
JSONObject policy1 = new JSONObject().put("roleId", "myrole");

JSONObject updateContent = new JSONObject()
  .put("policies", new JSONArray().put(policy1));

profile.update(updateContent, new ResponseListener<Profile>() {
  @Override
  public void onSuccess(Profile updatedProfile) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});

Performs a partial content update on this object.

update(content, [options], [callback])

Arguments Type Description
content JSON Object Profile content
options JSON Object Optional parameters
callback function Optional callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the Profile object to allow chaining.

Callback response

Resolves to the updated version of this object

~ User

User is the object representation of an user, which is associated to a Profile object

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 User objects are returned by Security.user method:
 */
 var userContent = {
   // A "profile" field is required to bind a user to an existing profile
   profileIds: ['admin'],

   // The "local" authentication strategy requires a password
   password: 'secretPassword',

   // You can also set custom fields to your user
   firstname: 'John',
   lastname: 'Doe'
 };

var user = kuzzle.security.user('myuser', userContent);
JSONObject userContent = new JSONObject()
  // A "profile" field is required to bind a user to an existing profile
  .put("profileIds", new JSONArray().put("admin"))
  // The "local" authentication strategy requires a password
  .put("password", "secret password")
  // You can also set custom fields to your user
  .put("firstname", "John")
  .put("lastname", "Doe");

// Using the KuzzleSecurity factory:
User user = kuzzle.security.user("user ID", userContent);

// Or directly with the constructor:
User user = new User(kuzzle.security, "user ID", userContent);
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$userId = 'myUser';
$userDefinition = [
  // A "profileIds" field is required to bind a user to an existing profile
  'profileIds' => ['myProfile'],
  // The "local" authentication strategy requires a password
  'password' => 'secret',
  'firstname' => 'John',
  'lastname' => 'Doe'
];

$kuzzle = new Kuzzle('localhost');
$security = $kuzzle->security();

// Using the Security factory
$user = $security->user($userId, $userDefinition);

// Or directly with the constructor:
$user = new User($security, $userId, $userDefinition);

Instantiates a new User object.

User(Security, id, content)

Arguments Type Description
Security Security An instantiated Security object
id string Unique user identifier
content JSON Object User content

Note: this constructor won’t make any call to Kuzzle.

Return value

Returns the User object.

Properties

Property name Type Description get/set
content JSON object Raw user content get
id string Unique profile identifier get

addProfile

var profile = kuzzle.security.fetchProfile('myprofile', function(error, profile) {
  // Can add a profile directly with a Profile object
  user.addProfile(profile);
});

// Or by passing an id
user.addProfile('myprofile');

// Updating the profile with a Profile object
kuzzle
  .security
  .fetchProfile("myprofile", opts, new ResponseListener<Profile>() {
    @Override
    public void onSuccess(Profile profile) {
      // Can add the profile directly with a Profile object
      user.addProfile(profile);
    }
  });

// Updating the profile with a profile ID
user.addProfile("myprofile");
<?php

use Kuzzle\Security\Profile;
use Kuzzle\Security\User;

// ...

$profile = $kuzzle->security->fetchProfile('myProfile');

/*
 * @var $user User
 */

// Updating the profile with a Profile object
$user->addProfile($profile);

// Updating the profile with a profile ID
$user->addProfile('myProfile');

Replace the profile associated to the user

addProfile(profileId)

addProfile(profile)

Arguments Type Description
profileId string Profile ID
profile Profile An instantiated Profile object

Return value

Returns the User object.

delete

// Using callbacks (NodeJS or Web Browser)
user
  .delete(function(error, result) {
    // result is the id of deleted user
  });

// Using promises (NodeJS)
user
  .deletePromise()
  .then((result) => {
    // result is the id of deleted user
  });
user.delete(new ResponseListener<String>() {
  @Override
  public void onSuccess(String deletedId) {

  }

  @Override public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->delete();
}
catch (ErrorException $e) {

}

Deletes the user in Kuzzle

delete([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Callback response

Resolves to a String containing the deleted user ID

getProfiles

for (profile of user.getProfiles()) {
  // profile can either be a profile ID if the object has not been hydrated,
  // or a Profile object otherwise
}
for(Profile profile : user.getProfiles()) {
  // if this object has not been hydrated, the profile object has no content
}

Returns this user associated profiles.

Return value

Returns an array of associated profiles

save

// Using callbacks (NodeJS or Web Browser)
user
  .save(function(error, result) {
    // result is a User object
  });

// Using promises (NodeJS)
user
  .savePromise()
  .then((result) => {
    // result is a User object
  });
user.save(new ResponseListener<User>() {
  @Override
  public void onSuccess(User user) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->save();
}
catch (ErrorException $e) {

}

Create or replace the user in kuzzle

save([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the User object to allow chaining.

Callback response

Resolves to a User object.

saveRestricted

// Using callbacks (NodeJS or Web Browser)
user
  .saveRestricted(function(error, result) {
    // result is a User object
  });

// Using promises (NodeJS)
user
  .saveRestrictedPromise()
  .then((result) => {
    // result is a User object
  });
user.saveRestricted(new ResponseListener<User>() {
  @Override
  public void onSuccess(User user) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->saveRestricted();
}
catch (ErrorException $e) {

}

Saves this user as restricted into Kuzzle.

saveRestricted([options], [callback])

Arguments Type Description
options JSON Object Optional parameters
callback function (Optional) Callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the User object to allow chaining.

Callback response

Resolves to a User object.

setContent

var user = kuzzle.security.fetchUser('myuser');
var userContent = {
  profileIds: ['profileId']
};

user = user.setContent(userContent);
JSONObject newContent = new JSONObject()
  .put("profileIds", new JSONArray()
    .put("profileId")
  );

user.setContent(newContent);
<?php

use Kuzzle\Security\User;

// ...

$userContent = [
  'profileIds' => ['profileId']
];

/*
 * @var $user User
 */
$user->setContent($userContent);

Replaces the content of User

setContent(data)

Arguments Type Description
data JSON Object User content

Return value

Returns the User object.

setProfiles

var profile = kuzzle.security.fetchProfile('myprofile', function(error, profile) {
  // Can set the profiles directly with a Profile object
  user.setProfiles([profile]);
});

// Or by passing their ids
user.setProfiles(['myprofile']);

// Updating the profile with a Profile object
kuzzle
  .security
  .fetchProfile("myprofile", opts, new ResponseListener<Profile>() {
    @Override
    public void onSuccess(Profile profile) {

      ArrayList<Profile> profileIds = new ArrayList<Profile>();
      profileIds.add(profile);

      user.setProfiles(profileIds);

    }
  });

// Updating the profile with a profile ID
ArrayList<String> profileIds = new ArrayList<String>();
profileIds.add("myprofile");

user.setProfiles(profileIds);
<?php

use Kuzzle\Security\Profile;
use Kuzzle\Security\User;

// ...

$profile = $kuzzle->security->fetchProfile('myProfile');

/*
 * @var $user User
 */

// Updating the profile with a Profile object
$user->setProfiles([$profile]);

// Updating the profile with a profile ID
$user->setProfiles(['myProfile']);

Replace the profile associated to the user

setProfiles(profileIds)

setProfiles(profiles)

Arguments Type Description
profileIds array of strings List of profile IDs
profiles array of Profile objects An array of instantiated Profile objects

Return value

Returns the User object.

update

var updateContent = {
  firstname: 'My Name Is',
  lastname: 'Jonas'
};

// Using callbacks (NodeJS or Web Browser)
user.update(updateContent, function(err, updatedUser) {
  // the updatedUser variable is the updated User object
})

// Using promises (NodeJS)
role
  .updatePromise(updateContent)
  .then(updatedUser => {
    // the updatedUser variable is the updated User object
  });
JSONObject updateContent = new JSONObject()
  .put("firstname", "My Name Is")
  .put("lastname", "Jonas");

user.update(updateContent, new ResponseListener<User>() {
  @Override
  public void onSuccess(User updatedUser) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

$userContent = [
  'firstname' => 'My Name Is',
  'lastname' => 'Jonas'
];

try {
  $user->update($userContent);
}
catch (ErrorException $e) {

}

Performs a partial content update on this object.

update(content, [options], [callback])

Arguments Type Description
content JSON Object User content
options JSON Object Optional parameters
callback function Optional callback handling the response

Available options:

Option Type Description Default
queuable boolean Mark this request as (not) queuable true

Return value

Returns the User object to allow chaining.

Callback response

Resolves to the updated version of this object