Anyone have a good solution to sorting by IP address in the correct order? I have a Flux query that is generating just a simple table in Grafana however IP’s are sorted so that the last octet is throwing everything off. For example, when sorting ascending, 10.10.10.10 appears before 10.10.10.1. 10.10.10.20 appears before 10.10.10.2, etc. In MySQL this is easy to do with casting or INET_ATON but can’t seem to find a good solution for Influxv2. Tried a few different transformations in Grafana as well without luck.
Hi @jsmaage
I do not have any test data (or time) right now to test this, but perhaps something like this?
import "array"
from(bucket: "your_bucket")
|> range(start: -1d)
|> filter(fn: (r) => r._measurement == "your_measurement")
|> map(fn: (r) => ({
r with
octet1: int(v: strings.split(v: r.ip, t: ".")[0]),
octet2: int(v: strings.split(v: r.ip, t: ".")[1]),
octet3: int(v: strings.split(v: r.ip, t: ".")[2]),
octet4: int(v: strings.split(v: r.ip, t: ".")[3])
}))
|> sort(columns: ["octet1", "octet2", "octet3", "octet4"])
Another possible solution would be to create a custom function in Flux, such as this:
import "math"
import "strings"
// Function to convert an IP address to a sortable integer
ipToSortableInt = (ip) => {
parts = strings.split(ip, ".")
// Validate IP address format
if length(part=parts) != 4 {
return 0
}
// Convert each octet to an integer and combine
return
int(v: parts[0]) * 256 * 256 * 256 +
int(v: parts[1]) * 256 * 256 +
int(v: parts[2]) * 256 +
int(v: parts[3])
}
from(bucket:"your_bucket")
|> range(start: -1d)
|> filter(fn: (r) => r._measurement == "network_data")
|> group()
|> map(fn: (r) => ({
_time: r._time,
ip: r.ip_address,
sortableIp: ipToSortableInt(ip: r.ip_address)
}))
|> sort(columns: ["sortableIp"])
|> keep(columns: ["_time", "ip"])
Thanks @grant2 I had kind of found the same via Google and GPT but could not get it to work since my IP addresses are tag values and not a field, I should have mentioned that.