---
title: "Apply a UDF"
description: "Learn to apply Aerospike Record UDFs in Python for single records, batch operations, and background queries."
---

# Apply a UDF

> For the complete documentation index see: [llms.txt](https://aerospike.com/docs/llms.txt)
> 
> All documentation pages available in markdown.

Jump to the [Code block](#code-block) for a combined complete example.

UDFs that execute on a single record are Record UDFs. The record may or may not exist in the database, and the UDF may create, read, and/or update a record.

## Setup

The following examples will use the setup below to illustrate applying a record UDF.

```python
import aerospike

from aerospike_helpers import expressions as exp

# Define host configuration

config = {

    'hosts': [ ('127.0.0.1', 3000) ]

}

# Establishes a connection to the server

client = aerospike.client(config)
```

The record structure:

```text
Occurred: Integer

Reported: Integer

Posted: Integer

Report: Map

{

    shape: List,

    summary: String,

    city: String,

    state: String,

    duration: String

}

Location: GeoJSON
```

## Single record commands

### Single argument

This example uses the `setRecent` function in the module `example.lua`. See [Manage UDFs](https://aerospike.com/docs/develop/client/python/usage/udf/manage) for `example.lua` code and information on registering the UDF.

This compares the `posted` bin to a supplied value and writes `true`/`false` to a `recent` bin based on the result.

```python
# Creates a key with the namespace "sandbox", set "ufodata", and user key 5000

key = ('sandbox', 'ufodata', 5000)

# Execute the UDF

client.apply(key, 'example', 'setRecent', [20210101])

# View the updated record

(key, meta, bins) = client.get(key)

print('Record: ', bins)

# Close the connection to the server

client.close()
```

### Multiple argument

This example uses the `getDaysBetween` function in the module `example.lua`. See [Manage UDFs](https://aerospike.com/docs/develop/client/python/usage/udf/manage) for `example.lua` code and information on registering the UDF.

This compares two dates, provided by passing the bin names with the date values, and returns the days between. The following example returns the days between the sighting occurrence and posting to the site.

```python
# Creates a key with the namespace "sandbox", set "ufodata", and user key 5000

key = ('sandbox', 'ufodata', 5000)

# Execute the UDF

result = client.apply(key, 'example', 'getDaysBetween', ['occurred', 'posted'])

print(result, ' days between occurrence and post')

# Close the connection to the server

client.close()
```

## Batch operation with a UDF

::: note
Server version 6.0.0 and above is required for batch UDF operations
:::

This example uses the multi-argument example from above, and apply it to a batch of records.

```python
# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Execute the UDF

batchRecords = client.batch_apply(keys, 'example', 'getDaysBetween', ['occurred', 'posted'])

# Access the records

for batchRecord in batchRecords.batch_records:

    (key, meta, bins) = batchRecord.record

    # Do something

    print(bins['SUCCESS'], 'days between occurrence and post')

# Close the connection to the server

client.close()
```

## Background query with a UDF

This example will use the single argument example from above, and apply it to all records that match a Filter Expression through a background query.

```python
# Build the expression

expr = exp.BinExists('posted').compile()

# Create new write policy

write_policy = {'expressions': expr}

# Create the query

query = client.query('sandbox', 'ufodata')

# Add the UDF to the query

query.apply('example', 'setRecent', [20210101])

# Execute the query

id = query.execute_background()

# Return the query status

job_info = client.job_info(id, aerospike.JOB_QUERY)

def query_status(x):

    return{

        0: 'Query not found',

        1: 'Query in progress, ' + str(job_info['progress_pct']) + '% complete',

        2: 'Query complete, ' + str(job_info['records_read']) + ' records read'

    }[x]

print(query_status(job_info['status']))

# Close the connection to the server

client.close()
```

## Code block

Expand this section for a single code block to apply a record UDF

```python
import aerospike

from aerospike_helpers import expressions as exp

# Define host configuration

config = {

    'hosts': [ ('127.0.0.1', 3000) ]

}

# Establishes a connection to the server

client = aerospike.client(config)

# Creates a key with the namespace "sandbox", set "ufodata", and user key 5000

key = ('sandbox', 'ufodata', 5000)

# Execute the UDF

result = client.apply(key, 'example', 'getDaysBetween', ['occurred', 'posted'])

print(result, ' days between occurrence and post')

# Close the connection to the server

client.close()
```