Map

class Map(service_name, name, context)[source]

Bases: Proxy[BlockingMap], Generic[KeyType, ValueType]

Hazelcast Map client proxy to access the map on the cluster.

Concurrent, distributed, observable and queryable map. This map can work both async(non-blocking) or sync(blocking). Blocking calls return the value of the call and block the execution until return value is calculated. However, async calls return Future and do not block execution. Result of the Future can be used whenever ready. A Future’s result can be obtained with blocking the execution by calling future.result().

Example

>>> my_map = client.get_map("my_map").blocking()  # sync map, all operations are blocking
>>> print("map.put", my_map.put("key", "value"))
>>> print("map.contains_key", my_map.contains_key("key"))
>>> print("map.get", my_map.get("key"))
>>> print("map.size", my_map.size())

Example

>>> my_map = client.get_map("map")  # async map, all operations are non-blocking
>>> def put_callback(f):
>>>     print("map.put", f.result())
>>> my_map.put("key", "async_val").add_done_callback(put_callback)
>>>
>>> print("map.size", my_map.size().result())
>>>
>>> def contains_key_callback(f):
>>>     print("map.contains_key", f.result())
>>> my_map.contains_key("key").add_done_callback(contains_key_callback)

This class does not allow None to be used as a key or value.

add_entry_listener(include_value: bool = False, key: Optional[KeyType] = None, predicate: Optional[Predicate] = None, added_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, removed_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, updated_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, evicted_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, evict_all_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, clear_all_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, merged_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, expired_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None, loaded_func: Optional[Callable[[EntryEvent[KeyType, ValueType]], None]] = None) Future[str][source]

Adds a continuous entry listener for this map.

Listener will get notified for map events filtered with given parameters.

Parameters:
  • include_value – Whether received event should include the value or not.

  • key – Key for filtering the events.

  • predicate – Predicate for filtering the events.

  • added_func – Function to be called when an entry is added to map.

  • removed_func – Function to be called when an entry is removed from map.

  • updated_func – Function to be called when an entry is updated.

  • evicted_func – Function to be called when an entry is evicted from map.

  • evict_all_func – Function to be called when entries are evicted from map.

  • clear_all_func – Function to be called when entries are cleared from map.

  • merged_func – Function to be called when WAN replicated entry is merged.

  • expired_func – Function to be called when an entry’s live time is expired.

  • loaded_func – Function to be called when an entry is loaded from a map loader.

Returns:

A registration id which is used as a key to remove the listener.

add_index(attributes: Optional[Sequence[str]] = None, index_type: Union[int, str] = 0, name: Optional[str] = None, bitmap_index_options: Optional[Dict[str, Any]] = None) Future[None][source]

Adds an index to this map for the specified entries so that queries can run faster.

Example

Let’s say your map values are Employee objects.

>>> class Employee(IdentifiedDataSerializable):
>>>     active = false
>>>     age = None
>>>     name = None
>>>     #other fields
>>>
>>>     #methods

If you query your values mostly based on age and active fields, you should consider indexing these.

>>> employees = client.get_map("employees")
>>> employees.add_index(attributes=["age"]) # Sorted index for range queries
>>> employees.add_index(attributes=["active"], index_type=IndexType.HASH)) # Hash index for equality predicates

Index attribute should either have a getter method or be public. You should also make sure to add the indexes before adding entries to this map.

Indexing time is executed in parallel on each partition by operation threads. The Map is not blocked during this operation. The time taken in proportional to the size of the Map and the number Members.

Until the index finishes being created, any searches for the attribute will use a full Map scan, thus avoiding using a partially built index and returning incorrect results.

