Aerospike
class Aerospike (View source)
The Aerospike client class
The Aerospike config options for php.ini
:
// The connection timeout in milliseconds.
aerospike.connect_timeout = 1000;
// The read operation timeout in milliseconds.
aerospike.read_timeout = 1000;
// The write operation timeout in milliseconds.
aerospike.write_timeout = 1000;
// Whether to send and store the record's (ns,set,key) data along with
// its (unique identifier) digest. 0: digest, 1: send
aerospike.key_policy = 0; // only digest
// The unsupported type handler. 0: none, 1: PHP, 2: user-defined
aerospike.serializer = 1; // php serializer
// Path to the user-defined Lua function modules.
aerospike.udf.lua_user_path = /usr/local/aerospike/usr-lua;
// Indicates if shared memory should be used for cluster tending.
// Recommended for multi-process cases such as FPM. { true, false }
aerospike.shm.use = false;
// Explicitly sets the shm key for this client to store shared-memory
// cluster tending results in.
aerospike.shm.key = 0xA8000000; // integer value
// Shared memory maximum number of server nodes allowed. Leave a cushion so
// new nodes can be added without needing a client restart.
aerospike.shm.max_nodes = 16;
// Shared memory maximum number of namespaces allowed. Leave a cushion for
// new namespaces.
aerospike.shm.max_namespaces = 8;
// Take over shared memory cluster tending if the cluster hasn't been tended
// by this threshold in seconds.
aerospike.shm.takeover_threshold_sec = 30;
// Control the batch protocol. 0: batch-index, 1: batch-direct
aerospike.use_batch_direct = 0;
// The client will compress records larger than this value in bytes for transport.
aerospike.compression_threshold = 0;
// Max size of the synchronous connection pool for each server node
aerospike.max_threads = 300;
// Number of threads stored in underlying thread pool that is used in
// batch/scan/query commands. In ZTS builds, this is always 0.
aerospike.thread_pool_size = 16;
// When turning on the optional logging in the client, this is the path to the log file.
aerospike.log_path = NULL;
aerospike.log_level = NULL;
aerospike.nesting_depth = 3;
// session handler
session.save_handler = aerospike; // to use the Aerospike session handler
session.gc_maxlifetime = 1440; // the TTL of the record used to store the session in seconds
session.save_path = NULL; // should follow the format ns|set|addr:port[,addr:port[,...]]. Ex: "test|sess|127.0.0.1:3000". The host info of just one cluster node is necessary
Constants
OPT_READ_DEFAULT_POL |
|
OPT_WRITE_DEFAULT_POL |
|
OPT_REMOVE_DEFAULT_POL |
|
OPT_BATCH_DEFAULT_POL |
|
OPT_OPERATE_DEFAULT_POL |
|
OPT_QUERY_DEFAULT_POL |
|
OPT_SCAN_DEFAULT_POL |
|
OPT_APPLY_DEFAULT_POL |
|
OPT_TLS_CONFIG |
|
OPT_TLS_ENABLE |
|
OPT_OPT_TLS_CAFILE |
|
OPT_TLS_CAPATH |
|
OPT_TLS_PROTOCOLS |
|
OPT_TLS_CIPHER_SUITE |
|
OPT_TLS_CRL_CHECK |
|
OPT_TLS_CRL_CHECK_ALL |
|
OPT_TLS_CERT_BLACKLIST |
|
OPT_TLS_LOG_SESSION_INFO |
|
OPT_TLS_KEYFILE |
|
OPT_TLS_CERTFILE |
|
OPT_CONNECT_TIMEOUT |
Defines the length of time (in milliseconds) the client waits on establishing a connection. value in milliseconds (default: 1000) |
OPT_READ_TIMEOUT |
Defines the length of time (in milliseconds) the client waits on a read
operation. value in milliseconds (default: 1000) |
OPT_WRITE_TIMEOUT |
Defines the length of time (in milliseconds) the client waits on a write
operation. value in milliseconds (default: 1000) |
OPT_TTL |
Sets the TTL of the record along with a write operation.
|
OPT_POLICY_KEY |
Accepts one of the POLICYKEY* values. https://www.aerospike.com/docs/client/php/usage/kvs/record-structure.html Records are uniquely identified by their digest, and can optionally store the value of their primary key (their unique ID in the application). Key storage policy option (digest-only or send key) |
POLICY_KEY_DIGEST |
Do not store the primary key with the record (default)
digest only |
POLICY_KEY_SEND |
Store the primary key with the record
store the primary key with the record |
OPT_POLICY_EXISTS |
Accepts one of the POLICYEXISTS* values. By default writes will try to create a record or update its bins, which is a behavior similar to how arrays work in PHP. Setting a write with a different POLICY_EXISTS_* value can simulate a more DML-like behavior, similar to an RDBMS. existence policy option |
POLICY_EXISTS_IGNORE |
"CREATE_OR_UPDATE" behavior. Create the record if it does not exist,
or update its bins if it does. (default)
create or update behavior |
POLICY_EXISTS_CREATE |
Create a record ONLY if it DOES NOT exist. create only behavior (fail otherwise) |
POLICY_EXISTS_UPDATE |
Update a record ONLY if it exists. update only behavior (fail otherwise) |
POLICY_EXISTS_REPLACE |
Replace a record ONLY if it exists. replace only behavior (fail otherwise) |
POLICY_EXISTS_CREATE_OR_REPLACE |
Create the record if it does not exist, or replace its bins if it does. create or replace behavior |
OPT_POLICY_GEN |
Set to an array( Aerospike::POLICYGEN* [, (int) $gen_value ] ) Specifies the behavior of write opertions with regards to the record's generation. Used to implement a check-and-set (CAS) pattern. generation policy option |
POLICY_GEN_IGNORE |
Do not consider generation for the write operation. write a record, regardless of generation (default) |
POLICY_GEN_EQ |
Only write if the record was not modified since a given generation value. write a record, ONLY if generations are equal |
POLICY_GEN_GT |
write a record, ONLY if local generation is greater-than remote generation |
OPT_SERIALIZER |
Set to one of the SERIALIZER_* values. Supported types, such as string, integer, and array get directly cast to the matching Aerospike types, such as as_string, as_integer, and as_map. Unsupported types, such as boolean, need a serializer to handle them. determines a handler for unsupported data types |
SERIALIZER_NONE |
Throw an exception instead of serializing unsupported types. throw an error when serialization is required |
SERIALIZER_PHP |
Use the built-in PHP serializer for any unsupported types. use the PHP serialize/unserialize functions (default) |
SERIALIZER_USER |
Use a user-defined serializer for any unsupported types. use a pair of functions written in PHP for serialization |
OPT_POLICY_COMMIT_LEVEL |
Accepts one of the POLICY_COMMITLEVEL* values. One of the https://www.aerospike.com/docs/architecture/consistency.html per-transaction consistency levels. Specifies the number of replicas required to be successfully committed before returning success in a write operation to provide the desired consistency level. commit level policy option |
POLICY_COMMIT_LEVEL_ALL |
Return succcess only after successfully committing all replicas. write to the master and all replicas (default) |
POLICY_COMMIT_LEVEL_MASTER |
Return succcess after successfully committing the master replica. master will asynchronously write to replicas |
OPT_POLICY_REPLICA |
Accepts one of the POLICYREPLICA* values. One of the https://www.aerospike.com/docs/architecture/consistency.html per-transaction consistency levels. Specifies which partition replica to read from. replica policy option |
POLICY_REPLICA_MASTER |
Read from the partition master replica node. read from master |
POLICY_REPLICA_ANY |
Read from an unspecified replica node. read from any replica node |
POLICY_REPLICA_SEQUENCE |
Always try node containing master partition first. If connection fails and
Currently restricted to master and one replica. (default) attempt to read from master first, then try the node containing replica partition if connection failed. (default) |
POLICY_REPLICA_PREFER_RACK |
Try node on the same rack as the client first. If there are no nodes on the
same rack, use POLICY_REPLICA_SEQUENCE instead. "rack_aware" must be set to true in the client constructor, and "rack_id" must match the server rack configuration to enable this functionality. attemp to read from master first, then try the node containing replica partition if connection failed. (default) |
OPT_POLICY_READ_MODE_AP |
Accepts one of the POLICY_READ_MODEAP* values. One of the https://www.aerospike.com/docs/architecture/consistency.html per-transaction consistency levels. Specifies the number of replicas to be consulted in a read operation to provide the desired consistency level in availability mode. policy read option for availability namespaces |
POLICY_READ_MODE_AP_ONE |
Involve a single replica in the operation. (default) |
AS_POLICY_READ_MODE_AP_ALL |
Involve all replicas in the operation. |
OPT_POLICY_READ_MODE_SC |
Accepts one of the POLICY_READ_MODESC* values. One of the https://www.aerospike.com/docs/architecture/consistency.html per-transaction consistency levels. Specifies the number of replicas to be consulted in a read operation to provide the desired consistency level. policy read option for consistency namespaces |
POLICY_READ_MODE_SC_SESSION |
Always read from master. Record versions are local to session. (default) |
POLICY_READ_MODE_SC_LINEARIZE |
Always read from master. Record versions are global and thus serialized. |
POLICY_READ_MODE_SC_ALLOW_REPLICA |
Read from master or fully migrated replica. Record versions may not always increase. |
POLICY_READ_MODE_SC_ALLOW_UNAVAILABLE |
Read from master or fully migrated replica. Unavailable partitions are allowed. Record versions may not always increase. |
OPT_DESERIALIZE |
|
OPT_SLEEP_BETWEEN_RETRIES |
Milliseconds to sleep between retries. Enter zero to skip sleep. const OPT_SLEEP_BETWEEN_RETRIES |
OPT_MAX_RETRIES |
Maximum number of retries before aborting the current transaction. The initial attempt is not counted as a retry. If OPT_MAX_RETRIES is exceeded, the transaction will return error ERR_TIMEOUT. WARNING: Database writes that are not idempotent (such as "add") should not be retried because the write operation may be performed multiple times if the client timed out previous transaction attempts. It's important to use a distinct write policy for non-idempotent writes which sets OPT_MAX_RETRIES = 0; |
OPT_TOTAL_TIMEOUT |
Total transaction timeout in milliseconds. The OPT_TOTAL_TIMEOUT is tracked on the client and sent to the server along with the transaction in the wire protocol. The client will most likely timeout first, but the server also has the capability to timeout the transaction. If OPT_TOTAL_TIMEOUT is not zero and OPT_TOTAL_TIMEOUT is reached before the transaction completes, the transaction will return error ERR_TIMEOUT. If OPT_TOTAL_TIMEOUT is zero, there will be no total time limit. |
OPT_SOCKET_TIMEOUT |
Socket idle timeout in milliseconds when processing a database command. If OPT_SOCKET_TIMEOUT is not zero and the socket has been idle for at least OPT_SOCKET_TIMEOUT, both OPT_MAX_RETRIES and OPT_TOTAL_TIMEOUT are checked. If OPT_MAX_RETRIES and OPT_TOTAL_TIMEOUT are not exceeded, the transaction is retried. If both OPT_SOCKET_TIMEOUT and OPT_TOTAL_TIMEOUT are non-zero and OPT_SOCKET_TIMEOUT > OPT_TOTAL_TIMEOUT, then OPT_SOCKET_TIMEOUT will be set to OPT_TOTAL_TIMEOUT. If OPT_SOCKET_TIMEOUT is zero, there will be no socket idle limit. |
OPT_BATCH_CONCURRENT |
Determine if batch commands to each server are run in parallel threads. |
OPT_ALLOW_INLINE |
Allow batch to be processed immediately in the server's receiving thread when the server
deems it to be appropriate. If false, the batch will always be processed in separate
transaction threads. This field is only relevant for the new batch index protocol. For batch exists or batch reads of smaller sized records (<= 1K per record), inline processing will be significantly faster on "in memory" namespaces. The server disables inline processing on disk based namespaces regardless of this policy field. Inline processing can introduce the possibility of unfairness because the server can process the entire batch before moving onto the next command. Default: true |
OPT_SEND_SET_NAME |
Send set name field to server for every key in the batch for batch index protocol. This is only necessary when authentication is enabled and security roles are defined on a per set basis. Default: false |
OPT_FAIL_ON_CLUSTER_CHANGE |
Abort the scan if the cluster is not in a stable state. Default false |
OPT_SCAN_PRIORITY |
Accepts one of the SCANPRIORITY* values. The priority of the scan |
SCAN_PRIORITY_AUTO |
The cluster will auto-adjust the priority of the scan. auto-adjust the scan priority (default) |
SCAN_PRIORITY_LOW |
Set the scan as having low priority. low priority scan |
SCAN_PRIORITY_MEDIUM |
Set the scan as having medium priority. medium priority scan |
SCAN_PRIORITY_HIGH |
Set the scan as having high priority. high priority scan |
OPT_SCAN_NOBINS |
Do not return the bins of the records matched by the scan. boolean value (default: false) |
OPT_SCAN_PERCENTAGE |
Set the scan to run over a given percentage of the possible records. integer value from 1-100 (default: 100) |
OPT_SCAN_CONCURRENTLY |
Scan all the nodes in the cluster concurrently. boolean value (default: false) |
OPT_QUERY_NOBINS |
Do not return the bins of the records matched by the query. boolean value (default: false) |
USE_BATCH_DIRECT |
Revert to the older batch-direct protocol, instead of batch-index. boolean value (default: false) |
OPT_POLICY_DURABLE_DELETE |
Set to true to enable durable delete for the operation. Durable deletes are an Enterprise Edition feature boolean value (default: false) |
OPT_MAP_ORDER |
Map policy declaring the ordering of an Aerospike map type |
AS_MAP_UNORDERED |
The Aerospike map is unordered
(default) |
AS_MAP_KEY_ORDERED |
The Aerospike map is ordered by key |
AS_MAP_KEY_VALUE_ORDERED |
The Aerospike map is ordered by key and value |
OPT_MAP_WRITE_MODE |
Map policy declaring the behavior of map write operations |
AS_MAP_UPDATE |
(default) |
AS_MAP_UPDATE_ONLY |
|
AS_MAP_CREATE_ONLY |
|
OPT_MAP_WRITE_FLAGS |
Map policy flags declaring the behavior of map write operations |
AS_MAP_WRITE_DEFAULT |
Default. Allow create or update. (default) |
AS_MAP_WRITE_CREATE_ONLY |
If the key already exists, the item will be denied. If the key does not exist, a new item will be created. |
AS_MAP_WRITE_UPDATE_ONLY |
If the key already exists, the item will be overwritten. If the key does not exist, the item will be denied. |
AS_MAP_WRITE_NO_FAIL |
Do not raise error if a map item is denied due to write flag constraints (always succeed). |
AS_MAP_WRITE_PARTIAL |
Allow other valid map items to be committed if a map item is denied due to write flag constraints. |
MAP_RETURN_NONE |
Do not return a result for the map operation (get and remove operations) |
MAP_RETURN_INDEX |
Return in key index order |
MAP_RETURN_REVERSE_INDEX |
Return in reverse key order |
MAP_RETURN_RANK |
Return in value order |
MAP_RETURN_REVERSE_RANK |
Return in reverse value order |
MAP_RETURN_COUNT |
Return count of items selected |
MAP_RETURN_KEY |
Return key for single key read and key list for range read |
MAP_RETURN_VALUE |
Return value for single key read and value list for range read |
MAP_RETURN_KEY_VALUE |
Return key/value items
Will be of the form ['key1', 'val1', 'key2', 'val2', 'key3', 'val3] |
LOG_LEVEL_OFF |
|
LOG_LEVEL_ERROR |
|
LOG_LEVEL_WARN |
|
LOG_LEVEL_INFO |
|
LOG_LEVEL_DEBUG |
|
LOG_LEVEL_TRACE |
|
OK |
Aerospike Status Codes Each Aerospike API method invocation returns a status code from the server. The status codes map to the https://github.com/aerospike/aerospike-client-c/blob/master/src/include/aerospike/as_status.h status codes of the C client. Success |
ERR_CONNECTION |
Synchronous connection error |
ERR_TLS_ERROR |
Node invalid or could not be found |
ERR_INVALID_NODE |
Node invalid or could not be found |
ERR_NO_MORE_CONNECTIONS |
Client hit the max asynchronous connections |
ERR_ASYNC_CONNECTION |
Asynchronous connection error |
ERR_CLIENT_ABORT |
Query or scan was aborted in user's callback |
ERR_INVALID_HOST |
Host name could not be found in DNS lookup |
ERR_PARAM |
Invalid client API parameter |
ERR_CLIENT |
Generic client API usage error |
ERR_SERVER |
Generic error returned by server |
ERR_RECORD_NOT_FOUND |
No record is found with the specified namespace/set/key combination. May be returned by a read, or a write with OPT_POLICY_EXISTS set to POLICY_EXISTS_UPDATE |
ERR_RECORD_GENERATION |
Generation of record does not satisfy the OPT_POLICY_GEN write policy |
ERR_REQUEST_INVALID |
Illegal parameter sent from client. Check client parameters and verify
each is supported by current server version |
ERR_OP_NOT_APPLICABLE |
The operation cannot be applied to the current bin on the server |
ERR_RECORD_EXISTS |
Record already exists. May be returned by a write with the
OPT_POLICY_EXISTS write policy set to POLICY_EXISTS_CREATE |
ERR_BIN_EXISTS |
(future) For future write requests which specify 'BIN_CREATE_ONLY',
request failed because one of the bins in the write already exists |
ERR_CLUSTER_CHANGE |
On scan requests, the scan terminates because cluster is in migration. Only occur when client requested 'fail_on_cluster_change' policy on scan |
ERR_SERVER_FULL |
Occurs when stop_writes is true (either memory - stop-writes-pct -
or disk - min-avail-pct). Can also occur if memory cannot be allocated
anymore (but stop_writes should in general hit first). Namespace will no
longer be able to accept write requests |
ERR_TIMEOUT |
Request was not completed during the allocated time, thus aborted |
ERR_ALWAYS_FORBIDDEN |
Write request is rejected because XDR is not running. Only occur when XDR configuration xdr-stop-writes-noxdr is on |
ERR_CLUSTER |
Server is not accepting requests. Occur during single node on a quick restart to join existing cluster |
ERR_BIN_INCOMPATIBLE_TYPE |
Operation is not allowed due to data type or namespace configuration incompatibility. For example, append to a float data type, or insert a non-integer when namespace is configured as data-in-index |
ERR_RECORD_TOO_BIG |
Attempt to write a record whose size is bigger than the configured write-block-size |
ERR_RECORD_BUSY |
Too many concurrent operations (> transaction-pending-limit) on the same record. A "hot-key" situation |
ERR_SCAN_ABORTED |
Scan aborted by user on server |
ERR_UNSUPPORTED_FEATURE |
The client is trying to use a feature that does not yet exist in the
version of the server node it is talking to |
ERR_BIN_NOT_FOUND |
(future) For future write requests which specify 'REPLACE_ONLY',
request fail because specified bin name does not exist in record |
ERR_DEVICE_OVERLOAD |
Write request is rejected because one or more storage devices of the node are not keeping up |
ERR_RECORD_KEY_MISMATCH |
For update request on records which has key stored, the incoming key does not match
the existing stored key. This indicates a RIPEMD160 key collision has happend (report as a bug) |
ERR_NAMESPACE_NOT_FOUND |
Namespace in request not found on server |
ERR_BIN_NAME |
Bin name length greater than 14 characters, or maximum number of unique bin names are exceeded |
ERR_FAIL_FORBIDDEN |
Operation not allowed at this time. For writes, the set is in the middle of being deleted, or the set's stop-write is reached; For scan, too many concurrent scan jobs (> scan-max-active); For XDR-ed cluster, fail writes which are not replicated from another datacenter |
ERR_FAIL_ELEMENT_NOT_FOUND |
Target was not found for operations that requires a target to be found |
ERR_FAIL_ELEMENT_EXISTS |
Target already exist for operations that requires the target to not exist |
ERR_SECURITY_NOT_SUPPORTED |
Security functionality not supported by connected server |
ERR_SECURITY_NOT_ENABLED |
Security functionality not enabled by connected server |
ERR_SECURITY_SCHEME_NOT_SUPPORTED |
Security scheme not supported |
ERR_INVALID_COMMAND |
Unrecognized security command |
ERR_INVALID_FIELD |
Field is not valid |
ERR_ILLEGAL_STATE |
Security protocol not followed |
ERR_INVALID_USER |
No user supplied or unknown user |
ERR_USER_ALREADY_EXISTS |
User already exists |
ERR_INVALID_PASSWORD |
Password does not exists or not recognized |
ERR_EXPIRED_PASSWORD |
Expired password |
ERR_FORBIDDEN_PASSWORD |
Forbidden password (e.g. recently used) |
ERR_INVALID_CREDENTIAL |
Invalid credential or credential does not exist |
ERR_INVALID_ROLE |
No role(s) or unknown role(s) |
ERR_INVALID_PRIVILEGE |
Privilege is invalid |
ERR_NOT_AUTHENTICATED |
User must be authenticated before performing database operations |
ERR_ROLE_VIOLATION |
User does not possess the required role to perform the database operation |
ERR_ROLE_ALREADY_EXISTS |
Role already exists |
ERR_UDF |
A user defined function failed to execute |
ERR_UDF_NOT_FOUND |
The UDF does not exist |
ERR_LUA_FILE_NOT_FOUND |
The LUA file does not exist |
ERR_BATCH_DISABLED |
Batch functionality has been disabled by configuring the batch-index-thread=0 |
ERR_BATCH_MAX_REQUESTS_EXCEEDED |
Batch max requests has been exceeded |
ERR_BATCH_QUEUES_FULL |
All batch queues are full |
ERR_GEO_INVALID_GEOJSON |
GeoJSON is malformed or not supported |
ERR_INDEX_FOUND |
Secondary index already exists https://www.aerospike.com/docs/client/php/usage/kvs/record-structure.html Records are uniquely identified by their digest, and can optionally store the value of their primary key (their unique ID in the application). Key storage policy option (digest-only or send key) |
ERR_INDEX_NOT_FOUND |
Secondary index does not exist |
ERR_INDEX_OOM |
Secondary index memory space exceeded |
ERR_INDEX_NOT_READABLE |
Secondary index not available for query. Occurs when indexing creation has not finished |
ERR_INDEX |
Generic secondary index error |
ERR_INDEX_NAME_MAXLEN |
Index name maximun length exceeded |
ERR_INDEX_MAXCOUNT |
Maximum number of indicies exceeded |
ERR_QUERY_ABORTED |
Secondary index query aborted |
ERR_QUERY_QUEUE_FULL |
Secondary index queue full |
ERR_QUERY_TIMEOUT |
Secondary index query timed out on server |
ERR_QUERY |
Generic query error |
OPERATOR_WRITE |
write operator for the operate() method |
OPERATOR_READ |
read operator for the operate() method |
OPERATOR_INCR |
increment operator for the operate() method |
OPERATOR_PREPEND |
prepend operator for the operate() method |
OPERATOR_APPEND |
append operator for the operate() method |
OPERATOR_TOUCH |
touch operator for the operate() method |
OPERATOR_DELETE |
delete operator for the operate() method |
OP_LIST_APPEND |
list-append operator for the operate() method |
OP_LIST_MERGE |
list-merge operator for the operate() method |
OP_LIST_INSERT |
list-insert operator for the operate() method |
OP_LIST_INSERT_ITEMS |
list-insert-items operator for the operate() method |
OP_LIST_POP |
list-pop operator for the operate() method |
OP_LIST_POP_RANGE |
list-pop-range operator for the operate() method |
OP_LIST_REMOVE |
list-remove operator for the operate() method |
OP_LIST_REMOVE_RANGE |
list-remove-range operator for the operate() method |
OP_LIST_CLEAR |
list-clear operator for the operate() method |
OP_LIST_SET |
list-set operator for the operate() method |
OP_LIST_GET |
list-get operator for the operate() method |
OP_LIST_GET_RANGE |
list-get-range operator for the operate() method |
OP_LIST_TRIM |
list-trim operator for the operate() method |
OP_LIST_SIZE |
list-size operator for the operate() method |
OP_MAP_SIZE |
map-size operator for the operate() method |
OP_MAP_CLEAR |
map-size operator for the operate() method |
OP_MAP_SET_POLICY |
map-set-policy operator for the operate() method |
OP_MAP_GET_BY_KEY |
map-get-by-key operator for the operate() method |
OP_MAP_GET_BY_KEY_RANGE |
map-get-by-key-range operator for the operate() method |
OP_MAP_GET_BY_VALUE |
map-get-by-value operator for the operate() method |
OP_MAP_GET_BY_VALUE_RANGE |
map-get-by-value-range operator for the operate() method |
OP_MAP_GET_BY_INDEX |
map-get-by-index operator for the operate() method |
OP_MAP_GET_BY_INDEX_RANGE |
map-get-by-index-range operator for the operate() method |
OP_MAP_GET_BY_RANK |
map-get-by-rank operator for the operate() method |
OP_MAP_GET_BY_RANK_RANGE |
map-get-by-rank-range operator for the operate() method |
OP_MAP_PUT |
map-put operator for the operate() method |
OP_MAP_PUT_ITEMS |
map-put-items operator for the operate() method |
OP_MAP_INCREMENT |
map-increment operator for the operate() method |
OP_MAP_DECREMENT |
map-decrement operator for the operate() method |
OP_MAP_REMOVE_BY_KEY |
map-remove-by-key operator for the operate() method |
OP_MAP_REMOVE_BY_KEY_LIST |
map-remove-by-key-list operator for the operate() method |
OP_MAP_REMOVE_BY_KEY_RANGE |
map-remove-by-key-range key operator for the operate() method |
OP_MAP_REMOVE_BY_VALUE |
map-remove-by-value operator for the operate() method |
OP_MAP_REMOVE_BY_VALUE_RANGE |
map-remove-by-value operator for the operate() method |
OP_MAP_REMOVE_BY_VALUE_LIST |
map-remove-by-value-list operator for the operate() method |
OP_MAP_REMOVE_BY_INDEX |
map-remove-by-index operator for the operate() method |
OP_MAP_REMOVE_BY_INDEX_RANGE |
map-remove-by-index-range operator for the operate() method |
OP_MAP_REMOVE_BY_RANK |
map-remove-by-rank operator for the operate() method |
OP_MAP_REMOVE_BY_RANK_RANGE |
map-remove-by-rank-range operator for the operate() method |
OP_EQ |
predicate operator for equality check of scalar integer or string value |
OP_BETWEEN |
predicate operator matching whether an integer falls between a range of integer values |
OP_CONTAINS |
predicate operator for a whether a specific value is in an indexed list, mapkeys, or mapvalues |
OP_RANGE |
predicate operator for whether an indexed list, mapkeys, or mapvalues has an integer value within a specified range |
OP_GEOWITHINREGION |
geospatial predicate operator for points within a specified region |
OP_GEOCONTAINSPOINT |
geospatial predicate operator for regons containing a sepcified point |
SCAN_STATUS_UNDEF |
Scan status is undefined |
SCAN_STATUS_INPROGRESS |
Scan is currently running |
SCAN_STATUS_ABORTED |
Scan completed successfully |
SCAN_STATUS_COMPLETED |
Scan was aborted due to failure or the user |
JOB_STATUS_UNDEF |
Job status is undefined |
JOB_STATUS_INPROGRESS |
Job is currently running |
JOB_STATUS_COMPLETED |
Job completed successfully |
INDEX_TYPE_DEFAULT |
The bin being indexed should contain scalar values such as string or integer |
INDEX_TYPE_LIST |
The bin being indexed should contain a list |
INDEX_TYPE_MAPKEYS |
The bin being indexed should contain a map. The map keys will be indexed |
INDEX_TYPE_MAPVALUES |
The bin being indexed should contain a map. The map values will be indexed |
INDEX_STRING |
If and only if the container type matches, the value should be of type string |
INDEX_NUMERIC |
If and only if the container type matches, the value should be of type integer |
INDEX_GEO2DSPHERE |
If and only if the container type matches, the value should be GeoJSON |
UDF_TYPE_LUA |
Declare the UDF module's language to be Lua |
PRIV_READ |
Privilege to read data |
PRIV_READ_WRITE |
Privilege to read and write data |
PRIV_READ_WRITE_UDF |
Privilege to read, write and execute user-defined functions |
PRIV_USER_ADMIN |
Privilege to create and assign roles to users |
PRIV_DATA_ADMIN |
Privilege to manage indexes and UDFs, monitor and abort scan/query jobs, get server config |
PRIV_SYS_ADMIN |
Privilege to modify dynamic server configs, get config and stats, and all data admin privileges |
Methods
Construct an Aerospike client object, and connect to the cluster defined in $config.
Disconnect from the Aerospike cluster and clean up resources.
Test whether the client is connected to the cluster.
Disconnect the client from all the cluster nodes.
Reconnect the client to the cluster nodes.
Expose the shared memory key used by shared-memory cluster tending
Return the error message associated with the last operation.
Return the error code associated with the last operation.
Return an array that represents the record's key.
Return the digest of hashing the (namespace, set, primary-key) tuple with RIPEMD-160.
Write a record identified by the $key with $bins, an array of bin-name => bin-value pairs.
Read a record with a given key, and store it in $record
Get the metadata of a record with a given key, and store it in $metadata
Touch the record identified by the $key, resetting its time-to-live.
Remove the record identified by the $key.
Remove $bins from the record identified by the $key.
Remove all the records from a namespace or set
Increment the value of $bin in the record identified by the $key by an $offset.
Append a string $value to the one already in $bin, in the record identified by the $key.
Prepend a string $value to the one already in $bin, in the record identified by the $key.
Perform multiple bin operations on a record with a given key, with write operations happening before read ones.
Perform multiple bin operations on a record with a given key, with write operations happening before read ones.
Count the number of elements in a list type bin
Add a single value (of any type) to the end of a list type bin
Add several items to the end of a list type bin
Insert a single element (of any type) at a specified index of a list type bin
Insert several elements at a specified index of a list type bin
Remove and get back the element at a specified index of a list type bin Index -1 is the last item in the list, -3 is the third from last, 0 is the first in the list.
Remove and get back several elements at a specified index range of a list type bin Index -1 is the last item in the list, -3 is the third from last, 0 is the first in the list.
Remove a list element at a specified index of a list type bin
Remove several list elements at a specified index range of a list type bin
Trim the list, removing all elements not in the specified index range of a list type bin
Remove all the elements from a list type bin
Set an element at a specified index of a list type bin
Get an element from a specified index of a list type bin
Get several elements starting at a specified index from a list type bin
Read a batch of records from a list of given keys, and fill $records with the resulting indexed array
Check if a batch of records exists in the database and fill $metdata with the results
Scan a namespace or set
Query a secondary index on a namespace or set
Helper method for creating an EQUALS predicate
Helper method for creating a BETWEEN predicate
Helper method for creating an CONTAINS predicate
Helper method for creating a RANGE predicate
Helper method for creating a GEOCONTAINS point predicate
Helper method for creating a GEOCONTAINS point predicate
Helper method for creating a GEOWITHIN region predicate
Helper method for creating a GEOWITHIN circle region predicate
Get the status of a background job triggered by Aerospike::scanApply or Aerospike::queryApply
Register a UDF module with the cluster
Remove a UDF module from the cluster
List the UDF modules registered with the cluster
Get the code for a UDF module registered with the cluster
Apply a UDF to a record
Apply a UDF to each record in a scan
Apply a UDF to each record in a query
Apply a stream UDF to a scan or secondary index query
Create a secondary index on a bin of a specified set
Drop a secondary index
Send an info request to a single cluster node
Send an info request to a single cluster node
Get the addresses of the cluster nodes
Set the logging threshold of the Aerospike object
Set a handler for log events
Set a serialization handler for unsupported types
Set a deserialization handler for unsupported types
Details
__construct(array $config, bool $persistent_connection = true, array $options = [])
Construct an Aerospike client object, and connect to the cluster defined in $config.
Aerospike::isConnected() can be used to test whether the connection has succeeded. If a config or connection error has occured, Aerospike::error() and Aerospike::errorno() can be used to inspect it.
$config = [
"hosts" => [
["addr" => "localhost", "port" => 3000]
],
"shm" => []
];
// Set a default policy for write and read operations
$writeOpts = [Aerospike::OPT_POLICY_KEY => Aerospike::POLICY_KEY_SEND];
$readOpts = [Aerospike::OPT_TOTAL_TIMEOUT => 150];
$opts = [Aerospike::OPT_WRITE_DEFAULT_POL => $writeOpts, Aerospike::OPT_READ_DEFAULT_POL => $readOpts];
$client = new Aerospike($config, true, $opts);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
void
__destruct()
Disconnect from the Aerospike cluster and clean up resources.
No need to ever call this method explicilty.
bool
isConnected()
Test whether the client is connected to the cluster.
If a connection error has occured, Aerospike::error() and Aerospike::errorno() can be used to inspect it.
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
void
close()
Disconnect the client from all the cluster nodes.
This method should be explicitly called when using non-persistent connections.
void
reconnect()
Reconnect the client to the cluster nodes.
Aerospike::isConnected() can be used to test whether the re-connection succeded. If a connection error occured Aerospike::error() and Aerospike::errorno() can be used to inspect it.
$client = new Aerospike($config, false);
$client->close();
$client->reconnect();
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
int|null
shmKey()
Expose the shared memory key used by shared-memory cluster tending
If shm cluster tending is enabled, Aerospike::shmKey will return the
value of the shm key being used by the client. If it was set explicitly
under the client's shm config parameter, or through the global
aerospike.shm.key
we expect to see that value. Otherwise the implicit
value generated by the client will be returned
string
error()
Return the error message associated with the last operation.
If the operation was successful the return value should be an empty string.
$client = new Aerospike($config, false);
if (!$client->isConnected()) {
echo "{$client->error()} [{$client->errorno()}]";
exit(1);
}
On connection error would show:
Unable to connect to server [-1]
int
errorno()
Return the error code associated with the last operation.
If the operation was successful the return value should be 0 (Aerospike::OK)
array
initKey(string $ns, string $set, int|string $pk, bool $is_digest = false)
Return an array that represents the record's key.
This value can be passed as the $key arguement required by other key-value methods.
In Aerospike, a record is identified by the tuple (namespace, set, primary key), or by the digest which results from hashing this tuple through RIPEMD-160.
Initializing a key
$key = $client->initKey("test", "users", 1234);
var_dump($key);
array(3) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1234)
}
Setting a digest
$base64_encoded_digest = '7EV9CpdMSNVoWn76A9E33Iu95+M=';
$digest = base64_decode($base64_encoded_digest);
$key = $client->initKey("test", "users", $digest, true);
var_dump($key);
array(3) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["digest"]=>
string(20) "?E}
?LH?hZ~??7Ü‹???"
}
string
getKeyDigest(string $ns, string $set, int|string $pk)
Return the digest of hashing the (namespace, set, primary-key) tuple with RIPEMD-160.
The digest uniquely identifies the record in the cluster, and is used to calculate a partition ID. Using the partition ID, the client can identify the node holding the record's master partition or replica partition(s) by looking it up against the cluster's partition map.
$digest = $client->getKeyDigest("test", "users", 1);
$key = $client->initKey("test", "users", $digest, true);
var_dump($digest, $key);
string(20) "9!?@%??;???Wp?'??Ag"
array(3) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["digest"]=>
string(20) "9!?@%??;???Wp?'??Ag"
}
int
put(array $key, array $bins, int $ttl = 0, array $options = [])
Write a record identified by the $key with $bins, an array of bin-name => bin-value pairs.
By default Aerospike::put() behaves in a set-and-replace mode, similar to how new keys are added to an array, or the value of existing ones is overwritten. This behavior can be modified using the $options parameter.
Note: a binary-string which includes a null-byte will get truncated at the position of the \0 character if it is not wrapped. For more information and the workaround see 'Handling Unsupported Types'.
Example #1 Aerospike::put() default behavior example
$key = $client->initKey("test", "users", 1234);
$bins = ["email" => "[email protected]", "name" => "Hey There"];
// will ensure a record exists at the given key with the specified bins
$status = $client->put($key, $bins);
if ($status == Aerospike::OK) {
echo "Record written.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
// Updating the record
$bins = ["name" => "You There", "age" => 33];
// will update the name bin, and create a new 'age' bin
$status = $client->put($key, $bins);
if ($status == Aerospike::OK) {
echo "Record updated.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
Record written.
Record updated.
Example #2 Fail unless the put explicitly creates a new record
// This time we expect an error, due to the record already existing (assuming we
// ran Example #1)
$status = $client->put($key, $bins, 0, [Aerospike::OPT_POLICY_EXISTS => Aerospike::POLICY_EXISTS_CREATE]);
if ($status == Aerospike::OK) {
echo "Record written.\n";
} elseif ($status == Aerospike::ERR_RECORD_EXISTS) {
echo "The Aerospike server already has a record with the given key.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
The Aerospike cluster already has a record with the given key.
Example #3 Fail if the record has been written since it was last read (CAS)
// Get the record metadata and note its generation
$client->exists($key, $metadata);
$gen = $metadata['generation'];
$gen_policy = [Aerospike::POLICY_GEN_EQ, $gen];
$res = $client->put($key, $bins, 0, [Aerospike::OPT_POLICY_GEN => $gen_policy]);
if ($res == Aerospike::OK) {
echo "Record written.\n";
} elseif ($res == Aerospike::ERR_RECORD_GENERATION) {
echo "The record has been written since we last read it.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
?>
The record has been written since we last read it.
Example #4 Handling binary strings
$str = 'Glagnar\'s Human Rinds, "It\'s a bunch\'a munch\'a crunch\'a human!';
$deflated = new \Aerospike\Bytes(gzdeflate($str));
$wrapped = new \Aerospike\Bytes("trunc\0ated");
$key = $client->initKey('test', 'demo', 'wrapped-bytes');
$status = $client->put($key, ['unwrapped'=>"trunc\0ated", 'wrapped'=> $wrapped, 'deflated' => $deflated]);
if ($status !== Aerospike::OK) {
die($client->error());
}
$client->get($key, $record);
$wrapped = \Aerospike\Bytes::unwrap($record['bins']['wrapped']);
$deflated = $record['bins']['deflated'];
$inflated = gzinflate($deflated->s);
echo "$inflated\n";
echo "wrapped binary-string: ";
var_dump($wrapped);
$unwrapped = $record['bins']['unwrapped'];
echo "The binary-string that was given to put() without a wrapper: $unwrapped\n";
Glagnar's Human Rinds, "It's a bunch'a munch'a crunch'a human!
wrapped binary-string: string(10) "truncated"
The binary-string that was given to put() without a wrapper: trunc
int
get(array $key, array $record, null|array $select = null, array $options = [])
Read a record with a given key, and store it in $record
The bins returned in $record can be filtered by passing a $select
array of bin names. Non-existent bins will appear in the $record with a NULL
value.
Example #1 Aerospike::get() default behavior example
$key = $client->initKey("test", "users", 1234);
$status = $client->get($key, $record);
if ($status == Aerospike::OK) {
var_dump($record);
} elseif ($status == Aerospike::ERR_RECORD_NOT_FOUND) {
echo "A user with key ". $key['key']. " does not exist in the database\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(3) {
["key"]=>
array(4) {
["digest"]=>
string(40) "436a3b9fcafb96d12844ab1377c0ff0d7a0b70cc"
["namespace"]=>
NULL
["set"]=>
NULL
["key"]=>
NULL
}
["metadata"]=>
array(2) {
["generation"]=>
int(3)
["ttl"]=>
int(12345)
}
["bins"]=>
array(3) {
["email"]=>
string(9) "[email protected]"
["name"]=>
string(9) "You There"
["age"]=>
int(33)
}
}
Example #2 get the record with filtered bins
// assuming this follows Example #1, getting a filtered record
$filter = ["email", "manager"];
unset($record);
$status = $client->get($key, $record, $filter);
if ($status == Aerospike::OK) {
var_dump($record);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(3) {
["key"]=>
array(4) {
["digest"]=>
string(40) "436a3b9fcafb96d12844ab1377c0ff0d7a0b70cc"
["namespace"]=>
NULL
["set"]=>
NULL
["key"]=>
NULL
}
["metadata"]=>
array(2) {
["generation"]=>
int(3)
["ttl"]=>
int(12344)
}
["bins"]=>
array(2) {
["email"]=>
string(15) "[email protected]"
["manager"]=>
NULL
}
}
int
exists(array $key, array $metadata, array $options = [])
Get the metadata of a record with a given key, and store it in $metadata
$key = $client->initKey("test", "users", 1234);
$status = $client->exists($key, $metadata);
if ($status == Aerospike::OK) {
var_dump($metadata);
} elseif ($status == Aerospike::ERR_RECORD_NOT_FOUND) {
echo "A user with key ". $key['key']. " does not exist in the database\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(2) {
["generation"]=>
int(4)
["ttl"]=>
int(1337)
}
or
A user with key 1234 does not exist in the database.
int
touch(array $key, int $ttl = 0, array $options = [])
Touch the record identified by the $key, resetting its time-to-live.
$key = $client->initKey("test", "users", 1234);
$status = $client->touch($key, 120);
if ($status == Aerospike::OK) {
echo "Added 120 seconds to the record's expiration.\n"
} elseif ($status == Aerospike::ERR_RECORD_NOT_FOUND) {
echo "A user with key ". $key['key']. " does not exist in the database\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
Added 120 seconds to the record's expiration.
or
A user with key 1234 does not exist in the database.
int
remove(array $key, array $options = [])
Remove the record identified by the $key.
$key = $client->initKey("test", "users", 1234);
$status = $client->remove($key);
if ($status == Aerospike::OK) {
echo "Record removed.\n";
} elseif ($status == Aerospike::ERR_RECORD_NOT_FOUND) {
echo "A user with key ". $key['key']. " does not exist in the database\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
Record removed.
int
removeBin(array $key, array $bins, array $options = [])
Remove $bins from the record identified by the $key.
$key = ["ns" => "test", "set" => "users", "key" => 1234];
$options = array(Aerospike::OPT_TTL => 3600);
$status = $client->removeBin($key, ["age"], $options);
if ($status == Aerospike::OK) {
echo "Removed bin 'age' from the record.\n";
} elseif ($status == Aerospike::ERR_RECORD_NOT_FOUND) {
echo "The database has no record with the given key.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
truncate(string $ns, string $set, int $nanos, array $options = [])
Remove all the records from a namespace or set
Remove records in a specified namespace/set efficiently. This method is many orders of magnitude faster than deleting records one at a time. Note: works with Aerospike Server versions >= 3.12 See https://www.aerospike.com/docs/reference/info#truncate Truncate command information
This asynchronous server call may return before the truncation is complete. The user can still write new records after the server returns because new records will have last update times greater than the truncate cutoff (set at the time of truncate call).
The truncate command does not durably delete records in the Community Edition. The Enterprise Edition provides durability through the truncate command.
$secondsInDay = 24 * 60 * 60;
// Multiply by 10 ^ 9 to get nanoseconds
$yesterday = 1000000000 * (time() - $secondsInDay);
// Remove all records in test/truncateSet updated before 24 hours ago
$status = $client->truncate("test", "demoSet", $yesterday);
// Truncate all records in test, regardless of update time
$status = $client->truncate("test", null, 0);
int
increment(array $key, string $bin, int|float $offset, array $options = [])
Increment the value of $bin in the record identified by the $key by an $offset.
$key = $client->initKey("test", "users", 1234);
$options = [Aerospike::OPT_TTL => 7200];
$status = $client->increment($key, 'pto', -4, $options);
if ($status == Aerospike::OK) {
echo "Decremented four vacation days from the user's PTO balance.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
append(array $key, string $bin, string $value, array $options = [])
Append a string $value to the one already in $bin, in the record identified by the $key.
$key = $client->initKey("test", "users", 1234);
$options = [Aerospike::OPT_TTL => 3600];
$status = $client->append($key, 'name', ' Ph.D.', $options);
if ($status == Aerospike::OK) {
echo "Added the Ph.D. suffix to the user.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
prepend(array $key, string $bin, string $value, array $options = [])
Prepend a string $value to the one already in $bin, in the record identified by the $key.
$key = $client->initKey("test", "users", 1234);
$options = [Aerospike::OPT_TTL => 3600];
$status = $client->prepend($key, 'name', '*', $options);
if ($status == Aerospike::OK) {
echo "Starred the user.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
operate(array $key, array $operations, array $returned, array $options = [])
Perform multiple bin operations on a record with a given key, with write operations happening before read ones.
Non-existent bins being read will have a NULL
value.
Currently a call to operate() can include only one write operation per-bin. For example, you cannot both append and prepend to the same bin, in the same call.
Like other bin operations, operate() only works on existing records (i.e. ones that were previously created with a put()).
Example #1 Combining several write operations into one multi-op call
[
["op" => Aerospike::OPERATOR_APPEND, "bin" => "name", "val" => " Ph.D."],
["op" => Aerospike::OPERATOR_INCR, "bin" => "age", "val" => 1],
["op" => Aerospike::OPERATOR_READ, "bin" => "age"]
]
$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]], "shm"=>[]];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
$key = $client->initKey("test", "users", 1234);
$operations = [
["op" => Aerospike::OPERATOR_APPEND, "bin" => "name", "val" => " Ph.D."],
["op" => Aerospike::OPERATOR_INCR, "bin" => "age", "val" => 1],
["op" => Aerospike::OPERATOR_READ, "bin" => "age"],
];
$options = [Aerospike::OPT_TTL => 600];
$status = $client->operate($key, $operations, $returned, $options);
if ($status == Aerospike::OK) {
var_dump($returned);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(1) {
["age"]=>
int(34)
}
Example #2 Implementing an LRU by reading a bin and touching a record in the same operation
[
["op" => Aerospike::OPERATOR_READ, "bin" => "age"],
["op" => Aerospike::OPERATOR_TOUCH, "ttl" => 20]
]
int
operateOrdered(array $key, array $operations, array $returned, array $options = [])
Perform multiple bin operations on a record with a given key, with write operations happening before read ones.
The order of the resulting elements will correspond to the order of the operations in the parameters.
Non-existent bins being read will have a NULL
value.
Currently a call to operateOrdered() can include only one write operation per-bin. For example, you cannot both append and prepend to the same bin, in the same call.
Like other bin operations, operateOrdered() only works on existing records (i.e. ones that were previously created with a put()).
Example #1 Combining several write operations into one multi-op call
$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]], "shm"=>[]];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
$key = $client->initKey("test", "demo", "pk458");
$operations = [
array("op" => Aerospike::OP_LIST_APPEND, "bin" => "age", "val"=>49),
array("op" => Aerospike::OP_LIST_GET, "bin" => "age", "index"=>0),
array("op" => Aerospike::OP_LIST_POP, "bin" => "age", "index"=>0)
];
$returned = "output value";
$status = $client->operateOrdered($key, $operations, $returned);
if ($status == Aerospike::OK) {
var_dump($returned);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
listSize(array $key, string $bin, int $count, array $options = [])
Count the number of elements in a list type bin
int
listAppend(array $key, string $bin, mixed $value, array $options = [])
Add a single value (of any type) to the end of a list type bin
int
listMerge(array $key, string $bin, array $items, array $options = [])
Add several items to the end of a list type bin
int
listInsert(array $key, string $bin, int $index, mixed $value, array $options = [])
Insert a single element (of any type) at a specified index of a list type bin
int
listInsertItems(array $key, string $bin, int $index, array $elements, array $options = [])
Insert several elements at a specified index of a list type bin
int
listPop(array $key, string $bin, int $index, mixed $element, array $options = [])
Remove and get back the element at a specified index of a list type bin Index -1 is the last item in the list, -3 is the third from last, 0 is the first in the list.
int
listPopRange(array $key, string $bin, int $index, int $count, array $elements, array $options = [])
Remove and get back several elements at a specified index range of a list type bin Index -1 is the last item in the list, -3 is the third from last, 0 is the first in the list.
int
listRemove(array $key, string $bin, int $index, array $options = [])
Remove a list element at a specified index of a list type bin
int
listRemoveRange(array $key, string $bin, int $index, int $count, array $options = [])
Remove several list elements at a specified index range of a list type bin
int
listTrim(array $key, string $bin, int $index, int $count, array $options = [])
Trim the list, removing all elements not in the specified index range of a list type bin
int
listClear(array $key, string $bin, array $options = [])
Remove all the elements from a list type bin
int
listSet(array $key, string $bin, int $index, mixed $value, array $options = [])
Set an element at a specified index of a list type bin
int
listGet(array $key, string $bin, int $index, array $element, array $options = [])
Get an element from a specified index of a list type bin
int
listGetRange(array $key, string $bin, int $index, int $count, array $elements, array $options = [])
Get several elements starting at a specified index from a list type bin
int
getMany(array $keys, array $records, array $select = [], array $options = [])
Read a batch of records from a list of given keys, and fill $records with the resulting indexed array
Each record is an array consisting of key, metadata and bins (see: {\Aerospike::get() get()}).
Non-existent records will have NULL
for their metadata and bins fields.
The bins returned can be filtered by passing an array of bin names.
Note that the protocol getMany() will use (batch-direct or batch-index)
is configurable through the config parameter Aerospike::USE_BATCH_DIRECT
or php.ini
config parameter aerospike.use_batch_direct
.
By default batch-index is used with servers that support it (version >= 3.6.0).
Example #1 Aerospike::getMany() default behavior example
$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]], "shm"=>[]];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
$key1 = $client->initKey("test", "users", 1234);
$key2 = $client->initKey("test", "users", 1235); // this key does not exist
$key3 = $client->initKey("test", "users", 1236);
$keys = array($key1, $key2, $key3);
$status = $client->getMany($keys, $records);
if ($status == Aerospike::OK) {
var_dump($records);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(3) {
[0]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1234)
["digest"]=>
string(20) "M?v2Kp???
?[??4?v
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(1)
}
["bins"]=>
array(3) {
["email"]=>
string(15) "[email protected]"
["name"]=>
string(9) "You There"
["age"]=>
int(33)
}
}
[1]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1235)
["digest"]=>
string(20) "?C??[?vwS??ƨ?????"
}
["metadata"]=>
NULL
["bins"]=>
NULL
}
[2]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1236)
["digest"]=>
string(20) "'?9?
??????
? ?"
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(1)
}
["bins"]=>
array(3) {
["email"]=>
string(19) "[email protected]"
["name"]=>
string(8) "This Guy"
["age"]=>
int(42)
}
}
}
Example #2 getMany records with filtered bins
// assuming this follows Example #1
$filter = ["email"];
$keys = [$key1, $key3];
$status = $client->getMany($keys, $records, $filter);
if ($status == Aerospike::OK) {
var_dump($records);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(2) {
[0]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1234)
["digest"]=>
string(20) "M?v2Kp???
?[??4?v
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(4)
}
["bins"]=>
array(1) {
["email"]=>
string(15) "[email protected]"
}
}
[1]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1236)
["digest"]=>
string(20) "'?9?
??????
? ?"
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(4)
}
["bins"]=>
array(1) {
["email"]=>
string(19) "[email protected]"
}
}
}
int
existsMany(array $keys, array $metadata, array $options = [])
Check if a batch of records exists in the database and fill $metdata with the results
Checks for the existence a batch of given keys (see: {\Aerospike::exists() exists()}),
and return an indexed array matching the order of the keys.
Non-existent records will have NULL
for their metadata.
Note that the protocol existsMany() will use (batch-direct or batch-index)
is configurable through the config parameter Aerospike::USE_BATCH_DIRECT
or php.ini
config parameter aerospike.use_batch_direct
.
By default batch-index is used with servers that support it (version >= 3.6.0).
Example #1 Aerospike::existsMany() default behavior example
$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]], "shm"=>[]];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
$key1 = $client->initKey("test", "users", 1234);
$key2 = $client->initKey("test", "users", 1235); // this key does not exist
$key3 = $client->initKey("test", "users", 1236);
$keys = array($key1, $key2, $key3);
$status = $client->existsMany($keys, $metadata);
if ($status == Aerospike::OK) {
var_dump($records);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(3) {
[0]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1234)
["digest"]=>
string(20) "M?v2Kp???
?[??4?v
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(1)
}
}
[1]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1235)
["digest"]=>
string(20) "?C??[?vwS??ƨ?????"
}
["metadata"]=>
NULL
}
[2]=>
array(3) {
["key"]=>
array(4) {
["ns"]=>
string(4) "test"
["set"]=>
string(5) "users"
["key"]=>
int(1236)
["digest"]=>
string(20) "'?9?
??????
? ?"
}
["metadata"]=>
array(2) {
["ttl"]=>
int(4294967295)
["generation"]=>
int(1)
}
}
}
int
scan(string $ns, string $set, callable $record_cb, array $select = [], array $options = [])
Scan a namespace or set
Scan a ns.set, and invoke a callback function record_cb on each record streaming back from the cluster.
Optionally select the bins to be returned. Non-existent bins in this list will appear in the record with a NULL value.
$options = [Aerospike::OPT_SCAN_PRIORITY => Aerospike::SCAN_PRIORITY_MEDIUM];
$processed = 0;
$status = $client->scan('test', 'users', function ($record) use (&$processed) {
if (!is_null($record['bins']['email'])) echo $record['bins']['email']."\n";
if ($processed++ > 19) return false; // halt the stream by returning a false
}, ['email'], $options);
var_dump($status, $processed);
[email protected]
:
[email protected]
I think a sample of 20 records is enough
int
query(string $ns, string $set, array $where, callable $record_cb, array $select = [], array $options = [])
Query a secondary index on a namespace or set
Query a ns.set with a specified predicate, and invoke a callback function record_cb on each record matched by the query and streaming back from the cluster.
Optionally select the bins to be returned. Non-existent bins in this list will appear in the record with a NULL value.
$result = [];
$where = Aerospike::predicateBetween("age", 30, 39);
$status = $client->query("test", "users", $where, function ($record) use (&$result) {
$result[] = $record['bins'];
});
if ($status !== Aerospike::OK) {
echo "An error occured while querying[{$client->errorno()}] {$client->error()}\n";
} else {
echo "The query returned ".count($result)." records\n";
}
[email protected]
:
[email protected]
I think a sample of 20 records is enough
static array
predicateEquals(string $bin, int|string $val)
Helper method for creating an EQUALS predicate
static array
predicateBetween(string $bin, int $min, int $max)
Helper method for creating a BETWEEN predicate
static array
predicateContains(string $bin, int $index_type, int|string $val)
Helper method for creating an CONTAINS predicate
Similar to predicateEquals(), predicateContains() looks for an exact match of a value inside a complex type - a list containing the value (if the index type is INDEX_TYPE_LIST), the value contained in the keys of a map (if the index type is INDEX_TYPE_MAPKEYS), or a record with the given value contained in the values of a map (if the index type was INDEX_TYPE_MAPVALUES).
static array
predicateRange(string $bin, int $index_type, int $min, int $max)
Helper method for creating a RANGE predicate
Similar to predicateBetween(), predicateRange() looks for records with a range of values inside a complex type - a list containing the values (if the index type is INDEX_TYPE_LIST), the values contained in the keys of a map (if the index type is INDEX_TYPE_MAPKEYS), or a record with the given values contained in the values of a map (if the index type was INDEX_TYPE_MAPVALUES)
static array
predicateGeoContainsGeoJSONPoint(string $bin, string $point)
Helper method for creating a GEOCONTAINS point predicate
static array
predicateGeoContainsPoint(string $bin, float $long, float $lat)
Helper method for creating a GEOCONTAINS point predicate
static array
predicateGeoWithinGeoJSONRegion(string $bin, string $region)
Helper method for creating a GEOWITHIN region predicate
static array
predicateGeoWithinRadius(string $bin, float $long, float $lat, float $radiusMeter)
Helper method for creating a GEOWITHIN circle region predicate
int
jobInfo(int $job_id, int $job_type, array $info, array $options = [])
Get the status of a background job triggered by Aerospike::scanApply or Aerospike::queryApply
// after a queryApply() where $job_id was set:
do {
time_nanosleep(0, 30000000); // pause 30ms
$status = $client->jobInfo($job_id, Aerospike::JOB_QUERY, $job_info);
var_dump($job_info);
} while($job_info['status'] != Aerospike::JOB_STATUS_COMPLETED);
int
register(string $path, string $module, int $language = Aerospike::UDF_TYPE_LUA, array $options = [])
Register a UDF module with the cluster
Note that modules containing stream UDFs need to also be copied to the
path described in aerospike.udf.lua_user_path
, as the last reduce
iteration is run locally on the client (after reducing on all the nodes
of the cluster).
Currently the only UDF language supported is Lua.
$status = $client->register('/path/to/my_udf.lua', 'my_udf.lua');
if ($status == Aerospike::OK) {
echo "UDF module at $path is registered as my_udf on the Aerospike DB.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
deregister(string $module, array $options = [])
Remove a UDF module from the cluster
$status = $client->deregister('my_udf');
if ($status == Aerospike::OK) {
echo "UDF module my_udf was removed from the Aerospike DB.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
listRegistered(array $modules, int $language = Aerospike::UDF_TYPE_LUA, array $options = [])
List the UDF modules registered with the cluster
The modules array has the following structure:
Array of:
name => module name
type => Aerospike::UDF_TYPE_*
Example
$status = $client->listRegistered($modules);
if ($status == Aerospike::OK) {
var_dump($modules);
} else {
echo "[{$client->errorno()}] ".$client->error();
}
array(2) {
[0]=>
array(2) {
["name"]=>
string(13) "my_record_udf"
["type"]=>
int(0)
}
[1]=>
array(2) {
["name"]=>
string(13) "my_stream_udf"
["type"]=>
int(0)
}
}
int
getRegistered(string $module, string $code, string $language = Aerospike::UDF_TYPE_LUA, array $options = [])
Get the code for a UDF module registered with the cluster
Populates code with the content of the matching UDF module that was previously registered with the server.
Example
$status = $client->getRegistered('my_udf', $code);
if ($status == Aerospike::OK) {
var_dump($code);
} elseif ($status == Aerospike::ERR_LUA_FILE_NOT_FOUND) {
echo "The UDF module my_udf was not found to be registered with the server.\n";
}
string(351) "function startswith(rec, bin_name, prefix)
if not aerospike:exists(rec) then
return false
end
if not prefix then
return true
end
if not rec[bin_name] then
return false
end
local bin_val = rec[bin_name]
l = prefix:len()
if l > bin_val:len() then
return false
end
ret = bin_val:sub(1, l) == prefix
return ret
end
"
int
apply(array $key, string $module, string $function, array $args = [], mixed $returned = null, array $options = [])
Apply a UDF to a record
Applies the UDF module.function to a record with a given key. Arguments can be passed to the UDF and any returned value optionally captured.
Currently the only UDF language supported is Lua.
$key = ["ns" => "test", "set" => "users", "key" => "1234"];
$status = $client->apply($key, 'my_udf', 'startswith', ['email', 'hey@'], $returned);
if ($status == Aerospike::OK) {
if ($returned) {
echo "The email of the user with key {$key['key']} starts with 'hey@'.\n";
} else {
echo "The email of the user with key {$key['key']} does not start with 'hey@'.\n";
}
} elseif ($status == Aerospike::ERR_UDF_NOT_FOUND) {
echo "The UDF module my_udf.lua was not registered with the Aerospike DB.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
The email of the user with key 1234 starts with 'hey@'.
int
scanApply(string $ns, string $set, string $module, string $function, array $args, int $job_id, array $options = [])
Apply a UDF to each record in a scan
Scan the ns.set and apply a UDF module.function to each of its records. Arguments can be passed to the UDF and any returned value optionally captured.
Currently the only UDF language supported is Lua.
$status = $client->scanApply("test", "users", "my_udf", "mytransform", array(20), $job_id);
if ($status === Aerospike::OK) {
var_dump("Job ID is $job_id");
} else if ($status === Aerospike::ERR_CLIENT) {
echo "An error occured while initiating the BACKGROUND SCAN [{$client->errorno()}] ".$client->error();
} else {
echo "An error occured while running the BACKGROUND SCAN [{$client->errorno()}] ".$client->error();
}
string(12) "Job ID is 1"
int
queryApply(string $ns, string $set, array $where, string $module, string $function, array $args, int $job_id, array $options = [])
Apply a UDF to each record in a query
Query the ns.set with a predicate, and apply a UDF module.function to each of matched records. Arguments can be passed to the UDF and any returned value optionally captured.
Currently the only UDF language supported is Lua.
$where = Aerospike::predicateBetween("age", 30, 39);
$status = $client->queryApply("test", "users", "my_udf", "mytransform", [20], $job_id);
if ($status === Aerospike::OK) {
var_dump("Job ID is $job_id");
} else if ($status === Aerospike::ERR_CLIENT) {
echo "An error occured while initiating the BACKGROUND SCAN [{$client->errorno()}] ".$client->error();
} else {
echo "An error occured while running the BACKGROUND SCAN [{$client->errorno()}] ".$client->error();
}
string(12) "Job ID is 1"
int
aggregate(string $ns, string $set, array $where, string $module, string $function, array $args, mixed $returned, array $options = [])
Apply a stream UDF to a scan or secondary index query
Apply the UDF module.function to the result of running a secondary index query on ns.set. The aggregated returned variable is then filled, with its type depending on the UDF. It may be a string, integer or array, and potentially an array of arrays, such as in the case the UDF does not specify a reducer and there are multiple nodes in the cluster, each sending back the result of its own aggregation.
As with query(), if an empty array is given as the where predicate a 'scan aggregation' is initiated instead of a query, which means the stream UDF is applied to all the records returned by the scan.
Note that modules containing stream UDFs need to also be copied to the
path described in aerospike.udf.lua_user_path
, as the last reduce
iteration is run locally on the client, after reducing on all the nodes
of the cluster.
Note aggregate is currently unsupported in PHP built with ZTS enabled. Attempting to use it in that environment will fail.
Currently the only UDF language supported is Lua.
Example Stream UDF
Module registered as stream_udf.lua
local function having_ge_threshold(bin_having, ge_threshold)
debug("group_count::thresh_filter: %s > %s ?", tostring(rec[bin_having]), tostring(ge_threshold))
return function(rec)
if rec[bin_having] < ge_threshold then
return false
end
return true
end
end
local function count(group_by_bin)
return function(group, rec)
if rec[group_by_bin] then
local bin_name = rec[group_by_bin]
group[bin_name] = (group[bin_name] or 0) + 1
end
return group
end
end
local function add_values(val1, val2)
return val1 + val2
end
local function reduce_groups(a, b)
return map.merge(a, b, add_values)
end
function group_count(stream, group_by_bin, bin_having, ge_threshold)
if bin_having and ge_threshold then
local myfilter = having_ge_threshold(bin_having, ge_threshold)
return stream : filter(myfilter) : aggregate(map}, count(group_by_bin)) : reduce(reduce_groups)
else
return stream : aggregate(map}, count(group_by_bin)) : reduce(reduce_groups)
end
end
Example of aggregating a stream UDF to the result of a secondary index query
// assuming test.users has a bin first_name, show the first name distribution
// for users in their twenties
$where = Aerospike::predicateBetween("age", 20, 29);
$status = $client->aggregate("test", "users", $where, "stream_udf", "group_count", ["first_name"], $names);
if ($status == Aerospike::OK) {
var_dump($names);
} else {
echo "An error occured while running the AGGREGATE [{$client->errorno()}] ".$client->error();
}
array(5) {
["Claudio"]=>
int(1)
["Michael"]=>
int(3)
["Jennifer"]=>
int(2)
["Jessica"]=>
int(3)
["Jonathan"]=>
int(3)
}
int
addIndex(string $ns, string $set, string $bin, string $name, int $indexType, int $dataType, array $options = [])
Create a secondary index on a bin of a specified set
Create a secondary index of a given index_type on a namespace ns, set and bin with a specified name
$status = $client->addIndex("test", "user", "email", "user_email_idx", Aerospike::INDEX_TYPE_DEFAULT, Aerospike::INDEX_STRING);
if ($status == Aerospike::OK) {
echo "Index user_email_idx created on test.user.email\n";
} else if ($status == Aerospike::ERR_INDEX_FOUND) {
echo "This index has already been created.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
$client->addIndex("test", "user", "movies", "user_movie_titles_idx", Aerospike::INDEX_TYPE_MAPKEYS, Aerospike::INDEX_STRING);
$client->addIndex("test", "user", "movies", "user_movie_views_idx", Aerospike::INDEX_TYPE_MAPVALUES, Aerospike::INDEX_NUMERIC);
$client->addIndex("test", "user", "aliases", "user_aliases_idx", Aerospike::INDEX_TYPE_LIST, Aerospike::INDEX_STRING);
$client->info("sindex", $res);
echo($res);
int
dropIndex(string $ns, string $name, array $options = [])
Drop a secondary index
$status = $client->dropIndex("test", "user_email_idx");
if ($status == Aerospike::OK) {
echo "Index user_email_idx was dropped from namespace 'test'\n";
} else if ($status == Aerospike::ERR_INDEX_NOT_FOUND) {
echo "No such index exists.\n";
} else {
echo "[{$client->errorno()}] ".$client->error();
}
int
info(string $request, string $response, null|array $host = null, array $options = [])
Send an info request to a single cluster node
Interface with the cluster's command and control functions. A formatted request string is sent to a cluster node, and a formatted response returned.
A specific host can be optionally set, otherwise the request command is sent to the host definded for client constructor.
$client->info('bins/test', $response);
var_dump($response);
string(53) "bins/test num-bin-names=2,bin-names-quota=32768,demo,characters"
array
infoMany(string $request, null|array $host = null, array $options = [])
Send an info request to a single cluster node
Interface with the cluster's command and control functions. A formatted request string is sent to a cluster node, and a formatted response returned.
A specific host can be optionally set, otherwise the request command is sent to the host definded for client constructor.
$response = $client->infoMany('build');
var_dump($response);
array(3) {
["BB936F106CA0568"]=>
string(6) "build 3.3.19"
["AE712F245BB9876"]=>
string(6) "build 3.3.19"
["DCBA9AA34EE12FA"]=>
string(6) "build 3.3.19"
}
array
getNodes()
Get the addresses of the cluster nodes
$nodes = $client->getNodes();
var_dump($nodes);
array(2) {
[0]=>
array(2) {
["addr"]=>
string(15) "192.168.120.145"
["port"]=>
string(4) "3000"
}
[1]=>
array(2) {
["addr"]=>
string(15) "192.168.120.144"
["port"]=>
string(4) "3000"
}
}
setLogLevel(int $log_level)
Set the logging threshold of the Aerospike object
setLogHandler(callable $log_handler)
Set a handler for log events
Registers a callback method that will be triggered whenever a logging event above the declared log threshold occurs.
$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]], "shm"=>[]];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
echo "Aerospike failed to connect[{$client->errorno()}]: {$client->error()}\n";
exit(1);
}
$client->setLogLevel(Aerospike::LOG_LEVEL_DEBUG);
$client->setLogHandler(function ($level, $file, $function, $line) {
switch ($level) {
case Aerospike::LOG_LEVEL_ERROR:
$lvl_str = 'ERROR';
break;
case Aerospike::LOG_LEVEL_WARN:
$lvl_str = 'WARN';
break;
case Aerospike::LOG_LEVEL_INFO:
$lvl_str = 'INFO';
break;
case Aerospike::LOG_LEVEL_DEBUG:
$lvl_str = 'DEBUG';
break;
case Aerospike::LOG_LEVEL_TRACE:
$lvl_str = 'TRACE';
break;
default:
$lvl_str = '???';
}
error_log("[$lvl_str] in $function at $file:$line");
});
setSerializer(callable $serialize_cb)
Set a serialization handler for unsupported types
Registers a callback method that will be triggered whenever a write method handles a value whose type is unsupported. This is a static method and the serialize_cb handler is global across all instances of the Aerospike class.
Aerospike::setSerializer(function ($val) {
return gzcompress(json_encode($val));
});
setDeserializer(callable $unserialize_cb)
Set a deserialization handler for unsupported types
Registers a callback method that will be triggered whenever a read method handles a value whose type is unsupported. This is a static method and the unserialize_cb handler is global across all instances of the Aerospike class.
Aerospike::setDeserializer(function ($val) {
return json_decode(gzuncompress($val));
});