Sorted Maps in Python

Sample code for doing sorted maps in Python.

import aerospike
from aerospike import predicates as p

def print_result((key, metadata, record)):
   print(record)

config = { 'hosts': [ ("localhost", 3000), ] }
client = aerospike.client(config).connect()

map_policy={'map_order':aerospike.MAP_KEY_VALUE_ORDERED}

# Insert the records
key = ("test", "demo", 'km1')
client.map_set_policy(key, "mymap", map_policy)
client.map_put(key,  "mymap", '0', 13)
client.map_put(key,  "mymap", '1', 3)
client.map_put(key,  "mymap", '2', 7)
client.map_put(key,  "mymap", '3', 2)
client.map_put(key,  "mymap", '4', 12)
client.map_put(key,  "mymap", '5', 33)
client.map_put(key,  "mymap", '6', 1)
client.map_put(key,  "mymap", '7', 12)
client.map_put(key,  "mymap", '8', 22)


# Query for sorted value
print "Sorted by values, 2 - 14"
ret_val = client.map_get_by_value_range(key, "mymap", 2, 14, aerospike.MAP_RETURN_VALUE)
print ret_val

#get first 3 indexes 
print "Index 0 - 3"
ret_val2 = client.map_get_by_index_range(key, "mymap", 0, 3, aerospike.MAP_RETURN_VALUE)
print ret_val2

Execute:

$ python sortedMapExample.py 
Sorted by values, 2 - 14
[2, 3, 7, 12, 12, 13]
Index 0 - 3
[13, 3, 7]

Improve code at: aerospike-discuss/stkovrflo_Py_SortedMaps at master · pygupta/aerospike-discuss · GitHub

(There are two other sample code files on github - one for doing Secondary Indexes on Lists and Maps, other for using Map SIs to do set level Sorted Maps.)

Additional info:

Look at Python documentation for Client. Server must be ver 3.8.4+ Create map policy : Define one of the key ordered or key value ordered policies http://www.aerospike.com/apidocs/python/client.html#map-policies for map_order

Put map type bin but first define the map policy. http://www.aerospike.com/apidocs/python/client.html#id1 see map_set_policy(key, bin, map_policy) then map_put()

Sorted maps are just regular maps but with map_order policy.

Also see ongoing discussion on this topic at: Create, and insert into, an Aerospike ordered map from Python - Stack Overflow

Note: Regardless of map type, ordered, k-ordered, k-v ordered, all API calls work, difference is performance. See aerospike.com/docs/guide/cdt-map.html - Table on performance for various OPs.

2 Likes

Release 3.2.0 of the Python client added support for ordered list.

I created examples for CDT (ordered map, ordered list) here: GitHub - aerospike-examples/aerospike-modeling: Examples of using Aerospike's complex data types (Map and List) to implement common patterns