Parameters:
  • attributes – List of indexed attributes.

  • index_type – Type of the index. By default, set to SORTED.

  • name – Name of the index.

  • bitmap_index_options

    Bitmap index options.

    • unique_key: (str): The unique key attribute is used as a source of values which uniquely identify each entry being inserted into an index. Defaults to KEY_ATTRIBUTE_NAME. See the hazelcast.config.QueryConstants for possible values.

    • unique_key_transformation (int|str): The transformation is applied to every value extracted from the unique key attribue. Defaults to OBJECT. See the hazelcast.config.UniqueKeyTransformation for possible values.

add_interceptor(interceptor: Any) Future[str][source]

Adds an interceptor for this map.

Added interceptor will intercept operations and execute user defined methods.

Parameters:

interceptor – Interceptor for the map which includes user defined methods.

Returns:

Id of registered interceptor.

aggregate(aggregator: Aggregator[AggregatorResultType], predicate: Optional[Predicate] = None) Future[AggregatorResultType][source]

Applies the aggregation logic on map entries and filter the result with the predicate, if given.

Parameters:
  • aggregator – Aggregator to aggregate the entries with.

  • predicate – Predicate to filter the entries with.

Returns:

The result of the aggregation.

clear() Future[None][source]

Clears the map.

The MAP_CLEARED event is fired for any registered listeners.

contains_key(key: KeyType) Future[bool][source]

Determines whether this map contains an entry with the key.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – The specified key.

Returns:

True if this map contains an entry for the specified key, False otherwise.

contains_value(value: ValueType) Future[bool][source]

Determines whether this map contains one or more keys for the specified value.

Parameters:

value – The specified value.

Returns:

True if this map contains an entry for the specified value, False otherwise.

delete(key: KeyType) Future[None][source]

Removes the mapping for a key from this map if it is present (optional operation).

Unlike remove(object), this operation does not return the removed value, which avoids the serialization cost of the returned value. If the removed value will not be used, a delete operation is preferred over a remove operation for better performance.

The map will not contain a mapping for the specified key once the call returns.

Warning

This method breaks the contract of EntryListener. When an entry is removed by delete(), it fires an EntryEvent with a None old_value. Also, a listener with predicates will have None values, so only the keys can be queried via predicates.

Parameters:

key – Key of the mapping to be deleted.

entry_set(predicate: Optional[Predicate] = None) Future[List[Tuple[KeyType, ValueType]]][source]

Returns a list clone of the mappings contained in this map.

Warning

The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.

Parameters:

predicate – Predicate for the map to filter entries.

Returns:

The list of key-value tuples in the map.

evict(key: KeyType) Future[bool][source]

Evicts the specified key from this map.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – Key to evict.

Returns:

True if the key is evicted, False otherwise.

evict_all() Future[None][source]

Evicts all keys from this map except the locked ones.

The EVICT_ALL event is fired for any registered listeners.

execute_on_entries(entry_processor: Any, predicate: Optional[Predicate] = None) Future[List[Any]][source]

Applies the user defined EntryProcessor to all the entries in the map or entries in the map which satisfies the predicate if provided. Returns the results mapped by each key in the map.

Parameters:
  • entry_processor – A stateful serializable object which represents the EntryProcessor defined on server side. This object must have a serializable EntryProcessor counter part registered on server side with the actual com.hazelcast.map.EntryProcessor implementation.

  • predicate – Predicate for filtering the entries.

Returns:

List of map entries which includes the keys and the results of the entry process.

execute_on_key(key: KeyType, entry_processor: Any) Future[Any][source]

Applies the user defined EntryProcessor to the entry mapped by the key. Returns the object which is the result of EntryProcessor’s process method.

Parameters:
  • key – Specified key for the entry to be processed.

  • entry_processor – A stateful serializable object which represents the EntryProcessor defined on server side. This object must have a serializable EntryProcessor counter part registered on server side with the actual com.hazelcast.map.EntryProcessor implementation.

Returns:

Result of entry process.

execute_on_keys(keys: Sequence[KeyType], entry_processor: Any) Future[List[Any]][source]

Applies the user defined EntryProcessor to the entries mapped by the collection of keys. Returns the results mapped by each key in the collection.

