-
Notifications
You must be signed in to change notification settings - Fork 3
Queries
Aerospike allows you to create secondary indexes and query records on them.
Annotate fields with @Indexed annotation
public class EntityIndexed {
@UserKey
@Indexed // will be ignored
public String key;
@Generation
public Integer generation;
// set specific index name
@Indexed(name = "index_number") // will set IndexType.NUMERIC
public int number;
// index name will be automatically set to idx_<setName>_<fieldName>
// in this case: idx_EntityIndexed_text
@Indexed // will set IndexType.STRING
public String text;
@Indexed // will set IndexCollectionType.LIST
public List<String> list;
@Indexed // will set IndexCollectionType.MAPKEYS
public Map<String, String> mapKeys;
@Indexed(collection = IndexCollectionType.MAPVALUES) // overrides MAPKEYS
public Map<String, String> mapValues;
@Ignore
@Indexed // will be ignored
public String ignored;To trigger index creation just call:
SpikefyService.register(EntityIndexed.class);Index names if not explicitly given are automatically assigned via class and field name: idx\<simpleClassName>\<fieldName>
If @SetName annotation is given on class type, then index is generated as: idx_<setName>_<fieldName>
note: changing indexed class names or field names also changes the underlying index names. So once in production be aware of this. If you have to change field or class name set index name manually on each field!
Indexes can also be created via native createIndex(..) method:
// get native client
IAerospikeClient client = SpikeifyService.getClient();
// create index
client.createIndex(new Policy(), namespace, setName, indexName, binName, IndexType.STRING);Indexes are dropped via native dropIndex(..)` method:
// get native client
IAerospikeClient client = SpikeifyService.getClient();
// drop index
client.dropIndex(new Policy(), namespace, setName, indexName);After a secondary index is created, you can query on it:
ResultSet<MyEntity> resultSet = sfy.query(MyEntity.class)
.filter(fieldName, searchedValue)
.now();
ResultSet<MyEntity> resultSet = sfy.query(MyEntity.class)
.filter(fieldName, rangeMin, rangeMax)
.now();ResultSet implements Iterable
for (MyEntity myEntity : resultSet){
// do something with myEntity
}Or retrieve list of entities:
List<MyEntity> list = resultSet.toList();note the toList() method automatically closes the result set!
If you have a large result set and you do not iterate through it entirely, then it's advisable to close it so that underlying client performs cleanup
resultSet.close();