Skip to content

Secondary 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 SI queries can employ the following index filters:

  • Equality comparison against string or integer indexes.
  • Range comparison against integer indexes. Range result sets are inclusive of lower and upper limits.
  • Contains comparison against indexes on the elements of a list, or the keys or values of a map.
  • Point-In-Region or Region-Contain-Point comparisons against geo indexes.

Record filtering with expressions can also be used with secondary index queries.

Policies

See Basic Queries for query policy information.

Setup

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

import aerospike
from aerospike_helpers import expressions as exp
from aerospike_helpers.operations import map_operations
from aerospike import predicates as p
from aerospike import GeoJSON
# 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

Create an index

Create an integer secondary index with asadm or sindex-create through asinfo. Both accept the integer key type in Database 8.2.0 and later. Use asadm for interactive work and asinfo for automation.

The following commands create an integer index on the sandbox namespace, ufodata set, and occurred bin.

asadm
asadm -e 'enable; manage sindex create integer occurred_idx ns sandbox set ufodata bin occurred'
asinfo
asinfo -v 'sindex-create:indexname=occurred_idx;namespace=sandbox;set=ufodata;bin=occurred;type=integer;indextype=default'

The Aerospike Client API can be used to create a secondary index as well. The following example creates the same index as the example above.

# Create index
client.index_integer_create(
'sandbox', # namespace
'ufodata', # set name
'occurred', # bin name
'occurred_idx', # index name
# optional policy
)

This example uses index_integer_create(), which creates an integer secondary index. Prefer aerospike.INDEX_INTEGER over the deprecated aerospike.INDEX_NUMERIC constant when you create indexes through the API (Python client 19.3.0 and later). Aerospike supports index types NUMERIC, STRING, GEO2DSPHERE, and BLOB as of Database 7.0.

The index_*_create() calls wait until the server finishes building the index before they return, so you can query the index right after the call.

Remove an index

The following command uses the Aerospike Admin (asadm) to remove the index created above.

Terminal window
asadm -e 'enable; manage sindex delete occurred_idx ns sandbox set ufodata'

The Aerospike Client API can be used to remove a secondary index as well. The following example removes the same index as the example above.

# Remove index
client.index_remove(
'sandbox', # namespace
'occurred_idx', # index name
# optional policy
)

Query an index

The following example queries the sandbox namespace and ufodata set name, with an inclusive range filter on the occurred bin, returning records with a bin value between 20210101 and 20211231.

# Create the query
query = client.query('sandbox', 'ufodata')
# Set index filter
query.where(p.between('occurred', 20210101, 20211231))
# 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 an index with a Filter Expression

The following example will use the geo string defined in the expandable section below.

View the language specific data creation
# Create geo region
region = GeoJSON({
'type': 'Polygon',
'coordinates': [
[
[-109.061279296875, 36.97622678464096],
[-102.01904296874999, 36.97622678464096],
[-102.01904296874999, 41.0130657870063],
[-109.061279296875, 41.0130657870063],
[-109.061279296875, 36.97622678464096]
]
]
})

This example queries the same namespace and set name, while using the same index filter as the example above, but adds a Filter Expression to the query policy to only return records with a location bin value within the geo region specified above.

# Build the expression
expr = exp.CmpGeo(exp.GeoBin('location'), region).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Set index filter
query.where(p.between('occurred', 20210101, 20211231))
# 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 an index and read only some map keys

To return only part of each matching record, add a read operation to the query with add_ops(). This needs Database 8.1.2 or later, because earlier servers allow only basic read operations in foreground queries.

This example queries the same namespace and set name, while using the same index filter, geo region, and Filter Expression as above. The operation reads only the city and state keys from the report map, so each record returns those two values in place of its bins.

# Build the expression
expr = exp.CmpGeo(exp.GeoBin('location'), region).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Set index filter
query.where(p.between('occurred', 20210101, 20211231))
# Read only 'city' and 'state' from the report map
mapKeys = ['city', 'state']
query.add_ops([
map_operations.map_get_by_key_list('report', mapKeys, aerospike.MAP_RETURN_VALUE)
])
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Record: ', bins['report'])
# Execute the query
query.foreach(record_set, policy=query_policy)
# Close the connection to the server
client.close()

Query the elements of a list

A secondary index can cover the elements of a list bin, instead of the whole bin value. Each element in the list is indexed, and a query matches a record when any element in its list matches. Create the index with index_list_create(), and give the type of the list elements, such as aerospike.INDEX_STRING, aerospike.INDEX_INTEGER, aerospike.INDEX_BLOB, or aerospike.INDEX_GEO2DSPHERE.

The following example creates an index on the tags list in the products set, writes three records, and queries for the products that have the tag sale.