Parameters:
  • keys – Collection of the keys for the entries to be processed.

  • entry_processor – A stateful serializable object which represents the EntryProcessor defined on server side. This object must have a serializable EntryProcessor counter part registered on server side with the actual com.hazelcast.map.EntryProcessor implementation.

Returns:

List of map entries which includes the keys and the results of the entry process.

flush() Future[None][source]

Flushes all the local dirty entries.

force_unlock(key: KeyType) Future[None][source]

Releases the lock for the specified key regardless of the lock owner.

It always successfully unlocks the key, never blocks, and returns immediately.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – The key to lock.

get(key: KeyType) Future[Optional[ValueType]][source]

Returns the value for the specified key, or None if this map does not contain this key.

Warning

This method returns a clone of original value, modifying the returned value does not change the actual value in the map. One should put modified value back to make changes visible to all nodes.

>>> value = my_map.get(key)
>>> value.update_some_property()
>>> my_map.put(key,value)

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – The specified key.

Returns:

The value for the specified key.

get_all(keys: Sequence[KeyType]) Future[Dict[KeyType, ValueType]][source]

Returns the entries for the given keys.

Warning

The returned map is NOT backed by the original map, so changes to the original map are NOT reflected in the returned map, and vice-versa.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

keys – Keys to get.

Returns:

Dictionary of map entries.

get_entry_view(key: KeyType) Future[SimpleEntryView[KeyType, ValueType]][source]

Returns the EntryView for the specified key.

Warning

This method returns a clone of original mapping, modifying the returned value does not change the actual value in the map. One should put modified value back to make changes visible to all nodes.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – The key of the entry.

Returns:

EntryView of the specified key.

is_empty() Future[bool][source]

Returns whether this map contains no key-value mappings or not.

Returns:

True if this map contains no key-value mappings, False otherwise.

is_locked(key: KeyType) Future[bool][source]

Checks the lock for the specified key.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – The key that is checked for lock

Returns:

True if lock is acquired, False otherwise.

key_set(predicate: Optional[Predicate] = None) Future[List[ValueType]][source]

Returns a List clone of the keys contained in this map or the keys of the entries filtered with the predicate if provided.

Warning

The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.

Parameters:

predicate – Predicate to filter the entries.

Returns:

A list of the clone of the keys.

load_all(keys: Optional[Sequence[KeyType]] = None, replace_existing_values: bool = True) Future[None][source]

Loads all keys from the store at server side or loads the given keys if provided.

Parameters:
  • keys – Keys of the entry values to load.

  • replace_existing_values – Whether the existing values will be replaced or not with those loaded from the server side MapLoader.

lock(key: KeyType, lease_time: Optional[float] = None) Future[None][source]

Acquires the lock for the specified key infinitely or for the specified lease time if provided.

If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.

You get a lock whether the value is present in the map or not. Other threads (possibly on other systems) would block on their invoke of lock() until the non-existent key is unlocked. If the lock holder introduces the key to the map, the put() operation is not blocked. If a thread not holding a lock on the non-existent key tries to introduce the key while a lock exists on the non-existent key, the put() operation blocks until it is unlocked.

Scope of the lock is this map only. Acquired lock is only for the key in this map.

Locks are re-entrant; so, if the key is locked N times, it should be unlocked N times before another thread can acquire it.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – The key to lock.

  • lease_time – Time in seconds to wait before releasing the lock.

project(projection: Projection[ProjectionType], predicate: Optional[Predicate] = None) Future[ProjectionType][source]

Applies the projection logic on map entries and filter the result with the predicate, if given.

Parameters:
  • projection – Projection to project the entries with.

  • predicate – Predicate to filter the entries with.

Returns:

The result of the projection.

put(key: KeyType, value: ValueType, ttl: Optional[float] = None, max_idle: Optional[float] = None) Future[Optional[ValueType]][source]

