← All posts

Aerospike UDF (User-Defined Function)

How to create and use Aerospike UDF using Node.js

The image from Aerospike LinkedIn page

Aerospike User-Defined Functions (UDFs) allow developers to execute custom logic directly within the Aerospike database. This is particularly useful for tasks such as filtering, aggregation, and more complex data processing that would otherwise require multiple round trips between the client and server.

An Aerospike User-Defined Function is a piece of code, written by a developer in Lua programming language (or C called from Lua) that runs inside the Aerospike database server.

In this article, we’ll explore how to create and use Aerospike UDFs using Node.js. We’ll cover the basics of Lua and demonstrate how to register and execute these functions within Aerospike.

Lua: The Language Behind Aerospike UDFs

Lua is a powerful, efficient, lightweight, and embeddable scripting language. It supports various programming paradigms, including procedural, object-oriented, functional, and data-driven programming. Lua’s flexibility makes it an excellent choice for writing Aerospike UDFs.

When you write UDFs for Aerospike, you’ll use Lua to define the logic that will run on the server. This logic can range from simple record filtering to more complex data manipulation.

Setting Up Aerospike and Node.js

To follow along with this guide, you’ll need the following versions:

  • Node.js: v8–14 with Aerospike client v3.16 — Aerospike server v3
  • Node.js: v20–22 with Aerospike client v5 — Aerospike server v7.1

Writing a Lua UDF for Aerospike

Let’s write a simple Lua UDF that filters records based on a specific condition. For instance, imagine that we have loads of records like the next one: {age: 25, isActive:1}. Create a file named test_udf.lua and define your function:

local function my_filter_fn(rec)
local isActive = rec['isActive'] or 0
if isActive == 1 then
return true
else
return false
end
end

local function my_map_fn(rec)
local result = map()
result['isActive'] = rec['isActive']
return result
end

function test_fn(stream)
return stream : filter(my_filter_fn) : map(my_map_fn)
end

This Lua code defines a set of functions designed to filter and map records within an Aerospike stream using a User-Defined Function (UDF). Here’s a detailed breakdown of each part:

1. my_filter_fn

local function my_filter_fn(rec)
local isActive = rec['isActive'] or 0
if isActive == 1 then
return true
else
return false
end
end

This function filters records based on the value of the isActive field. It first attempts to retrieve the isActive field from the record (rec). If isActive doesn't exist, it defaults to 0.

2. my_map_fn

local function my_map_fn(rec)
local result = map()
result['isActive'] = rec['isActive']
return result
end

This function transforms records by creating a new map that includes only the isActive field from the original record. It makes a new, empty map named result. The isActive value from the original record (rec) is added to the result map. The function returns the result map, which now contains just the isActive field.

3. test_fn

function test_fn(stream)
return stream : filter(my_filter_fn) : map(my_map_fn)
end

This function processes a stream of records by filtering them using my_filter_fn and then mapping the filtered records using my_map_fn. The function receives a stream of records as its input. The filter method applies my_filter_fn to the stream, keeping only the records where isActive equals 1. The map method then applies my_map_fn to each of the filtered records, transforming them into a simplified map containing just the isActive field. The final result is a stream of records that have been both filtered and transformed.

Registering the Lua UDF with Aerospike

Once you’ve written your Lua script, you need to register it with Aerospike. You can do this using the Aerospike Query Language (AQL).

Open AQL:

aql

Register the Lua module:

REGISTER MODULE 'test_udf.lua'

Verify the registration:

SHOW MODULES

Creating a Secondary Index

Before using the UDF to filter data, you need to create a secondary index on the field you plan to filter by. For our example, we’ll create an index on the age field. More about it here.

Using the UDF in Node.js

Now that the UDF is registered and the index is created, you can execute the UDF using Node.js.

  1. Create an index.js file:
const Aerospike= require('aerospike');

const AerospikeClient = Aerospike.client({
hosts: '127.0.0.1:3000', // aerospike server
log: { level: Aerospike.log.DEBUG }, // show logs
modlua: {userPath: './udf'} // local path to udf
});

try {
await AerospikeClient.connect();
await getKeys();
await AerospikeClient.close();
} catch (e) {
console.log('Error:', e);
}

async function getKeys(){
return new Promise((resolve, reject) => {
try{
let query = AerospikeClient.query('namespace', 'set');
// add filter with secondary index
query.where(Aerospike.filter.equal('age', 18));
// set udf to be used (it should be present in the udf folder and registered in the aerospike)
query.setUdf( 'test_udf', 'test_fn');
let stream = query.foreach();
let data = [];
stream.on('data', (record) => {
data.push(record);
});
stream.on('error', (error) => {
console.error('Stream error:', error);
});
stream.on('end', () => {
console.log('Stream end - ', data.length);
return resolve();
});
} catch (err) {
console.log('getKeys err - ', err);
return reject(err);
}
})
}

2. Run the script:

node index.js

Conclusion

Aerospike UDFs offer a powerful way to execute custom logic directly within the database, reducing the need for complex queries or multiple round trips between client and server. By following the steps outlined in this article, you can easily create, register, and execute UDFs using Node.js.


Useful links:

  1. The full code of the example in this article.
  2. Aerospike UDF documentation