# Create an index on the elements of the "tags" list
client.index_list_create(
'sandbox', # namespace
'products', # set name
'tags', # bin name
aerospike.INDEX_STRING, # type of the list elements
'tags_idx', # index name
# optional policy
)
# Write the records
client.put(('sandbox', 'products', 1), {'name': 'Desk', 'tags': ['sale', 'new']})
client.put(('sandbox', 'products', 2), {'name': 'Lamp', 'tags': ['clearance']})
client.put(('sandbox', 'products', 3), {'name': 'Chair', 'tags': ['sale']})
# Create the query
query = client.query('sandbox', 'products')
# Set index filter: the list contains the string "sale"
query.where(p.contains('tags', aerospike.INDEX_TYPE_LIST, 'sale'))
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Name: {0}'.format(bins['name']))
# Execute the query
query.foreach(record_set)
# Close the connection to the server
client.close()

Use p.contains() with aerospike.INDEX_TYPE_LIST to query a list index. p.equals() looks for an index on the whole bin value, so it can’t use an index on list elements and fails with IndexNotFound.

A query returns the user key only for records that were written with the aerospike.POLICY_KEY_SEND key policy. Otherwise the key tuple holds None in place of the user key, so read a bin, such as name in the example, to identify the records.

To index the keys or the values of a map bin, use index_map_keys_create() or index_map_values_create(). Query them with p.contains() and aerospike.INDEX_TYPE_MAPKEYS or aerospike.INDEX_TYPE_MAPVALUES.

Query a geospatial index

A geospatial index lets a query find records by location. Store each location in a bin as a GeoJSON value. Create the index with index_single_value_create() and aerospike.INDEX_GEO2DSPHERE. Query it with one of the geo_ predicates. GeoJSON lists the longitude before the latitude.

The following example creates a geospatial index on the loc bin of the places set, writes three places, and queries for the places within 20,000 meters of a point in San Francisco.

# Create a geospatial index
client.index_single_value_create(
'sandbox', # namespace
'places', # set name
'loc', # bin name
aerospike.INDEX_GEO2DSPHERE, # index data type
'loc_idx', # index name
# optional policy
)
# Write the records. Coordinates are [longitude, latitude].
client.put(('sandbox', 'places', 1), {
'name': 'San Francisco',
'loc': GeoJSON({'type': 'Point', 'coordinates': [-122.4194, 37.7749]})
})
client.put(('sandbox', 'places', 2), {
'name': 'Oakland',
'loc': GeoJSON({'type': 'Point', 'coordinates': [-122.2711, 37.8044]})
})
client.put(('sandbox', 'places', 3), {
'name': 'Los Angeles',
'loc': GeoJSON({'type': 'Point', 'coordinates': [-118.2437, 34.0522]})
})
# Create the query
query = client.query('sandbox', 'places')
# Set index filter: within 20,000 meters of longitude -122.4194, latitude 37.7749
query.where(p.geo_within_radius('loc', -122.4194, 37.7749, 20000))
# Create callback function
def record_set(record):
(key, meta, bins) = record
# Do something
print('Name: {0}'.format(bins['name']))
# Execute the query
query.foreach(record_set)
# Close the connection to the server
client.close()

The query prints San Francisco and Oakland. The index serves the query, so the server doesn’t check the distance of every record in the set.

To find the points inside a region instead of a circle, use p.geo_within_geojson_region('loc', region.dumps()). Here region is a GeoJSON polygon like the one in Query an index with a Filter Expression. To find the regions that contain a point, store the regions in the bin and use p.geo_contains_point('loc', longitude, latitude). See Geospatial data for the geospatial data type and its limits.

Pagination

See Pagination for more information.

Code block

Expand this section for a single code block to execute a basic SI query
import aerospike
from aerospike_helpers import expressions as exp
from aerospike_helpers.operations import operations, map_operations
from aerospike import predicates as p
from aerospike import GeoJSON
# Define host configuration
config = {
'hosts': [ ('127.0.0.1', 3000) ]
}
# Establishes a connection to the server
client = aerospike.client(config)
# Create geo region
region = GeoJSON({
'type': 'Polygon',
'coordinates': [
[
[-109.061279296875, 36.97622678464096],
[-102.01904296874999, 36.97622678464096],
[-102.01904296874999, 41.0130657870063],
[-109.061279296875, 41.0130657870063],
[-109.061279296875, 36.97622678464096]
]
]
})
# Build the expression
expr = exp.CmpGeo(exp.GeoBin('location'), region).compile()
# Create the policy
query_policy = {'expressions': expr}
# Create the query
query = client.query('sandbox', 'ufodata')
# Set index filter
query.where(p.between('occurred', 20210101, 20211231))
# 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()