Associates the specified value with the specified key in this map.

If the map previously contained a mapping for the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted after the ttl.

Warning

This method returns a clone of the previous value, not the original (identically equal) value previously put into the map.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – The specified key.

  • value – The value to associate with the key.

  • ttl – Maximum time in seconds for this entry to stay in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite time-to-live.

  • max_idle – Maximum time in seconds for this entry to stay idle in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite max idle time.

Returns:

Previous value associated with key or None if there was no mapping for key.

put_all(map: Dict[KeyType, ValueType]) Future[None][source]

Copies all the mappings from the specified map to this map.

No atomicity guarantees are given. In the case of a failure, some key-value tuples may get written, while others are not.

Parameters:

map – Dictionary which includes mappings to be stored in this map.

put_if_absent(key: KeyType, value: ValueType, ttl: Optional[float] = None, max_idle: Optional[float] = None) Future[Optional[ValueType]][source]

Associates the specified key with the given value if it is not already associated.

If ttl is provided, entry will expire and get evicted after the ttl.

This is equivalent to below, except that the action is performed atomically:

>>> if not my_map.contains_key(key):
>>>     return my_map.put(key,value)
>>> else:
>>>     return my_map.get(key)

Warning

This method returns a clone of the previous value, not the original (identically equal) value previously put into the map.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – Key of the entry.

  • value – Value of the entry.

  • ttl – Maximum time in seconds for this entry to stay in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite time-to-live.

  • max_idle – Maximum time in seconds for this entry to stay idle in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite max idle time.

Returns:

Old value of the entry.

put_transient(key: KeyType, value: ValueType, ttl: Optional[float] = None, max_idle: Optional[float] = None) Future[None][source]

Same as put, but MapStore defined at the server side will not be called.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – Key of the entry.

  • value – Value of the entry.

  • ttl – Maximum time in seconds for this entry to stay in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite time-to-live.

  • max_idle – Maximum time in seconds for this entry to stay idle in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite max idle time.

remove(key: KeyType) Future[Optional[ValueType]][source]

Removes the mapping for a key from this map if it is present.

The map will not contain a mapping for the specified key once the call returns.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:

key – Key of the mapping to be deleted.

Returns:

The previous value associated with key, or None if there was no mapping for key.

remove_all(predicate: Predicate) Future[None][source]

Removes all entries which match with the supplied predicate.

Parameters:

predicate – Used to select entries to be removed from map.

remove_if_same(key: KeyType, value: ValueType) Future[bool][source]

Removes the entry for a key only if it is currently mapped to a given value.

This is equivalent to below, except that the action is performed atomically:

>>> if my_map.contains_key(key) and my_map.get(key) == value:
>>>     my_map.remove(key)
>>>     return True
>>> else:
>>>     return False

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – The specified key.

  • value – Remove the key if it has this value.

Returns:

True if the value was removed, False otherwise.

remove_entry_listener(registration_id: str) Future[bool][source]

Removes the specified entry listener.

Returns silently if there is no such listener added before.

Parameters:

registration_id – Id of registered listener.

Returns:

True if registration is removed, False otherwise.

remove_interceptor(registration_id: str) Future[bool][source]

Removes the given interceptor for this map, so it will not intercept operations anymore.

Parameters:

registration_id – Registration ID of the map interceptor.

Returns:

True if the interceptor is removed, False otherwise.

replace(key: KeyType, value: ValueType) Future[Optional[ValueType]][source]

Replaces the entry for a key only if it is currently mapped to some value.

This is equivalent to below, except that the action is performed atomically:

>>> if my_map.contains_key(key):
>>>     return my_map.put(key,value)
>>> else:
>>>     return None

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Warning

This method returns a clone of the previous value, not the original (identically equal) value previously put into the map.

Parameters:
  • key – The specified key.

  • value – The value to replace the previous value.

Returns:

