In Python how I mix query.select with query.foreach to print?


#1

Hello world,

I am working my way through the content here:

http://www.aerospike.com/docs/client/python/usage/query/query.html

I have a simple script which works well:

import pdb
import aerospike

config = {'hosts': [('127.0.0.1',3000)]}

client = aerospike.client(config).connect()

mynamspace = 'test'
myset      = 'dogs'

myrecname  = 'Fred'
myrecpk    = 100
foodbin    = 'Fred likes catfood'
agebin     = 4

myrecord   = {'myrecname': myrecname, 'myrecpk': myrecpk, 'foodbin': foodbin, 'agebin': agebin}

keytuple     = (mynamspace,myset,myrecpk)

client.put(keytuple, myrecord)

query = client.query(mynamspace,myset)

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

query.foreach(print_result)

qsel = query.select('foodbin', 'agebin')

But when I add the following line, the script fails:

qsel.foreach(print_result)

Questions:

Why did it fail?

How do I print qsel results?


#2

When you call query.foreach the query executes and streams the resulting records to the callback, one at a time. You’re trying to select after the query has started. That won’t work.

For example:

import aerospike
from aerospike import predicates as p

client = aerospike.client({ 'hosts': [ ('192.168.119.3', 3000) ]  }).connect()
myquery = client.query("test", "tweets")
myquery.select('tweet','username')
# callback for each record read
def mycallback((key, meta, record)):
  print(record)

myquery.where(p.equals('username','ronen'))
myquery.foreach(mycallback)

Gives back:

{'username': u'ronen', 'tweet': u'you go girl'}
{'username': u'ronen', 'tweet': u'YOLO!'}

#3

FYI, The API documentation for Query has been cleaned up.