Skip to content

Primary index

For the complete documentation index see: llms.txt

All documentation pages available in markdown.

Jump to the Code block for a combined complete example.

Basic PI queries have the following features:

  • Filter records by set name.
  • Filter records by filter expressions.
  • Limit the number of records returned, useful for pagination.
  • Return only record digests and metadata (generation and TTL).
  • Return specified bins.

Setup

The following examples will use the setup and record structure below to illustrate primary index queries in an Aerospike database.

import aerospike
from aerospike_helpers import expressions as exp
from aerospike_helpers.operations import operations
# Define host configuration
config = {
'hosts': [ ('127.0.0.1', 3000) ]
}
# Establishes a connection to the server
client = aerospike.client(config)

The record structure:

Occurred: Integer
Reported: Integer
Posted: Integer
Report: Map
{
shape: List,
summary: String,
city: String,
state: String,
duration: String
}
Location: GeoJSON

Policies

See Basic Queries for query policy information.

Query a set

The following example queries the sandbox namespace and ufodata set name, while limiting the record set to only 20 records.

# Create the query
query = client.query('sandbox', 'ufodata')
# Set max records to return
query.max_records = 20
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Key: {0} | Record: {1}'.format(key[2], bins))
# Execute the query
query.foreach(record_set)
# Close the connection to the server
client.close()

Query with a metadata filter

The following example queries the same namespace and set as the example above, but also adds a metadata Filter Expression that will only return records that are greater than 16 KiB.

# Build the expression
expr = exp.GT(exp.DeviceSize(), (1024 * 16)).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Key: {0} | Record: {1}'.format(key[2], bins))
# Execute the query
query.foreach(record_set, policy=query_policy)
# Close the connection to the server
client.close()

Query with a data filter

The following example queries the same namespace and set as the example above, but also adds a data Filter Expression that will only return records where the occurred bin value is in the inclusive range 20200101 to 20211231.

Take a look at secondary index queries to see how this same query can be run more efficiently with an index.

# Build the expression
expr = exp.Let(
exp.Def('bin', exp.IntBin('occurred')),
exp.And(
exp.GE(exp.Var('bin'), 20210101),
exp.LE(exp.Var('bin'), 20211231))).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Key: {0} | Record: {1}'.format(key[2], bins))
# Execute the query
query.foreach(record_set, policy=query_policy)
# Close the connection to the server
client.close()

Query a range of partitions

Aerospike divides each namespace into 4096 partitions. Each record belongs to exactly one partition, so non-overlapping ranges that cover all 4096 partitions return every record exactly once. To process a set in independent parts, limit a query to a range of partitions with the partition_filter key of the query policy. For example, you can split a full-set scan across several workers. Partition filters need Database 6.0 or later.

  • begin: the first partition. The default is 0.
  • count: the number of partitions to include. The default is all 4096 partitions.

When a query uses a partition filter, foreach() calls your callback with two arguments: the partition ID as an int, and the record tuple. A callback that accepts only the record fails with ClientError: Callback function contains an error.

The following example counts the records in the ufodata set by querying the first and second half of the partitions separately.

# Create a callback function that counts records. With a partition filter,
# it receives the partition ID and the record.
def count_range(begin, count):
total = 0
def tally(partition_id, record):
nonlocal total
total += 1
# Limit the query to a range of partitions
query_policy = {'partition_filter': {'begin': begin, 'count': count}}
query = client.query('sandbox', 'ufodata')
query.foreach(tally, policy=query_policy)
return total
first_half = count_range(0, 2048) # Partitions 0 to 2047
second_half = count_range(2048, 2048) # Partitions 2048 to 4095
print('{0} + {1} = {2}'.format(first_half, second_half, first_half + second_half))
# Close the connection to the server
client.close()

If you use query.results() instead of foreach(), pass the same policy. It returns the record tuples without partition IDs.

Pagination

Pagination uses a combination of a partition filter and a defined maximum records to return query results. The partition filter maintains a cursor identifying the end of the current page and the beginning of the next. Moving to the next page of results is as simple as executing the query again, with the previously defined partition filter.

The following example executes a query with an Expression Filter identifying records with more than 3 shape items in the report map, returning 10 records per page. The partition filter is set to query all 4096 partitions in the database.

# Build the expression
expr = exp.GT(
exp.ListSize(
None,
exp.MapGetByKey(None, aerospike.MAP_RETURN_VALUE, exp.ResultType.LIST, 'shape', exp.MapBin('report'))
),
3).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Set max records
query.max_records = 10
# Set pagination
query.paginate()
# Execute the query
page = 0
while not query.is_done():
count = 0
records = query.results(query_policy)
for record in records:
(key, meta, bins) = record
# Do something
print('Key: {0} | Record: {1}'.format(key[2], bins))
count += 1
page += 1
print('Page {0} | {1} records'.format(page, count))
# Close the connection to the server
client.close()

Code block

Expand this section for a single code block to execute a basic PI query
import aerospike
from aerospike_helpers import expressions as exp
from aerospike_helpers.operations import operations
# Define host configuration
config = {
'hosts': [ ('127.0.0.1', 3000) ]
}
# Establishes a connection to the server
client = aerospike.client(config)
# Build the expression
expr = exp.Let(
exp.Def('bin', exp.IntBin('occurred')),
exp.And(
exp.GE(exp.Var('bin'), 20210101),
exp.LE(exp.Var('bin'), 20211231))).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Key: {0} | Record: {1}'.format(key[2], bins))
# Execute the query
query.foreach(record_set, policy=query_policy)
# Close the connection to the server
client.close()