Previous value associated with key, or None if there was no mapping for key.

replace_if_same(key: ValueType, old_value: ValueType, new_value: ValueType) Future[bool][source]

Replaces the entry for a key only if it is currently mapped to a given value.

This is equivalent to below, except that the action is performed atomically:

>>> if my_map.contains_key(key) and my_map.get(key) == old_value:
>>>     my_map.put(key, new_value)
>>>     return True
>>> else:
>>>     return False

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – The specified key.

  • old_value – Replace the key value if it is the old value.

  • new_value – The new value to replace the old value.

Returns:

True if the value was replaced, False otherwise.

set(key: KeyType, value: ValueType, ttl: Optional[float] = None, max_idle: Optional[float] = None) Future[None][source]

Puts an entry into this map.

Similar to the put operation except that set doesn’t return the old value, which is more efficient. If ttl is provided, entry will expire and get evicted after the ttl.

Warning

This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key’s class.

Parameters:
  • key – Key of the entry.

  • value – Value of the entry.

  • ttl – Maximum time in seconds for this entry to stay in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite time-to-live.

  • max_idle – Maximum time in seconds for this entry to stay idle in the map. If not provided, the value configured on the server side configuration will be used. Setting this to 0 means infinite max idle time.

set_ttl(key: KeyType, ttl: float) Future[None][source]

Updates the TTL (time to live) value of the entry specified by the given key with a new TTL value.

New TTL value is valid starting from the time this operation is invoked, not since the time the entry was created. If the entry does not exist or is already expired, this call has no effect.

Parameters:
  • key – The key of the map entry.

  • ttl – Maximum time in seconds for this entry to stay in the map. Setting this to 0 means infinite time-to-live.

size() Future[int][source]

Returns the number of entries in this map.

Returns:

Number of entries in this map.

try_lock(key: KeyType, lease_time: Optional[float] = None, timeout: float = 0) Future[bool][source]

Tries to acquire the lock for the specified key.

When the lock is not available:

  • If the timeout is not provided, the current thread doesn’t wait and returns False immediately.

  • If the timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens:

    • The lock is acquired by the current thread, or

    • The specified waiting time elapses.

If the lease time is provided, lock will be released after this time elapses.

Parameters:
  • key – Key to lock in this map.

  • lease_time – Time in seconds to wait before releasing the lock.

  • timeout – Maximum time in seconds to wait for the lock.

Returns:

True if the lock was acquired, False otherwise.

try_put(key: KeyType, value: ValueType, timeout: float = 0) Future[bool][source]

Tries to put the given key and value into this map and returns immediately if timeout is not provided.

If timeout is provided, operation waits until it is completed or timeout is reached.

Parameters:
  • key – Key of the entry.

  • value – Value of the entry.

  • timeout – Maximum time in seconds to wait.

Returns:

True if the put is successful, False otherwise.

try_remove(key: KeyType, timeout: float = 0) Future[bool][source]

Tries to remove the given key from this map and returns immediately if timeout is not provided.

If timeout is provided, operation waits until it is completed or timeout is reached.

Parameters:
  • key – Key of the entry to be deleted.

  • timeout – Maximum time in seconds to wait.

Returns:

True if the remove is successful, False otherwise.

unlock(key: KeyType) Future[None][source]

Releases the lock for the specified key.

It never blocks and returns immediately. If the current thread is the holder of this lock, then the hold count is decremented. If the hold count is zero, then the lock is released.

Parameters:

key – The key to lock.

values(predicate: Optional[Predicate] = None) Future[List[ValueType]][source]

Returns a list clone of the values contained in this map or values of the entries which are filtered with the predicate if provided.

Warning

The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.

Parameters:

predicate – Predicate to filter the entries.

Returns:

A list of clone of the values contained in this map.

blocking() BlockingMap[KeyType, ValueType][source]

Returns a version of this proxy with only blocking method calls.