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.

Here is the object diagram of our SDKs:

object diagram

Constructors

Connects to a Kuzzle instance.

/*
 As this SDK embarks two protocols instead of just one (WebSocket and SocketIO),
 the "port" option has been replaced by a "wsPort" and "ioPort" ones, used
 to set, respectively, the WebSocket port and the SocketIO one.

 These ports are defaulted to Kuzzle default values, so you only have to change
 them if you modify the protocols default values server-side.
 */
var kuzzle = new Kuzzle('localhost', {
  defaultIndex: 'some index',
  autoReconnect: true,
  headers: {someheader: "value"},
  ioPort: 7512,
  wsPort: 7513
});

// 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 KuzzleResponseListener<Void>() {
 @Override
 public void onSuccess(Void object) {
   // invoked once connected, object contains the kuzzle instance
 }

 @Override
 public void onError(JSONObject error) {
   // Handle connection error
 }
});
NSError* error = nil;
KuzzleOptions* opt = [[KuzzleOptions alloc] init];
opt.defaultIndex = @"some index";
opt.headers = @{
     @"someheader": @"value"
};
opt.port = 7512;
Kuzzle* kuzzle = [[Kuzzle alloc] initWithHost:@"localhost" options: opt connectionCallback:^(id object, NSError * errorConnection) {
  if(errorConnection) {
    // error occured
  }
  // everything went fine
} error: &error];

if(error) {
  // kuzzle was not initialized properly and error was thrown
}

NOTICE:
If you want to immediately access kuzzle after connection have a look at snippet below

@implementation YourClass {
  Kuzzle* kuzzle;
}

-(yourReturnType)yourMethod {
  NSError* error = nil;
  KuzzleOptions* opt = [[KuzzleOptions alloc] init];
  opt.defaultIndex = @"some index";
  opt.headers = @{
    @"someheader": @"value"
  };
  Kuzzle* kuzzle = [[Kuzzle alloc] initWithHost:@"localhost" options: opt connectionCallback:^(id object, NSError * errorConnection) {
    if(errorConnection) {
      // error occured
    }
    // everything went fine
    __weak Kuzzle* weakKuzzle = kuzzle;

    // example
    NSError* internalError = nil;
    [weakKuzzle getServerInfoAndReturnError: &internalError callback:^(NSDictionary* dictionary, NSError* errorInternal) {
      if(errorInternal) {
          // error occured
          return;
      }
      // everything went fine
    }];

  } error: &error];
}
  let options = KuzzleOptions()
      options
          .setDefaultIndex("some index")
          .setHeaders([
              "someheader": "value"
          ])
  do {
    var kuzzle = try Kuzzle(host: "localhost", options: options, connectionCallback: { result in
      switch result {
        case let .onError(error):
        // error occured during connecting, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is AnyObject
        break
      }
    })
  } catch {
    // KuzzleError.InvalidHost, when host name was not valid
    // KuzzleError.EmptyHost, when passed host name was empty
  }
}
<?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
ioPort integer (Javascript SDK only) Kuzzle network port for socket.io 7512
metadata JSON object Common metadata, will be sent to all future requests
offlineMode string Offline mode configuration manual
port integer (All SDKs except Javascript) 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
wsPort integer (Javascript SDK only) Kuzzle network port for websocket 7513

