Search code examples
aerospike

Create, and insert into, an Aerospike ordered map from Python


I see documentation for appending to a list in Aerospike, from Python, namely:

key = ('test', 'demo', 1)
rec = {'coutry': 'India', 'city': ['Pune', 'Dehli']}

client.put(key, rec)

client.list_append(key, 'city', 'Mumbai')

However I don't know how to add elements to a map in Aerospike, from Python, and I also don't know how to define said map as sorted.

Essentially I am trying to model a time series as follows:

  ticker1: {intepochtime1: some_number, intepochtime2: some_other_number,...}
  ticker2: {intepochtime1: some_number, intepochtime2: some_other_number,...}
  ........

where the tickers are the record keys, so are indexed obviously, but also where the intepochtimes are integer JS-style integer timestamps and are also indexed by virtue of being stored in ascending or descending order and therefore easily range-queryable. How is this doable from Python?


Solution

  • Here is some sample code to get you started: Also on github: https://github.com/pygupta/aerospike-discuss/tree/master/stkovrflo_Py_SortedMaps

    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
    
    
    
    pgupta@ubuntu:~/discussRepo/aerospike-discuss/stkovrflo_Py_SortedMaps$ python sortedMapExample.py 
    Sorted by values, 2 - 14
    [2, 3, 7, 12, 12, 13]
    Index 0 - 3
    [13, 3, 7]