Notes:

  • the offlineMode option only accepts the manual and auto values
  • the Javascript SDK accepts ioPort and wsPort options instead of the port one. This is because this SDK supports 2 network protocols to ensure maximum performances AND compatibility depending on browsers capabilities

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
ioPort integer (Javascript SDK only) Kuzzle network port for socket.io 7512
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 (All SDKs except Javascript) 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
wsPort integer (Javascript SDK only) Kuzzle network port for websocket 7513

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 Websocket 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 deleted and new requests are queued
  • 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
  • the Javascript SDK accepts ioPort and wsPort options instead of the port one. This is because this SDK supports 2 network protocols to ensure maximum performances AND compatibility depending on browsers capabilities

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 KuzzleRoom.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
reconnected Fired when the current session has reconnected to Kuzzle after a disconnection, and only if autoReconnect is set to true
queryError Fired whenever Kuzzle responds with an error

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(KuzzleEvent.connected, new IKuzzleEventListener() {
  @Override
  public void trigger(Object... args) {
    // Actions to perform when receiving a 'subscribed' global event
  }
});
NSError* error = nil;
[kuzzle addListenerForEvent: KuzzleEventTypeCONNECTED error: &error callback:^(id result, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
kuzzle.addListener(.CONNECTED, callback: { result in
  switch result {
    case let .onError(error):
    // error occured during call, error is NSError
    break
    case let .onSuccess(success):
    // everything went fine, success is AnyObject
    break
  }
})
<?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 KuzzleResponseListener<KuzzleTokenValidity>() {
  @Override
  public void onSuccess(KuzzleTokenValidity tokenInfo) {
    if (tokenInfo.isValid()) {
      // tokenInfo.getExpiresAt() returns the expiration timestamp
    }
    else {
      // tokenInfo.getState() returns the invalidity reason
    }
  }
});
NSError* error = nil;
[kuzzle checkTokenWithToken: @"some jwt token" error: &error callback:^(KuzzleTokenValidity * tokenValidity, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.TokenEmpty, when token argument is empty string
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try checkToken(withToken: "some jwt token", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during connecting, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleTokenValidity
        break
      }
  })
} catch {
  // KuzzleError.TokenEmpty, when token argument is empty string
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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.

connect

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

// not implemented (sdk PHP is using REST API)

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

dataCollectionFactory

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

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

collection = kuzzle.dataCollectionFactory('collection');
KuzzleDataCollection collection = kuzzle.dataCollectionFactory("collection", "index");

// or using a default index:
kuzzle.setDefaultIndex("index");
KuzzleDataCollection collection = kuzzle.dataCollectionFactory("collection");
NSError* error = nil;
KuzzleDataCollection* collection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

// or using a default index:
NSError* error = nil;
KuzzleOptions* opt = [[KuzzleOptions alloc] init];
opt.defaultIndex = @"some index";
Kuzzle* kuzzle = [[Kuzzle alloc] initWithHost:@"localhost" options: opt error: &error];

KuzzleDataCollection* collection = [kuzzle dataCollectionFactoryWithCollectionName: @"" error: &error];
do {
  try kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
} catch {
  // KuzzleError.NoIndexSpecified, when defaultIndex and index passed in function are both nil
  // KuzzleError.IllegalState when state is .DISCONNECTED
}
// or using a default index, simplified snippet:
let options = KuzzleOptions()
    options
        .setDefaultIndex("some index")
        .setHeaders([
            "someheader": "value"
        ])
var kuzzle = try! Kuzzle(address: "localhost", options: options)

do {
  try kuzzle.dataCollectionFactory(collectionName: "collection")
} catch {
  // KuzzleError.NoIndexSpecified, when defaultIndex and index passed in function are both nil
  // KuzzleError.IllegalState when state is .DISCONNECTED
}
<?php
use \Kuzzle\Kuzzle;

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

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

Instantiates a new KuzzleDataCollection object.

dataCollectionFactory(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 KuzzleDataCollection object.

disconnect

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

// not implemented (sdk PHP is using REST API)

Closes the current connection.

flushQueue

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

// not implemented (sdk PHP is using REST API)

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 KuzzleResponseListener<JSONArray>() {
  @Override
  public void onSuccess(JSONArray object) {
    // loop through all returned frames
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
};
NSError* error = nil;
[kuzzle getAllStatisticsAndReturnError: &error callback:^(NSArray * results, NSError * error) {
  if(error) {
  // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try getAllStatistics(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Array with dictionaries
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<Boolean>() {
  @Override
  public void onSuccess(Boolean autoRefresh) {
    // autoRefresh var contains the autoRefresh status of myIndex.
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
}
do {
    try kuzzle.getAutoRefresh("myIndex", callback: {
      (result) in
        case let .onSuccess(autoRefresh):
          // autoRefresh var contains the autoRefresh status of myIndex.
        case let .onError(error)
          // Handle error
    })
} catch {
  //     Handle KuzzleError
  //     * KuzzleError.IllegalState when state is .DISCONNECTED
  //     * KuzzleError.StrategyEmpty when strategy passed to function was empty string
}
<?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();
NSString* token = [kuzzle getJwtToken];
let token:String? = kuzzle.getJwtToken() // token can be nil!
<?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 KuzzleResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject rights) {
        // result is a JSON object
    }

    @Override
    public void onError(JSONObject error) {
        // Handle error
    }
  });
// Not implemented yet
kuzzle
  .security
  .getMyRights(callback: {(response) in
    switch response {
      case let .onSuccess(rights):
        // rights is a JsonObject
      case let .onError(error):
        // handle the error here
    }
  })

<?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 KuzzleResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject result) {
    // Handle success
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle getServerInfoAndReturnError: &error callback:^(NSDictionary* serverInfo, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.getServerInfo(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Dictionary
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject object) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle getStatisticsAndReturnError: &error callback:^(NSArray * stats, NSError * error) {
    if(error) {
    // error occured
  }
  // everything went fine
}]
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.getStatistics(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is array
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject object) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle listCollectionsAndReturnError: &error callback:^(NSDictionary * collections, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.NoIndexSpecified, when defaultIndex and index passed in function are both nil
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.listCollections(index: "some index", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Dictionary
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<String[]>() {
  @Override
  public void onSuccess(String[] result) {
    // ...
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle listIndexesAndReturnError: &error callback:^(NSArray * array, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.listIndexes(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Array with indexes
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<JSONObject>() {
  @Override
  public void onSuccess(JSONObject result) {
    // ...
  }

  @Override
  public void onError() {
    // Handle error
  }
});
NSError* error = nil;
NSDictionary* credentials = @{@"username": @"John Doe", @"password": @"my secret password"};
[kuzzle loginWithStrategy: @"local" credentials: credentials error: &error callback:^(NSDictionary* result, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.StrategyEmpty when strategy passed to function was empty string
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try try kuzzle.login(withStrategy: "local", credentials: credentials, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Dictionary
        break
      }
  })
} catch {
  // KuzzleError.StrategyEmpty when strategy passed to function was empty string
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleResponseListener<Void>() {
  @Override
  public void onSuccess(Void result) {
    // ...
  }

  @Override
  public void onError() {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle logoutAndReturnError: &error callback:^(id result, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
kuzzle.logout(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is AnyObject
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

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

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 KuzzleMemoryStorage 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 KuzzleResponseListener<Date>() {
  @Override
  public void onSuccess(Date object) {
    // 'object' contains the Kuzzle timestamp (utc, in milliseconds)
  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
NSError* error = nil;
[kuzzle nowAndReturnError: &error callback:^(NSDate * date, NSError * error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.now(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is NSDate
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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: 'read', action: 'search'}, {match: { message: 'this is a test' }}, function (err, res) {
  // ...
});

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

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

  }

  @Override
  public void onError(JSONObject error) {
    // Handle error
  }
});
QueryArgs* queryArgs = [[QueryArgs alloc] init];
queryArgs.controller = @"read";
queryArgs.action = @"search";

NSDictionary* query = @{@"": @""};

[kuzzle queryWithQueryArgs: queryArgs query: query error: &error callback:^(NSDictionary * result, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let queryArgs = QueryArgs(controller: "read", action: "search")
let query = ["": ""]
try kuzzle.query(queryArgs: queryArgs, query: query, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is Dictionary
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

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

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

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

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 Kuzzle API Documentation

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");
try kuzzle.refreshIndex("myIndex")
<?php
use \Kuzzle\Kuzzle;

$kuzzle = new Kuzzle('localhost');

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

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(KuzzleEvent.disconnected);

// Removes all listeners on all global events
kuzzle.removeAllListeners();
// Removes all listeners on the "unsubscribed" global event
[kuzzle removeAllListenersWithEvent: KuzzleEventTypeDISCONNECTED];

// 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(KuzzleEvent.disconnected, "listenerId");
[kuzzle removeListenerWithEvent: KuzzleEventTypeDISCONNECTED listenerId: @"listenerId"];
kuzzle.removeListener(event: .DISCONNECTED, listenerId: "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();
[kuzzle replayQueue];
kuzzle.replayQueue()
<?php

// not implemented (sdk PHP is using REST API)

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 KuzzleSecurity singleton.

setAutoRefresh

kuzzle.setAutoRefresh('myIndex', true);
try kuzzle.setAutoRefresh("myIndex", autoRefresh: 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');
[kuzzle setDefaultIndex: @"index"];
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 KuzzleResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSDictionary* content = @{
                          @"firstname": @"My Name Is",
                          @"lastname": @"Jonas"
                          };
[kuzzle updateSelfWithContent: content error: &error callback:^(NSDictionary * result, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
  let content = [
    "firstname": "My Name Is",
    "lastname": "Jonas"
  ]
  do {
  try kuzzle.updateSelf(content: content, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is dictionary
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

<?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) {
  // error occured
}

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);
NSDictionary* headers = @{@"someContent": @"someValue"};

[kuzzle setHeadersWithData: headers replace: YES];
// merge headers with already existing ones
[kuzzle setHeadersWithData: headers];
let headers = ["someContent": "someValue"]

kuzzle.setHeaders(content: headers, replace: true)
// merge headers with already existing ones
kuzzle.setHeaders(content: headers);
<?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)
// Directly with a JWT Token
NSError* error = nil;
[kuzzle setJwtToken: @"some jwt token" error: &error];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

/*
 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 NSDictionary returned by e.g.KuzzleWebView
 */
NSError* error = nil;
[kuzzle setJwtTokenFromResponse: authenticationResponse error: &error];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
// Directly with a JWT Token
do {
  try kuzzle.setJwtToken("some jwt token")
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

/*
 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 Dictionary returned by e.g.KuzzleWebView
 */
 do {
  try kuzzle.setJwtToken(fromResponse: authenticationResponse)
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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();
[kuzzle unsetJwtToken];
// Directly with a JWT Token
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();
[kuzzle startQueuing];
kuzzle.startQueuing()
<?php

// not implemented (sdk PHP is using REST API)

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();
[kuzzle stopQueuing];
kuzzle.stopQueuing()
<?php

// not implemented (sdk PHP is using REST API)

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 KuzzleUser object
});

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

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[kuzzle whoAmIAndReturnError: &error callback:^(KuzzleUser * user, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.whoAmI(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php
use \Kuzzle\Kuzzle;
use \Kuzzle\Security\User;

$kuzzle = new Kuzzle('localhost');

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

Retrieves current user object.

whoAmI(callback)

Arguments Type Description
callback function Callback handling the response

Callback response

An instanciated KuzzleUser object.

KuzzleDataCollection

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 KuzzleDataCollection(kuzzle, "my-collection", "my-index")
  KuzzleDataCollection myCollection = new KuzzleDataCollection(kuzzle, "my-collection", "my-index");
  KuzzleDataCollection* myCollection = [[KuzzleDataCollection alloc] initWithKuzzle: kuzzle collection: @"my-collection" index: @"my-index" ];
  let myCollection = KuzzleDataCollection(kuzzle: kuzzle, collection: "my-collection", index: "my-index")
<?php

use \Kuzzle\Kuzzle;
use \Kuzzle\DataCollection;

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

KuzzleDataCollection(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 recommanded to instanciate a KuzzleDataCollection object by calling Kuzzle.dataCollectionFactory 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

count

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

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];
NSDictionary* filter = @{};
[myCollection countWithFilters: filter error: &error callback:^(NSNumber * amount, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let filter = ["":""]
do {
  let myCollection = try kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
  try myCollection.count(filters: filter, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is integer
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

$filters = [];

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

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

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
  .dataCollectionFactory('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
 .dataCollectionFactory('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
  .dataCollectionFactory("collection", "index")
  .create(new KuzzleResponseListener<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
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection createAndReturnError: &error callback:^(NSDictionary * collections, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.create(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDataCollection object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

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

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

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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to a JSON object containing the raw Kuzzle response.

createDocument

// Using callbacks (NodeJS or Web Browser)
kuzzle
  .dataCollectionFactory('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 KuzzleDocument object
  });

// Using promises (NodeJS only)
kuzzle
 .dataCollectionFactory('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 KuzzleDocument object
 });
KuzzleDocument myDocument = new KuzzleDocument(collection);
myDocument.setContent("title", "foo");
myDocument.setContent("content", "bar");

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];
KuzzleOptions* options = [[KuzzleOptions alloc] init];
options.updateIfExists = YES;

KuzzleDocument* document = [[KuzzleDocument alloc] initWithCollection: myCollection];
document.content = @{
  @"foo": @"title",
  @"bar": @"content"
};

if(!error) {
    [myCollection createDocumentWithDocument: document options: options error:&error callback:^(KuzzleDocument * document, NSError * error) {
        if(error) {
            // error occured
        }
        // everything went fine
    }];

    if(error) {
        // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
    }
} else {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  let options = KuzzleOptions()
  options.setUpdateIfExists(true)
  let document = KuzzleDocument(collection: myCollection)
  document.content = [
    "title": "foo",
    "content": "bar"
  ]
  try myCollection.createDocument(document: document, options: options, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

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

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

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

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

Create a new document in Kuzzle.

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

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

Arguments Type Description
KuzzleDocument object KuzzleDocument 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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to a KuzzleDocument object containing the newly created document.

dataMappingFactory

var dataMapping = kuzzle
  .dataCollectionFactory('collection', 'index')
  .dataMappingFactory({someField: {type: 'string', index: 'analyzed'}})
  .apply();
KuzzleDataMapping dataMapping = kuzzle
  .dataCollectionFactory("collection", "index")
  .dataMappingFactory(new JSONObject().put("someFiled", new JSONObject().put("type", "string").put("index", "analyzed"))
  .apply();
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [[myCollection dataMappingFactoryWithMapping: @{@"someField": @{@"type": @"string", @"index": @"analyzed"}}] applyAndReturnError: &error];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
myCollection.dataMappingFactory(withMapping: ["someField": ["type": "string", "index": "analyzed"]])
<?php

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

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

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

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

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

Creates a new KuzzleDataMapping object, using its constructor.

dataMappingFactory([mapping])

Arguments Type Description
mapping JSON Object Optional mapping

Return value

Returns the newly created KuzzleDataMapping object.

delete

deleteDocument

// Deleting one document using callbacks (NodeJS or Web Browser)
kuzzle
  .dataCollectionFactory('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
  .dataCollectionFactory('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
  .dataCollectionFactory('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
 .dataCollectionFactory('collection', 'index')
 .deleteDocumentPromise({filter: {equals: {title: 'foo'}}})
 .then(res => {
   // promise resolved once the delete by query has been completed
 });
// Deleting one document
kuzzle
  .dataCollectionFactory("collection", "index")
  .deleteDocument("document unique ID", new KuzzleResponseListener<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
  .dataCollectionFactory("collection", "index")
  .deleteDocument(equalsFilter, new KuzzleResponseListener<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
    }
  });
// Deleting one document
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection deleteDocumentWithDocumentId: @"document unique ID" error: &error callback:^(NSArray * deletedItems, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

// Deleting multiple documents
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection deleteDocumentWithFilters: @{@"filter": @{@"equals": @{@"title": @"foo"}} error: &error callback:^(NSArray * deletedItems, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
// Deleting one document
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  try myCollection.deleteDocument(documentId: "document unique ID", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is array with deleted item
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

// Deleting multiple documents
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  try myCollection.deleteDocument(filters: ["filter": ["equals": ["title": "foo"]]], callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is array with deleted item
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

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

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

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

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

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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to an array containing the deleted document IDs.

documentFactory

var document = kuzzle
  .dataCollectionFactory('collection', 'index')
  .documentFactory('id', {some: 'content'})
  .save();
KuzzleDocument document = kuzzle
  .dataCollectionFactory("collection", "index")
  .documentFactory("id", new JSONObject().put("some", "content"))
  .save();
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  KuzzleDocument* document = [myCollection documentFactoryWithId: @"id" content: @{@"some": @"content"}];
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  try myCollection.documentFactory(id: "id", content: ["some": "content"])
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

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

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

// $document instanceof Document

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

Creates a new KuzzleDocument object, using its constructor.

documentFactory([id], [content])

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

Return value

Returns the newly created KuzzleDocument object.

fetchDocument

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection fetchDocumentWithDocumentId: "documentId" error: &error callback:^(KuzzleDocument * document, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.fetchDocument(documentId: "documentId", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

$documentId = 'foobar';

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

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

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

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 KuzzleDocument object.

fetchAllDocuments

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

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection fetchAllDocumentsAndReturnError: &error callback:^(KuzzleDocumentList * documentList, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.fetchAllDocuments(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocumentList object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

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

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

  // $result instanceof SearchResult

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

Callback response:

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

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 KuzzleDocument objects

getMapping

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
    [myCollection getMappingAndReturnError: &error callback:^(KuzzleDataMapping * mapping, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  try myCollection.getMapping(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDataMapping object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

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

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

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

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 KuzzleDataMapping object.

publishMessage

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

kuzzle
  .dataCollectionFactory("collection", "index")
  .publish(message, opts);
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  KuzzleOptions* options = [[KuzzleOptions alloc] init];
  options.metadata = @{@"metadata": @"is volatile information"};
  [myCollection publishMessageWithContent: @{@"foo": @"bar", @"baz": @"qux"} options: options error: &error];
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  // NSError representation for KuzzleError.ContentEmpty, when content of passed document is empty
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
do {
  let options = KuzzleOptions()
  options.setMetadata(["metadata": "is volatile information"])
  try myCollection.publishMessage(content: ["foo": "bar", "baz": "qux"], options: options)
} catch {
  // KuzzleError.ContentEmpty, when content of passed document is empty
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

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

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

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

Publish a realtime message

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

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

Arguments Type Description
KuzzleDocument object KuzzleDocument 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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to a raw Kuzzle response in JSON format.

replaceDocument

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

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

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

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection replaceDocumentWithDocumentId: @"documentId" content: @{@"new": @"document content"} error: &error callback: ^(KuzzleDocument * document, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.replaceDocument(documentId: "documentId", content: ["new": "document content"], callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

<?php

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

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

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

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

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

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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to an updated KuzzleDocument object.

roomFactory

var room = kuzzle
  .dataCollectionFactory('collection', 'index')
  .roomFactory()
  .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")
      )
  );

KuzzleRoom room = kuzzle.dataCollectionFactory("collection", "index")
  .roomFactory()
  .renew(filters, new KuzzleResponseListener<KuzzleNotificationResponse>() {
    @Override
      public void onSuccess(KuzzleNotificationResponse object) {
        // handle notifications
      }

      @Override
      public void onError(JSONObject error) {
        // Handle notifications error
      }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  KuzzleRoom* room = [myCollection roomFactory];
  [room renewWithFilters: @{@"in": @{@"field": @[@"some", @"new", @"filter"]}} error: &error callback:^(KuzzleNotification * notification, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
let room = dataCollection.roomFactory()
do {
  try room.renew(filters: ["in": ["field": ["some", "new", "filter"]]], callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleNotification object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

// not implemented (sdk PHP is using REST API)

Creates a new KuzzleRoom object, using its constructor.

roomFactory([options])

Arguments Type Description
options object Subscription configuration

Return value

Returns the newly created KuzzleRoom 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
  .dataCollectionFactory('collection', 'index')
  .search(filter, function (err, res) {
    res.documents.forEach(document => {
      console.log(document.toString());
    });
  });

// Using promises (NodeJS only)
kuzzle
  .dataCollectionFactory('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
  .dataCollectionFactory("collection", "index")
  .search(userFilter, new KuzzleResponseListener<KuzzleDocumentList>() {
    @Override
    public void onSuccess(KuzzleDocumentList result) {
      for (KuzzleDocument 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
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

NSDictionary* inStatus = @{
  @"in": @{
    @"status": @[
      @"idle", @"wantToHire", @"toHire", @"riding"
    ],
  }
};

NSDictionary* inType = @{
  @"in": @{
    @"type": @[@"cab"]
  }
};

NSDictionary* geoDistance = @{
  @"geo_distance": @{
    @"distance": @"10km",
    @"pos": @{
      @"lat": @"54.4838902",
      @"lon": @"17.01559"
    }
  }
};

NSDictionary* filter = @{
  @"filter": @{
    @"and": @[
     inStatus,
     inType,
     geoDistance
    ]
  }
};

[myCollection searchWithFilters: filter error: &error callback:^(KuzzleDocumentList* documentList, NSError* error) {
    if(error) {
        // error occured
    }
    // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
  let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
  let inStatus = [
    "in": [
      "status": ["idle", "wantToHire", "toHire", "riding"],
    ]
  ]
  let inType = [
    "in":[
      "type": ["cab"]
    ]
  ]

  let geoDistance = [
    "geo_distance": [
      "distance": "10km",
      "pos": [
        "lat": "54.4838902",
        "lon": "17.01559"
        ]
    ]
  ]

  let filter = [
    "filter": [
      "and": [
        inStatus,
        inType,
        geoDistance
      ]
    ]
  ]
  do {
    try myCollection.search(filters: filter, callback: { result in
        switch result {
          case let .onError(error):
          // error occured during call, error is NSError
          break
          case let .onSuccess(success):
          // everything went fine, success is KuzzleDocumentList object
          break
        }
    })
  } catch {
    // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
<?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->dataCollectionFactory('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) {
  // error occured
}

Callback response:

{ "total": 3,
  "documents": [<KuzzleDocument>, <KuzzleDocument>, <KuzzleDocument>],
  "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 KuzzleDocument objects
  • an array of aggregations objects if some are provided in the request (see the Elasticsearch documentation for more details)

setHeaders

kuzzle
  .dataCollectionFactory('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
  .dataCollectionFactory("collection", "index")
  .setHeaders(content, true);
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  NSDictionary* headers = @{
    @"someContent": @"someValue",
    @"metadata": @{
      @"someMetaData": @[
        @"with",
        @"some",
        @"values"
        ]
      }
    };
  [myCollection setHeadersWithData: headers replace: YES];
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

let headers = [
  "someContent": "someValue",
  "metadata": [
    "someMetaData": [
     "with",
      "some",
      "values"
    ]
  ]
]

myCollection.setHeaders(content: headers, replace: true)
<?php

use \Kuzzle\Kuzzle;

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

$kuzzle = new Kuzzle('localhost');
$dataCollection = $kuzzle->dataCollectionFactory('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 KuzzleDataCollection object to allow chaining.

subscribe

kuzzle
  .dataCollectionFactory('collection', 'index')
  .subscribe({equals: {title: 'foo'}}, function (error, result) {
    // called each time a new notification on this filter is received
    // check the KuzzleRoom/Notifications section of this documentation
    // to get notification examples
  })
  .onDone(function (err, kuzzleRoomInstance) {
    // 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
  .dataCollectionFactory("collection", "index")
  .subscribe(filter, new KuzzleResponseListener<KuzzleNotificationResponse>() {
    @Override
    public void onSuccess(KuzzleNotificationResponse object) {
      // called each time a new notification on this filter is received

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle subscription error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

NSDictionary* inStatus = @{
  @"in": @{
    @"status": @[
      @"idle", @"wantToHire", @"toHire", @"riding"
    ],
  }
};

NSDictionary* inType = @{
  @"in": @{
    @"type": @[
      @"cab"
    ]
  }
};

NSDictionary* geoDistance = @{
  @"geo_distance": @{
    @"distance": @"10km",
    @"pos": @{
     @"lat": @"54.4838902",
     @"lon": @"17.01559"
    }
  }
};

NSDictionary* filter = @{
  @"filter": @{
    @"and": @[
      inStatus,
      inType,
      geoDistance
    ]
  }
};

if(!error) {
  [myCollection subscribeWithFilters: filter error: &error callback:^(KuzzleDocumentList* documentList, NSError* error) {
    if(error) {
        // error occured
    }
    // everything went fine
}];
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
  let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")
  let inStatus = [
    "in": [
      "status": ["idle", "wantToHire", "toHire", "riding"],
    ]
  ]
  let inType = [
    "in":[
      "type": ["cab"]
    ]
  ]

  let geoDistance = [
    "geo_distance": [
      "distance": "10km",
      "pos": [
        "lat": "54.4838902",
        "lon": "17.01559"
      ]
    ]
  ]

  let filter = [
    "filter": [
      "and": [
        inStatus,
        inType,
        geoDistance
      ]
    ]
  ]
  do {
    try myCollection.subscribe(filters: filter, callback: { result in
        switch result {
          case let .onError(error):
          // error occured during call, error is NSError
          break
          case let .onSuccess(success):
          // everything went fine, success is KuzzleDocumentList object
          break
        }
    })
  } catch {
    // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
<?php

// not implemented (sdk PHP is using REST API)

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 KuzzleRoom 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
  .dataCollectionFactory('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
 .dataCollectionFactory('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
  .dataCollectionFactory("collection", "index")
  .truncate(new KuzzleResponseListener<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
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection truncateAndReturnError: &error callback:^(NSDictionary * result, NSError * error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.truncate(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is dictionary
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

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

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

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 KuzzleDataCollection object to allow chaining.

Callback response

Resolves to a JSON object containing the raw Kuzzle response.

updateDocument

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

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

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

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
  });
NSError* error = nil;
KuzzleDataCollection* myCollection = [kuzzle dataCollectionFactoryWithCollectionName: @"collection" index: @"index" error: &error];

if(!error) {
  [myCollection updateDocumentWithDocumentId: @"documentId" content: @{@"title":@"a shiny new title"} error: &error callback:^(KuzzleDocument * document, NSError *  error) {
    if(error) {
      // error occured
    }
    // everything went fine
  }];

  if(error) {
    // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
  }
} else {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let myCollection = try! kuzzle.dataCollectionFactory(collectionName: "collection", index: "index")

do {
  try myCollection.updateDocument(documentId: "documentId", content: ["title": "a shiny new title"], callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

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

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

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

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

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 peristence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns the KuzzleDataCollection object to allow chaining.

Callback response

Resolves to an up-to-date KuzzleDocument object.

KuzzleDocument

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

Constructors

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

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

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

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

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

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

KuzzleDocument document = new KuzzleDocument(collection, "id", content);
KuzzleDocument* document = [[KuzzleDocument alloc] initWithCollection: collection];

KuzzleDocument* document = [[KuzzleDocument alloc] initWithCollection: collection documentId: @"documentId"];

NSDictionary* content = @{
                          @"content": @"some content"
                          };

KuzzleDocument* document = [[KuzzleDocument alloc] initWithCollection: collection content: content];

KuzzleDocument* document = [[KuzzleDocument alloc] initWithCollection: collection documentId: @"documentId" content: content];
let document = KuzzleDocument(collection: dataCollection)

let document = KuzzleDocument(collection: dataCollection, documentId: "documentId")


let content = ["content": "some content"]

let document = KuzzleDocument(collection: dataCollection, content: content)

let document = KuzzleDocument(collection: dataCollection, documentId: "documentId", content: content)
<?php

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

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

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

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

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

KuzzleDocument(KuzzleDataCollection, [documentId], [content])

Arguments Type Description
KuzzleDataCollection object An instanciated KuzzleDataCollection 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 KuzzleDataCollection 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 KuzzleResponseListener<KuzzleDocument>() {
    @Override
    public void onSuccess(KuzzleDocument object) {
      // called once the delete action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
NSError* error = nil;
[document deleteAndReturnError: &error callback:^(NSString * deletedDocumentId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try document.delete(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleDocument
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

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

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 peristence 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();
NSError* error = nil;
[document publishAndReturnError: &error];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try document.publish()
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

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

Publishes the content of this document as a realtime 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 KuzzleDocument 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 KuzzleResponseListener<KuzzleDocument>() {
    @Override
    public void onSuccess(KuzzleDocument object) {
      // called once the refresh action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
NSError* error = nil;
[document refreshAndReturnError: &error callback: ^(KuzzleDocument * document, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try document.refresh(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

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

Creates a new KuzzleDocument 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 KuzzleDocument 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 KuzzleResponseListener<KuzzleDocument>() {
    @Override
    public void onSuccess(KuzzleDocument object) {
      // called once the save action has been completed
    }

    @Override
    public void onError(JSONObject error) {
      // Handle error
    }
});
NSError* error = nil;
[document saveAndReturnError: &error callback:^(KuzzleDocument * document, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try document.save(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDocument object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Document;

// ...

/**
 * @var $document Document
 */

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

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 peristence layer indexation to return (available with Elasticsearch 5.x and above) undefined

Return value

Returns this KuzzleDocument object to allow chaining.

Callback response

Resolves to this KuzzleDocument 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);
NSDictionary* content = @{
  @"content": @"some content"
};

[document setContentWithData: content replace: YES];
let content = [
    "content": "some content"
]
document.setContent(content: content, replace: 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 KuzzleDocument object to allow chaining.

setHeaders

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

document.setHeaders(headers, true);
NSDictionary* headers = @{
  @"someContent": @"someValue",
  @"metadata": @{
    @"someMetaData": @[
      @"with",
      @"some",
      @"values"
      ]
    }
  };
[document setHeadersWithData: headers replace: YES];
let headers = [
  "someContent": "someValue",
  "metadata": [
    "someMetaData": [
     "with",
      "some",
      "values"
    ]
  ]
]
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 KuzzleDocument object to allow chaining.

subscribe

document
  .subscribe(function (error, notification) {
    // called each time a change occurs on this document
  })
  .onDone(function (error, kuzzleRoomInstance) {
    // 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, kuzzleRoomInstance) {
    // Handles the subscription result
  });
KuzzleRoom room = document.subscribe(new KuzzleResponseListener<KuzzleNotificationResponse>() {
    @Override
    public void onSuccess(KuzzleNotificationResponse object) {
      // called each time a change occurs on this document
    }

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

    @Override
    public void onError(JSONObject error) {
      // Handle subscription error
    }
  });
NSError* error = nil;
KuzzleRoom* room = [document subscribeAndReturnError: &error callback:^(KuzzleNotification * notification, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let room = try document.subscribe(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleNotification object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

// not implemented (sdk PHP is using REST API)

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

KuzzleRoom

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 subcribing to all changes occuring 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 (realtime)
  • a matching document is about to be created or deleted (realtime)
  • 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 notificating 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 realtime 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 susbcribed 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.
 KuzzleRoom objects are returned by KuzzleDataCollection.subscribe and
 KuzzleDocument.subscribe methods.

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

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

KuzzleRoomOptions options = new KuzzleRoomOptions().setSubscribeToSelf(false);
KuzzleRoom room = new KuzzleRoom(dataCollection, options);
KuzzleRoom* room = [[KuzzleRoom alloc] initWithCollection: dataCollection];

KuzzleRoomOptions* roomOptions = [[KuzzleRoomOptions alloc] init];
roomOptions.subscribeToSelf = YES;
KuzzleRoom* room = [[KuzzleRoom alloc] initWithCollection: dataCollection options: roomOptions];
let room = KuzzleRoom(collection: dataCollection)

let roomOptions = KuzzleRoomOptions()
roomOptions.subscribeToSelf = true
let room = KuzzleRoom(collection: dataCollection, options: roomOptions)
<?php

// not implemented (sdk PHP is using REST API)

Creates a KuzzleRoom object.

KuzzleRoom(KuzzleDataCollection, [options])

Arguments Type Description
KuzzleDataCollection object an instantiated Kuzzle Data 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 realtime 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 KuzzleDataCollection object and can be overrided
  • 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 KuzzleResponseListener<Integer>() {
 @Override
 public void onSuccess(Integer result) throws Exception {
   //  ...
 }

 @Override
 public void onError(JSONObject error) throws Exception {
   // Handle error
 }
});
NSError* error = nil;
[room countAndReturnError: &error callback:^(NSNumber * amount, NSError * _Nullable error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try room.count(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is integer
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

// not implemented (sdk PHP is using REST API)

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 KuzzleRoom/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 KuzzleResponseListener<KuzzleNotificationResponse>() {
 @Override
 public void onSuccess(KuzzleNotificationResponse result) throws Exception {
   // called each time a change is detected on documents matching this filter

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

 @Override
 public void onError(JSONObject error) throws Exception {
   // Handle error
 }
}, new KuzzleResponseListener<KuzzleRoom>() {
  // Handle the subscription result
});
NSError* error = nil;

NSDictionary* inStatus = @{
                             @"in": @{
                                     @"status": @[
                                             @"idle", @"wantToHire", @"toHire", @"riding"
                                             ],
                                     }};

NSDictionary* inType = @{
                           @"in": @{
                                   @"type": @[@"cab"]
                                   }
                           };

NSDictionary* geoDistance = @{
                              @"geo_distance": @{
                                      @"distance": @"10km",
                                      @"pos": @{
                                              @"lat": @"54.4838902",
                                              @"lon": @"17.01559"
                                              }
                                      }
                              };

NSDictionary* filter = @{
                         @"filter": @{
                                 @"and": @[
                                         inStatus,
                                         inType,
                                         geoDistance
                                         ]
                                 }};

[room renewWithFilters: filter error: &error callback:^(KuzzleNotification * notification, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let inStatus = [
  "in": [
    "status": ["idle", "wantToHire", "toHire", "riding"],
  ]
]

let inType = [
  "in":[
    "type": ["cab"]
  ]
]

let geoDistance = [
  "geo_distance": [
  "distance": "10km",
  "pos": [
    "lat": "54.4838902",
    "lon": "17.01559"
    ]
  ]
]

let filter = [
  "filter": [
    "and": [
      inStatus,
      inType,
      geoDistance
    ]
  ]
]

do {
  try room.renew(filters: filter, callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleNotification
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

// not implemented (sdk PHP is using REST API)

Renew the subscription. Force a resubscription using the same filters if no new ones are provided. Unsubscribes first if this KuzzleRoom 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);
NSDictionary* headers = @{
  @"someContent": @"someValue",
  @"metadata": @{
    @"someMetaData": @[
      @"with",
      @"some",
      @"values"
      ]
    }
  };
[room setHeadersWithData: headers replace: YES];
let headers = [
  "someContent": "someValue",
  "metadata": [
    "someMetaData": [
     "with",
      "some",
      "values"
    ]
  ]
]
room.setHeaders(headers, true);
<?php

// not implemented (sdk PHP is using REST API)

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 KuzzleRoom object to allow chaining.

unsubscribe

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

// not implemented (sdk PHP is using REST API)

Cancels the current subscription.

Return value

Returns this KuzzleRoom object to allow chaining.

KuzzleDataMapping

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 KuzzleDataMapping 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.
 KuzzleDataMapping objects are returned by the method
 KuzzleDataCollection.getMapping

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

mapping = kuzzle.dataCollectionFactory('collection', 'index').dataMappingFactory(mapping);
KuzzleDataMapping dataMapping = new KuzzleDataMapping(dataCollection);

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

KuzzleDataMapping dataMapping = new KuzzleDataMapping(dataCollection, mapping);
KuzzleDataMapping* dataMapping = [[KuzzleDataMapping alloc] initWithCollection: myCollection];

NSDictionary* mappping = @{
                           @"foo": @{
                                   @"type": @"string"
                                   }
                           };
KuzzleDataMapping* dataMapping = [[KuzzleDataMapping alloc] initWithCollection: myCollection mapping: mappping];
let dataMapping = KuzzleDataMapping(collection: dataCollection)

let dataMapping = KuzzleDataMapping(collection: dataCollection!, mapping: ["foo": ["type": "string"]])
<?php

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

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

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

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

KuzzleDataMapping(KuzzleDataCollection, [mapping])

Arguments Type Description
KuzzleDataCollection JSON Object An instanciated KuzzleDataCollection 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 KuzzleDataCollection 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 KuzzleResponseListener<KuzzleDataMapping>() {
   @Override
   public void onSuccess(KuzzleDataMapping object) {
     // called once the mapping action has been completed
   }

   @Override
   public void onError(JSONObject error) {
     // Handle error
   }
});
NSError* error = nil;
[dataMapping applyAndReturnError: &error callback:^(KuzzleDataMapping * mapping, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
do {
  try dataMapping.apply(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDataMapping object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleDataMapping object to allow chaining.

Callback response

Resolves to this updated KuzzleDataMapping 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 KuzzleResponseListener<KuzzleDataMapping>() {
   @Override
   public void onSuccess(KuzzleDataMapping object) {
     // called once the mapping has been retrieved from Kuzzle
   }

   @Override
   public void onError(JSONObject error) {
     // Handle error
   }
});
NSError* error = nil;
[dataMapping refreshAndReturnError: &error callback:^(KuzzleDataMapping * mapping, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];
do {
  try dataMapping.refresh(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleDataMapping object
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\DataMapping;

// ...

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

Instanciates a new KuzzleDataMapping 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 KuzzleDataMapping 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);
NSDictionary* fieldValue = @{
                             @"type": @"string",
                             @"index": @"analyzed",
                             @"null_value": @"",
                             };
[dataMapping setWithField: @"field" value: fieldValue];
let fieldValue = [
    "type": "string",
    "index": "analyzed",
    "null_value": ""
]
dataMapping.set(field: "field", value: fieldValue)
<?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 KuzzleDataMapping object to allow chaining.

setHeaders

dataMapping.setHeaders({someContent: 'someValue'}, true);
JSONObject headers = new JSONObject();
headers.put("someContent", "someValue");
dataMapping.setHeaders(headers, true);
NSDictionary* headers = @{
  @"someContent": @"someValue",
  @"metadata": @{
    @"someMetaData": @[
      @"with",
      @"some",
      @"values"
      ]
    }
  };
[dataMapping setHeadersWithData: headers replace: YES];
let headers = [
  "someContent": "someValue",
  "metadata": [
    "someMetaData": [
     "with",
      "some",
      "values"
    ]
  ]
]
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 KuzzleDataMapping object to allow chaining.

KuzzleMemoryStorage

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

  • all cluster based functions
  • all script based functions
  • all 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
 KuzzleMemoryStorage object by calling Kuzzle.memoryStorage
 */
var memoryStorage = kuzzle.memoryStorage;
// using the static instance
KuzzleMemoryStorage memoryStorage = kuzzle.memoryStorage;

// or instanciating a new KuzzleMemoryStorage object
KuzzleMemoryStorage memoryStorage = new KuzzleMemoryStorage(kuzzle);
<?php

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

$kuzzle = new Kuzzle('localhost');

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

// or instanciating 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
KuzzleMemoryStorage memoryStorage = kuzzle.memoryStorage;

memoryStorage.setListener(new KuzzleResponseListener<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) {
  // error occured
}

KuzzleSecurity

The KuzzleSecurity component lets you handle the permissions in Kuzzle.

Kuzzle defines the permissions by attaching a profile to each user.

A profile is defined as a set of roles.
Each role defines some permissions on Kuzzle’s indexes, collections, controllers and actions.

Within a profile, the role permissions are cumulative. If one of the profile role allows to execute the action, all the users attached to this profile will be allowed to execute the action.

Within a role, the permissions can be defined and overriden. The precedence order is defined as the most specific rule overrides the less specific rule.

Constructors

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

// or instanciating a new KuzzleSecurity object
KuzzleSecurity security = new KuzzleSecurity(kuzzle);
// using the static instance
KuzzleSecurity* security = kuzzle.security;

// or instanciating a new KuzzleSecurity object
KuzzleSecurity* security = [[KuzzleSecurity alloc] initWithKuzzle: kuzzle];
// using the static instance
let security = kuzzle.security

// or instanciating a new KuzzleSecurity object
let security = KuzzleSecurity(kuzzle: kuzzle)
<?php

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

$kuzzle = new Kuzzle('localhost');

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

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

KuzzleSecurity(Kuzzle)

Arguments Type Description
Kuzzle object An instanciated 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 KuzzleRole object
  });

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

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

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

    @Override
    public void onError(JSONObject error) {

    }
  })
NSDictionary* roleDefinition = @{
  @"controllers": @{
    @"*": @{
      @"actions": @{
        @"*": @true
      }
    }
  }
};

NSError* error = nil;
KuzzleOptions* opts = [[KuzzleOptions alloc] init];
opts.replaceIfExist = true;

[kuzzle.security createRoleWithId: @"myRole" content: roleDefinition options:opts error: &error callback:^(KuzzleRole * createdRole, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let roleDefinition = [
  "controllers": [
    "*": [
      "actions": [
        "*": true
      ]
    ]
  ]
]

do {
  let opts = KuzzleOptions()
  opts.setReplaceIfExist(true)
  try kuzzle.security.createRole(id: "myRole", content: roleDefinition, options: opts, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 occured
}

Create a new role in Kuzzle.

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

Arguments Type Description
id string Unique role identifier
content JSON Object A plain javascript 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 KuzzleRole 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 KuzzleProfile object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createProfilePromise('myprofile', profileDefinition, options)
  .then((response) => {
    // result is a KuzzleProfile 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)
  );

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

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

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSArray* profileDefinition = @{
  @"policies": @[
    @{"roleId": @"myrole"},
    @{"roleId": @"default", "restrictedTo": @[@{"index": @"index1"}]}
  ],
};

NSError* error = nil;
KuzzleOptions* opts = [[KuzzleOptions alloc] init];
opts.replaceIfExist = true;

[kuzzle.security createProfileWithId: @"myprofile" content: profileDefinition options:opts error: &error callback:^(KuzzleProfile * createdProfile, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let profileDefinition = {
  "policies": [
    {"roleId": 'myrole'},
    {"roleId": 'default', "restrictedTo": [{"index": 'index1'}, {"index": 'index2', "collections": ["foo", "bar"] } ] }
  ]
}

do {
  let opts = KuzzleOptions()
  opts.setReplaceIfExist(true)
  try kuzzle.security.createProfile(id: "myprofile", content: profileDefinition, options: opts, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

Create a new profile in Kuzzle.

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

Arguments Type Description
id string Unique profile identifier
content JSON Object A plain javascript 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 KuzzleProfile 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 KuzzleUser object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createUserPromise('myuser', userContent, options)
  .then((response) => {
    // result is a KuzzleUser 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");

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

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

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSDictionary* newUser = @{
  @"profileIds": @[@"admin"],
  @"password": @"secret password",
  @"firstname": @"John",
  @"lastname": @"Doe"
};

NSError* error = nil;
KuzzleOptions* opts = [[KuzzleOptions alloc] init];
opts.replaceIfExist = true;

[kuzzle.security createUserWithId: @"myRole" content: newUser options:opts error: &error callback:^(KuzzleUser * createdUser, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let newUser = [
  "profileIds": ["admin"],
  "password": "secret password",
  "firstname": "John",
  "lastname": "Doe"
]

do {
  let opts = KuzzleOptions()
  opts.setReplaceIfExist(true)
  try kuzzle.security.createUser(id: "newUser", content: newUser, options: opts, callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

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 javascript 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 KuzzleUser 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 KuzzleUser object
  });

// Using promises (NodeJS)
kuzzle
  .security
  .createRestrictedUserPromise('myuser', userContent, options)
  .then((response) => {
    // result is a KuzzleUser 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");

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

kuzzle
  .security
  .createRestrictedUser("myNewUser", newUser, opts, new KuzzleResponseListener<KuzzleUser>() {
    @Override
    public void onSuccess(KuzzleUser 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) {
  // error occured
}

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 javascript 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 KuzzleUser 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 KuzzleResponseListener<String>() {
    @Override
    public void onSuccess(String profileName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[kuzzle.security deleteProfileWithId: @"myprofile" error:&error callback:^(NSString * deletedprofileIds, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.deleteProfile(id: "myprofile", callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

$profileId = 'myProfile';

$kuzzle = new Kuzzle('localhost');

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

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 KuzzleSecurity 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 KuzzleResponseListener<String>() {
    @Override
    public void onSuccess(String roleName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[kuzzle.security deleteRoleWithId: @"myrole" error:&error callback:^(NSString * deletedRoleId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.deleteRole(id: "myrole", callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

$roleId = 'myRole';

$kuzzle = new Kuzzle('localhost');

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

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 KuzzleSecurity 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 KuzzleResponseListener<String>() {
    @Override
    public void onSuccess(String userName) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[kuzzle.security deleteUserWithId: @"myuser" error:&error callback:^(NSString * deletedUserId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.deleteUser(id: "myuser", callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use \Kuzzle\Kuzzle;

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

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

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 KuzzleSecurity object to allow chaining.

Callback response

Resolves the user id which has been deleted.

getRole

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

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

kuzzle
  .security
  .getRole("myrole", new KuzzleResponseListener<KuzzleRole>() {
    @Override
    public void onSuccess(KuzzleRole role) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[kuzzle.security getRoleWithId: @"myrole" error: &error callback:^(KuzzleRole * role, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.getRole(id: "myrole", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

$roleId = 'myRole';

$kuzzle = new Kuzzle('localhost');

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

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

Retrieves a single stored role using its unique ID.

getRole(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 KuzzleRole object.

getProfile

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

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

kuzzle
  .security
  .getProfile("myprofile", new KuzzleResponseListener<KuzzleProfile>() {
    @Override
    public void onSuccess(KuzzleProfile profile) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;

[kuzzle.security getProfileWithId: @"myprofile" error: &error callback:^(KuzzleProfile * profile, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.getProfile(id: "myprofile", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

$profileId = 'myProfile';

$kuzzle = new Kuzzle('localhost');

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

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

Retrieves a single stored profile using its unique ID.

getProfile(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 KuzzleProfile object.

getUser

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

// Using promises (NodeJS)
kuzzle
  .security
  .getUserPromise('myuser')
  .then((result) => {
    // result is a KuzzleUser object
  })
kuzzle
  .security
  .getUser("myuser", new KuzzleResponseListener<KuzzleUser>() {
    @Override
    public void onSuccess(KuzzleUser user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[kuzzle.security getUserWithId: @"myuser" error: &error callback:^(KuzzleUser * user, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try kuzzle.security.getUser(id: "myuser", callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

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

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

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

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

Retrieves a single stored user using its unique ID.

getUser(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 KuzzleUser 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 KuzzleResponseListener<JSONObject>() {
    @Override
    public void onSuccess(JSONObject rights) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
// Not implemented yet
kuzzle
  .security
  .getUserRights("id", { (response) in
    switch response {
      case let .onSuccess(rights):
        // rights is a JsonObject containing rights
      case let .onError(error):
        // handle the error here
    }
  });
<?php

use \Kuzzle\Kuzzle;

$userId = 'myUser';

$kuzzle = new Kuzzle('localhost');

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

}
catch (ErrorException $e) {
  // error occured
}

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 KuzzleResponseListener<JSONArray>() {
    @Override
    public void onSuccess(JSONArray rights) {
        KuzzleRights rights = kuzzle.security.isActionAllowed(rights, "read", "get", "index1", "collection1");
    }

    @Override
    public void onError(JSONObject error) {
     // ...
    }
});
// Not implemented yet
// Not implemented yet
<?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) {
  // error occured
}

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

profileFactory

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

var profile = kuzzle.security.profileFactory('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)
  );

KuzzleProfile profile = kuzzle.security.profileFactory("myprofile", profileDefinition);
NSDictionary* profileDefinition = @{
  @"policies": @[
    @{"roleId": @"myrole"},
    @{"roleId": @"default", "restrictedTo": @[@{"index": @"index1"}]}
  ],
};

KuzzleProfile* profile = [kuzzle.security profileFactoryWithId: @"myprofile" content: profileDefinition];
let profileDefinition = {
  "policies": [
    {"roleId": 'myrole'},
    {"roleId": 'default', "restrictedTo": [{"index": 'index1'}, {"index": 'index2', "collections": ["foo", "bar"] } ] }
  ]
}

let profile = kuzzle.security.profileFactory(id: "myprofile", content: 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->profileFactory($profileId, $profileDefinition);

// $profile instanceof Profile

Instantiate a new KuzzleProfile object.

profileFactory(id, content)

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

Return value

Returns the KuzzleProfile object.

roleFactory

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

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

KuzzleRole role = kuzzle.security.roleFactory("myrole", roleDefinition);
NSDictionary* roleDefinition = @{
  @"controllers": @{
    @"*": @{
      @"actions": @{
        @"*": @true
      }
    }
  }
};

KuzzleRole* role = [kuzzle.security roleFactoryWithId: @"myrole" content: roleDefinition];
let roleDefinition = [
  "controllers": [
    "*": [
      "actions": [
        "*": true
      ]
    ]
  ]
]

let role = kuzzle.security.roleFactory(id: "myrole", content: roleDefinition)
<?php

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

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

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

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

// $role instanceof Role

Instantiate a new KuzzleRole object.

roleFactory(id, content)

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

Return value

Returns the KuzzleRole 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 KuzzleResponseListener<KuzzleSecurityDocumentList>() {
    @Override
    public void onSuccess(KuzzleSecurityDocumentList profiles) {
      // Contains a profiles list
      for(KuzzleProfile profile : profiles.getDocuments()) {

      }

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

    @Override
    public void onError(JSONObject error) {

    }
  });

NSError* error = nil;
NSDictionary* filters = @{
  @"policies": @[
    @"myrole",
    @"admin"
  ],
  @"from": @0,
  @"size": @10
};

[kuzzle.security searchProfilesWithFilters: filters error: &error callback:^(NSArray<KuzzleProfile *> * profiles, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let filters = [
      "policies": [
          "myrole",
          "admin"
      ],
      "from": 0,
      "size": 1
  ]
  try kuzzle.security.searchProfiles(filters: filters, callback: {result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is array with KuzzleProfile objects
      break
    }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

Callback response:

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

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 KuzzleResponseListener<KuzzleSecurityDocumentList>() {
    @Override
    public void onSuccess(KuzzleSecurityDocumentList users) {
      // users.getDocuments() returns an users list
      for(KuzzleUser user : users.getDocuments()) {

      }

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

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
NSDictionary* filters = @{
  @"filter": @{
    @"and": @[
      @{
        @"terms": @{
          @"profileIds": @[
            @"anonymous",
            @"default"
          ]
        }
      },
      @{
        @"geo_distance": @{
          @"distance": @"10km",
            @"pos": @{
             @"lat": @"54.4838902",
             @"lon": @"17.01559"
            }
          }
        }
      ]
    }
};

[kuzzle.security searchUsersWithFilters: filters error: &error callback:^(NSArray<KuzzleUser *> * users, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let filters = [
    "filter": [
      "and": [
        [
          "terms": [
            "profileIds": [
              "anonymous",
              "default"
            ]
          ]
        ],
        [
          "geo_distance": [
            "distance": "10km",
            "pos": [
              "lat": "54.4838902",
              "lon": "17.01559"
            ]
          ]
        ]
      ]
    ]
  ]

  try kuzzle.security.searchUsers(filters: filters, callback: {result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is array with KuzzleUser objects
      break
    }
})
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

Callback response:

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

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 KuzzleResponseListener<KuzzleSecurityDocumentList>() {
    @Override
    public void onSuccess(KuzzleSecurityDocumentList roles) {
      // roles.getDocuments() returns a roles list
      for(KuzzleRole role : roles.getDocuments()) {

      }

      // roles.getTotal() returns the number of matched roles, regardless of pagination
      roles.getTotal();
    }
  });
NSError* error = nil;
NSDictionary* filters = @{
  @"controllers": @[
    @"read",
    @"write"
  ],
  @"from": @0,
  @"size": @10
};

[kuzzle.security searchRolesWithFilters: filters error: &error callback:^(NSArray<KuzzleRole *> * roles, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let filters = [
      "controllers": [
          "read",
          "write"
      ],
      "from": 0,
      "size": 1
  ]
  try kuzzle.security.searchRoles(filters: filters, allback: {result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is array with KuzzleRole objects
      break
    }
})
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

Callback response:

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

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 KuzzleResponseListener<KuzzleProfile>() {
    @Override
    public void onSuccess(KuzzleProfile profile) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSDictionary* profileDefinition = @{
  @"policies": @[
    @{"roleId": @"myrole"},
    @{"roleId": @"default", "restrictedTo": @[@{"index": @"index1"}]}
  ],
};

NSError* error = nil;
[kuzzle.security updateProfileWithId: @"profileId" content: profileDefinition error: &error callback:^(KuzzleProfile * updatedProfile, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let profileDefinition = [
    "policies": [
      {"roleId": 'myrole'},
      {"roleId": 'default', "restrictedTo": [{"index": 'index1'}, {"index": 'index2', "collections": ["foo", "bar"] } ] }
    ]
  ]
  try kuzzle.security.updateProfile(id: "profileId", content: profileDefinition, callback: { result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is updated KuzzleProfile object
      break
    }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

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 javascript 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 KuzzleSecurity object to allow chaining.

Callback response

Resolves to an updated KuzzleProfile 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 KuzzleResponseListener<KuzzleRole>() {
    @Override
    public void onSuccess(KuzzleRole role) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSDictionary* roleDefinition = @{
  @"controllers": @{
    @"*": @{
      @"actions": @{
        @"*": @true
      }
    }
  }
};

NSError* error = nil;
[kuzzle.security updateRoleWithId: @"roleId" content: roleDefinition error: &error callback:^(KuzzleRole * updatedRole, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let roleDefinition = [
  "controllers": [
    "*": [
      "actions": [
        "*": true
      ]
    ]
  ]
]

do {
  try kuzzle.security.updateRole(id: "roleId", content: newContent, callback: { result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is updated KuzzleRole object
      break
    }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

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 javascript 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 KuzzleSecurity object to allow chaining.

Callback response

Resolves to an updated KuzzleRole 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 KuzzleResponseListener<KuzzleUser>() {
    @Override
    public void onSuccess(KuzzleUser user) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSDictionary* newContent = @{
  @"firstname": @"My Name Is",
  @"lastname": @"Jonas"
};

NSError* error = nil;
[kuzzle.security updateUserWithId: @"userId" content: newContent error: &error callback:^(KuzzleUser * updatedUser, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  let newContent = [
    "firstname": "My Name Is",
    "lastname": "Jonas"
  ]
  try kuzzle.security.updateUser(id: "userId", content: newContent, callback: { result in
    switch result {
      case let .onError(error):
      // error occured during call, error is NSError
      break
      case let .onSuccess(success):
      // everything went fine, success is updated KuzzleUser object
      break
    }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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) {
  // error occured
}

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 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 KuzzleSecurity object to allow chaining.

Callback response

Resolves to an updated KuzzleUser object

userFactory

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.userFactory('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");

KuzzleUser user = kuzzle.security.userFactory("userId", userContent);  
NSDictionary* userContent = @{
  @"profileIds": @[@"someProfile"],
  @"password": @"a password",
  @"firstname": @"John",
  @"lastname": @"Doe"
};

KuzzleUser* user = [kuzzle.security userFactoryWithId: @"myuser" content: userContent];
let userContent = [
  "profileIds": ["someProfile"],
  "password": "a password",
  "firstname": "John",
  "lastname": "Doe"
]

let user = kuzzle.security.userFactory(id: "myuser", content: 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->userFactory($userId, $userDefinition);
// $user instanceof User

Instantiate a new KuzzleUser object.

userFactory(id, content)

Arguments Type Description
id string Unique user identifier
content JSON Object User content

Return value

Returns the KuzzleUser object.

~ KuzzleRole

KuzzleRole is the object representation of a set of right policies.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 KuzzleRole objects are returned by KuzzleSecurity.roleFactory method:
 */
var roleDefinition = {
  controllers: {
    "*": {
      actions: {
        "*": true
      }
    }
  }
};

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

KuzzleRole role = new KuzzleRole(kuzzle.security, "role ID", roleDefinition);
NSDictionary* roleDefinition = @{
  @"controllers": @{
    @"*": @{
      @"actions": @{
        @"*": @true
      }
    }
  }
};

// Using the KuzzleSecurity factory:
KuzzleRole* role = [kuzzle.security roleFactoryWithId: @"roleId" content: roleDefinition];

// Or directly with the constructor:
KuzzleRole* role = [[KuzzleRole alloc] initWithSecurity: kuzzle.security id: @"roleId" content: roleDefinition];
let roleDefinition = [
  "controllers": [
    "*": [
      "actions": [
        "*": true
      ]
    ]
  ]
]

// Using the KuzzleSecurity factory:
let role = kuzzle.security.roleFactory(id: "roleId", content: roleDefinition)

// Or directly with the constructor:
let role = KuzzleRole(security: kuzzle.security, id: "roleid", content: roleContent)
<?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->roleFactory($roleId, $roleDefinition);

// Or directly with the constructor:
$role = new Role($security, $roleId, $roleDefinition);

Instantiates a new KuzzleRole object.

KuzzleRole(KuzzleSecurity, id, content)

Arguments Type Description
KuzzleSecurity KuzzleSecurity An instanciated KuzzleSecurity 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 KuzzleRole 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 KuzzleResponseListener<String>() {
  @Override
  public void onSuccess(String deletedId) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[role deleteAndReturnError: &error callback:^(NSString * roleId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try role.delete(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\Role;

// ...

/*
 * @var $role Role
 */
try {
  $role->delete();
}
catch(ErrorException $e) {
  // error occured
}

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.

update

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

// Using callbacks (NodeJS or Web Browser)
role.update(updateContent, function(err, updatedRole) {
  // the updatedRole variable is the updated KuzzleRole object
})

// Using promises (NodeJS)
role
  .updatePromise(updateContent)
  .then(updatedRole => {
    // the updatedRole variable is the updated KuzzleRole object
  });
JSONObject roleDefinition = new JSONObject()
  .put("controllers", new JSONObject()
    .put("read", new JSONObject()
      .put("actions", new JSONObject()
        .put("get", true)
      )
    )
  )
);

role.update(roleDefinition, new KuzzleResponseListener<KuzzleRole>() {
  @Override
  public void onSuccess(KuzzleRole updatedRole) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
NSDictionary* roleDefinition = @{
  @"controllers": @{
    @"read": @{
      @"actions": @{
        @"get": @true
      }
    }
  }
};

[role updateWithContent: roleDefinition error: &error callback:^(KuzzleRole * updatedRole, NSError * onError) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let roleDefinition = [
  "controllers": [
    "read": [
      "actions": [
        "get": true
      ]
    ]
  ]
]
do {
    role.update(content: roleDefinition, callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\Role;

// ...

$roleDefinition = [
  'controllers' => [
    'read' => [
      '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 some more detailed information on the expected role definition, please refer to Kuzzle’s role reference definition documentation.

To get some more detailed information about Kuzzle’s user management model, please refer to Kuzzle’s security documentation.

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 KuzzleRole object to allow chaining.

Callback response

Resolves to the updated version of this object

save

// Using callbacks (NodeJS or Web Browser)
role
  .save(function(error, result) {
    // result is a KuzzleRole object
  });

// Using promises (NodeJS)
role
  .savePromise()
  .then((result) => {
    // result is a KuzzleRole object
  });
role.save(new KuzzleResponseListener<KuzzleRole> {
  @Override
  public void onSuccess(KuzzleRole savedRole) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[role saveAndReturnError: &error callback:^(KuzzleRole * savedRole, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try role.save(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleRole
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?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 KuzzleRole object to allow chaining.

Callback response

Resolves to a KuzzleRole 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);
NSDictionary* newContent = @{
  @"controllers": @{
    @"*": @{
      @"actions": @{
        @"*": @true
      }
    }
  }
};

[role setContentWithData: roleDefinition];
let roleDefinition = [
  "controllers": [
    "*": [
      "actions": [
        "*": true
      ]
    ]
  ]
]

role.setContent(content: roleDefinition)
<?php

use Kuzzle\Security\Role;

// ...

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

/*
 * @var $role Role
 */
$role->setContent($roleDefinition);

Replaces the content of the KuzzleRole object.

setContent(data)

Arguments Type Description
data JSON Object Role content

Return value

Returns the KuzzleRole object.

~ KuzzleProfile

KuzzleProfile is the object representation of a profile, which is a set of one or many KuzzleRole objects.

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 KuzzleProfile objects are returned by KuzzleSecurity.profileFactory method:
 */
var profileDefinition = {
  policies: [
    {roleId: 'myrole'},
    {roleId: 'default', restrictedTo: [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ] }
  ]
};

var role = kuzzle.security.profileFactory('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)
  );

KuzzleProfile profile = new KuzzleProfile(kuzzle.security, "profileId", roles);
NSDictionary* profileContent = @{
  @"policies": @[
    @{"roleId": @"myrole"},
    @{"roleId": @"default", "restrictedTo": @[@{"index": @"index1"}]}
  ],
};

// Using the KuzzleSecurity factory:
KuzzleProfile* profile = [kuzzle.security profileFactoryWithId: @"profileId" content: profileContent];

// Or directly with the constructor:
KuzzleProfile* profile = [[KuzzleProfile alloc] initWithSecurity: kuzzle.security id: @"profileId" content: profileContent];
let profileContent = [
  "policies": [
    {"roleId": 'myrole'},
    {"roleId": 'default', "restrictedTo": [{"index": 'index1'}, {"index": 'index2', "collections": ["foo", "bar"] } ] }
  ]
]

// Using the KuzzleSecurity factory:
let profile = kuzzle.security.profileFactory(id: "profileId", content: profileContent)

// Or directly with the constructor:
let profile = KuzzleProfile(security: kuzzle.security, id: "profileId", content: profileContent)
<?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->profileFactory($profileId, $profileDefinition);

// Or directly with the constructor:
$profile = new Profile($security, $profileId, $profileDefinition);

Instantiates a new KuzzleProfile object.

KuzzleProfile(KuzzleSecurity, id, content)

Arguments Type Description
KuzzleSecurity KuzzleSecurity An instanciated KuzzleSecurity 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 KuzzleProfile object.

Properties

Property name Type Description get/set
content JSON object Raw profile content get
id string Unique profile identifier get

addPolicy

// Passing a KuzzlePolicy object
var policy = profile.policyFactory({
  'roleId': 'some role id',
  'restrictedTo': [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ]
})
profile.addPolicy(policy);

// Or by passing its description
profile.addPolicy({
  'roleId': 'some role id',
  'restrictedTo': [{index: 'index1'}, {index: 'index2', collections: ['foo', 'bar'] } ]
});
KuzzlePolicy policy = new KuzzlePolicy(profile, 'some role id', )
profile.addRole("a role ID");

// you may also add a KuzzleRole object directly
profile.addRole(kuzzle.security.getRole("another role ID"));
[profile addRoleWithId: @"roleId"];

// you may also add a KuzzleRole object directly
KuzzleRole* role = [[KuzzleRole alloc] initWithSecurity: kuzzle.security id: @"roleId" content: @{}];
[profile addRoleWithRole: role];
profile.addRole(id: "roleId")

// you may also add a KuzzleRole object directly
let role = KuzzleRole(security: kuzzle.security, id: "roleId", content: ["":""])
profile.addRole(role: role)

Adds a role to the profile.

addPolicy(id)

addPolicy(policy)

Arguments Type Description
id string Unique id corresponding to the new associated role
policy KuzzlePolicy policy instance corresponding to the new associated role and its restrictions

Return value

Returns the KuzzleProfile 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 KuzzleResponseListener<String>() {
    @Override
    public void onSuccess(String deleteId) {

    }

    @Override
    public void onError(JSONObject error) {

    }
  });
NSError* error = nil;
[profile deleteAndReturnError: &error callback:^(NSString * profileId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try profile.delete(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\Profile;

// ...

/*
 * @var $profile Profile
 */
try {
  $profile->delete();
}
catch(ErrorException $e) {
  // error occured
}

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 deleted profile.

getPolicies

for (policy of profile.getPolicies()) {
  // policy is a KuzzlePolicy object
}
for(KuzzlePolicy policy : profile.getPolicies()) {
  // policy is a KuzzlePolicy object
}
for (KuzzlePolicy* policy in [profile getPolicies]) {
  // policy is a KuzzlePolicy object
}
for policy in profile.getPolicies() {
  // policy is a KuzzlePolicy 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

update

var updateContent = {
  policies: [
    {roleId: 'myrole'},
  ]
};

// Using callbacks (NodeJS or Web Browser)
profile.update(updateContent, function(err, updatedProfile) {
  // the updatedProfile variable is the updated KuzzleProfile object
})

// Using promises (NodeJS)
role
  .updatePromise(updateContent)
  .then(updatedProfile => {
    // the updatedProfile variable is the updated KuzzleProfile object
  });
JSONObject policy1 = new JSONObject()
  .put("roleId", "myrole");

JSONObject updateContent = new JSONObject()
  .put("policies", new JSONArray()
    .put(policy1)

user.update(updateContent, new KuzzleResponseListener<KuzzleProfile>() {
  @Override
  public void onSuccess(KuzzleProfile updatedProfile) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
NSDictionary* updatedContent = @{
  @"policies": @[
    @{"roleId": @"myrole"},
  ],
};

[profile updateWithContent: updatedContent error: &error callback:^(KuzzleProfile * updatedProfile, NSError * onError) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let updatedContent = [
  "policies": [
    {"roleId": 'myrole'},
  ]
]

do {
    user.update(content: updatedContent, callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}

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 KuzzleProfile object to allow chaining.

Callback response

Resolves to the updated version of this object

save

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

var profile = kuzzle.security.profileFactory('myprofile', profileDefinition);

// Using callbacks (NodeJS or Web Browser)
profile
  .save(function(error, result) {
    // result is a KuzzleProfile object
  });

// Using promises (NodeJS)
profile
  .savePromise()
  .then((result) => {
    // result is a KuzzleProfile 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)
  );

KuzzleProfile profile = kuzzle.security.profileFactory("myprofile", roles);

profile.save(new KuzzleResponseListener<KuzzleProfile>() {
  @Override
  public void onSuccess(KuzzleProfile savedProfile) {

  }

  @Overrid public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[profile saveAndReturnError: &error callback:^(KuzzleProfile * savedProfile, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try profile.save(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleProfile
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\Profile;

// ...

/*
 * @var $profile Profile
 */

try {
  $profile = $profile->save();

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

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 KuzzleProfile object to allow chaining.

Callback response

Resolves to a KuzzleProfile object.

setContent

var profile = kuzzle.security.getProfile('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);
NSDictionary* newContent = @{
  @"policies": @[
    @{"roleId": @"myrole"},
    @{"roleId": @"default", "restrictedTo": @[@{"index": @"index1"}]}
  ],
};
[profile setContentWithData: newContent];
let newContent = []
  "policies": [
    {"roleId": 'myrole'},
    {"roleId": 'default', "restrictedTo": [{"index": 'index1'}, {"index": 'index2', "collections": ["foo", "bar"] } ] }
  ]
]

profile.setContent(content: newContent)
<?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 KuzzleProfile object.

setContent(data)

Arguments Type Description
data JSON Object Profile content

Return value

Returns the KuzzleProfile object.

setPolicies

policy = profile.policyFactory({
  "roleId": "roleId"
});

// Replaces the profile policies set with the given entry.
// The entry can be an array of KuzzlePolicy objects, an array of policy definition or a mix of the two.
profile.setPolicies([policy, {'roleId': 'default'}]);
KuzzleRole
  policy1 = profile.policyFactory("role1 ID", new JSONObject()),
  policy2 = profile.policyFactory("role2 ID", new JSONObject()),
  policy3 = profile.policyFactory("role3 ID", new JSONObject());

// Binding policy objects to a profile
profile.setPolicies({policy1, policy2, policy3});

// Binding policy definition to a profile
profile.setPolicies({
  new JSONObject().put('roleId', 'role1 ID'),
  new JSONObject().put('roleId', 'role2 ID'),
  new JSONObject().put('roleId', 'role3 ID')
});
KuzzlePolicy* policy1 = [profile policyFactoryWithId: @"role1Id" content: @{}];
KuzzlePolicy* policy2 = [profile policyFactoryWithId: @"role2Id" content: @{}];
KuzzlePolicy* policy3 = [profile policyFactoryWithId: @"role3Id" content: @{}];

// Binding role objects to a profile
[profile setPoliciesWithPolicies: @[policy1, policy2, policy3]];

// Binding role IDs to a profile
[profile setPoliciesWithPoliciesDescription: @[@{"roleId": @"role1Id"}, @{"roleId": @"role2Id"}, @{"roleId": @"role3Id"}]];
let policy1 = profile.policyFactory(roleId: "role1Id", content: ["":""])
let policy2 = profile.policyFactory(roleId: "role2Id", content: ["":""])
let policy3 = profile.policyFactory(roleId: "role3Id", content: ["":""])

// Binding role objects to a profile
profile.setPolicies(withPolicies: [policy1, policy2, policy3])

// Binding role IDs to a profile
profile.setPolicies(withPoliciesDescription: [{"roleId", "role1Id"}, {"roleId", "role2Id"}, {"roleId", "role3Id"}])

Replaces the roles associated to the profile.

setPolicies(policyDescriptionArray)

setPolicies(kuzzlePolicyArray)

Arguments Type Description
policyDescriptionArray array of object Descriptions of policy to add
kuzzlePolicyArray array of KuzzlePolicy objects KuzzlePolicy objects to add

Return value

Returns the KuzzleProfile object.

~ KuzzleUser

KuzzleUser is the object representation of an user, which is associated to a KuzzleProfile

Constructors

/*
 Constructors are not exposed in the JS/Node SDK.
 KuzzleUser objects are returned by KuzzleSecurity.userFactory 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.userFactory('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:
KuzzleUser user = kuzzle.security.userFactory("user ID", userContent);

// Or directly with the constructor:
KuzzleUser user = new KuzzleUser(kuzzle.security, "user ID", userContent);
NSDictionary* userContent = @{
  @"profileIds": @[@"admin"],
  @"password": @"secret password",
  @"firstname": @"John",
  @"lastname": @"Doe"
};

// Using the KuzzleSecurity factory:
KuzzleUser* user = [kuzzle.security userFactoryWithId: @"userId" content: userContent];

// Or directly with the constructor:
KuzzleUser* user = [[KuzzleUser alloc] initWithSecurity: kuzzle.security id: @"userId" content: userContent];
let userContent = [
  "profileIds": ["admin"],
  "password": "secret password",
  "firstname": "John",
  "lastname": "Doe"
]

// Using the KuzzleSecurity factory:
let user = kuzzle.security.userFactory(id: "userId", content: userContent)

// Or directly with the constructor:
let user = KuzzleUser(security: kuzzle.security, id: "userId", content: 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->userFactory($userId, $userDefinition);

// Or directly with the constructor:
$user = new User($security, $userId, $userDefinition);

Instantiate a new KuzzleUser object.

KuzzleUser(KuzzleSecurity, id, content)

Arguments Type Description
KuzzleSecurity KuzzleSecurity An instanciated KuzzleSecurity 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 KuzzleUser object.

Properties

Property name Type Description get/set
content JSON object Raw user content get
id string Unique profile identifier get

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 KuzzleResponseListener<String>() {
  @Override
  public void onSuccess(String deletedId) {

  }

  @Override public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[user deleteAndReturnError: &error callback:^(NSString * userId, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try user.delete(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is string with id of deleted KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->delete();
}
catch (ErrorException $e) {
  // error occured
}

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 KuzzleProfile object otherwise
}
for(KuzzleProfile profile : user.getProfiles()) {
  // if this object has not been hydrated, the profile object has no content
}
for (KuzzleProfile* profile in [user getProfiles]) {
  // if this object has not been hydrated, the profile object has no content
}
for profile in 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

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 KuzzleUser object
})

// Using promises (NodeJS)
role
  .updatePromise(updateContent)
  .then(updatedUser => {
    // the updatedUser variable is the updated KuzzleUser object
  });
JSONObject updateContent = new JSONObject()
  .put("firstname", "My Name Is")
  .put("lastname", "Jonas");

user.update(updateContent, new KuzzleResponseListener<KuzzleUser>() {
  @Override
  public void onSuccess(KuzzleUser updatedUser) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
NSDictionary* updatedContent = @{
                                 @"firstname": @"My Name Is",
                                 @"lastname": @"Jonas"
                                 };
[user updateWithContent: updatedContent error: &error callback:^(KuzzleUser * updatedUser, NSError * onError) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
let updatedContent = [
    "firstname": "My Name Is",
    "lastname": "Jonas"
]
do {
    user.update(content: updatedContent, callback: {result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

$userContent = [
  'firstname' => 'My Name Is',
  'lastname' => 'Jonas'
];

try {
  $user->update($userContent);
}
catch (ErrorException $e) {
  // error occured
}

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 KuzzleUser object to allow chaining.

Callback response

Resolves to the updated version of this object

save

// Using callbacks (NodeJS or Web Browser)
user
  .save(function(error, result) {
    // result is a KuzzleUser object
  });

// Using promises (NodeJS)
user
  .savePromise()
  .then((result) => {
    // result is a KuzzleUser object
  });
user.save(new KuzzleResponseListener<KuzzleUser>() {
  @Override
  public void onSuccess(KuzzleUser user) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
NSError* error = nil;
[user saveAndReturnError: &error callback:^(KuzzleUser * savedUser, NSError * error) {
  if(error) {
    // error occured
  }
  // everything went fine
}];

if(error) {
  // NSError reprsentation for KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
do {
  try user.save(callback: { result in
      switch result {
        case let .onError(error):
        // error occured during call, error is NSError
        break
        case let .onSuccess(success):
        // everything went fine, success is KuzzleUser
        break
      }
  })
} catch {
  // KuzzleError.IllegalState, when Kuzzle state is .DISCONNECTED
}
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->save();
}
catch (ErrorException $e) {
  // error occured
}

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 KuzzleUser object to allow chaining.

Callback response

Resolves to a KuzzleUser object.

saveRestricted

// Using callbacks (NodeJS or Web Browser)
user
  .saveRestricted(function(error, result) {
    // result is a KuzzleUser object
  });

// Using promises (NodeJS)
user
  .saveRestrictedPromise()
  .then((result) => {
    // result is a KuzzleUser object
  });
user.saveRestricted(new KuzzleResponseListener<KuzzleUser>() {
  @Override
  public void onSuccess(KuzzleUser user) {

  }

  @Override
  public void onError(JSONObject error) {

  }
});
<?php

use Kuzzle\Security\User;

// ...

/*
 * @var $user User
 */

try {
  $user->saveRestricted();
}
catch (ErrorException $e) {
  // error occured
}

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 KuzzleUser object to allow chaining.

Callback response

Resolves to a KuzzleUser object.

setContent

var user = kuzzle.security.getUser('myuser');
var userContent = {
  profileIds: ['profileId']
};

user = user.setContent(userContent);
JSONObject newContent = new JSONObject()
  .put("profileIds", new JSONArray()
    .put("profileId")
  );

user.setContent(newContent);
NSDictionary* newContent = @{
  @"profileIds": @[
    @"profileId"
  ]
};
[user setContentWithData: newContent];
let newContent = [
  "profileIds": [
    "profileId"
  ]
]

user.setContent(content: newContent)
<?php

use Kuzzle\Security\User;

// ...

$userContent = [
  'profileIds' => ['profileId']
];

/*
 * @var $user User
 */
$user->setContent($userContent);

Replaces the content of KuzzleUser

setContent(data)

Arguments Type Description
data JSON Object User content

Return value

Returns the KuzzleUser object.

setProfiles

var profile = kuzzle.security.getProfile('myprofile', function(error, profile) {
  // Can set the profiles directly with a KuzzleProfile object
  user.setProfiles([profile]);
});

// Or by passing their ids
user.setProfiles(['myprofile']);

// Updating the profile with a KuzzleProfile object
kuzzle
  .security
  .getProfile("myprofile", opts, new KuzzleResponseListener<KuzzleProfile>() {
    @Override
    public void onSuccess(KuzzleProfile profile) {

      ArrayList<KuzzleProfile> profileIds = new ArrayList<KuzzleProfile>();
      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);
// Updating the profile with a KuzzleProfile object
[kuzzle.security getProfileWithId: @"myprofile" options: opts error: &error callback:^(KuzzleProfile * profile, NSError * error) {

  [user setProfilesWithProfile: @[profile]];

}];

// Updating the profile with a profile ID
[user setProfilesWithId: @[@"profileId"]];

do {
  try kuzzle.security.getProfile(id: "myprofile", callback: { result in
      switch result {
        case let .onSuccess(profile):

        user.setProfiles(withProfiles: [profile])

        break
      }
  })
} catch {
  // error occured
}

// Updating the profile with a profile ID
user.setProfiles(withIds: ["profileId"])
<?php

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

// ...

$profile = $kuzzle->security->getProfile('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(kuzzleProfile)

Arguments Type Description
profileIds array List of profile ID
kuzzleProfile array An array of instanciated KuzzleProfile object

Return value

Returns the KuzzleUser object.

addProfile

var profile = kuzzle.security.getProfile('myprofile', function(error, profile) {
  // Can add a profile directly with a KuzzleProfile object
  user.addProfile(profile);
});

// Or by passing an id
user.addProfile('myprofile');

// Updating the profile with a KuzzleProfile object
kuzzle
  .security
  .getProfile("myprofile", opts, new KuzzleResponseListener<KuzzleProfile>() {
    @Override
    public void onSuccess(KuzzleProfile profile) {
      // Can add the profile directly with a KuzzleProfile object
      user.addProfile(profile);
    }
  });

// Updating the profile with a profile ID
user.addProfile("myprofile");
// Updating the profile with a KuzzleProfile object
[kuzzle.security getProfileWithId: @"myprofile" options: opts error: &error callback:^(KuzzleProfile * profile, NSError * error) {

  [user addProfileWithProfile: profile];

}];

// Updating the profile with a profile ID
[user addProfileWithId: @"profileId"];

do {
  try kuzzle.security.getProfile(id: "myprofile", callback: { result in
      switch result {
        case let .onSuccess(profile):

        user.addProfile(withProfile: profile)

        break
      }
  })
} catch {
  // error occured
}

// Updating the profile with a profile ID
user.addProfile(withIds: "profileId")
<?php

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

// ...

$profile = $kuzzle->security->getProfile('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(kuzzleProfile)

Arguments Type Description
profileId string Profile ID
kuzzleProfile kuzzleProfile An instanciated KuzzleProfile object

Return value

Returns the KuzzleUser object.