Last() function returns a different value each time I submit the script

The below code filters, keeps some columns and then tries to get the most recent value. But each time I click “submit” I get a different value.

Am I misunderstanding how last() works?

from(bucket: "test_bucket_untagged")
  |> range(start: 0)
  |> filter(fn: (r) => r["_measurement"] == "data")
  |> filter(fn: (r) => r["host"] == "2302")
  |> filter(fn: (r) => (r["_field"] =~ /Alarm/) and not (r["_field"] =~/SP/))
  |> keep(columns: ["_time", "_value", "alarmState"])
  |> last()

The behavior you’re experiencing could be due to the nature of the last() function in Flux and how your query interacts with your data. Here’s an analysis and potential causes of the issue:

Understanding last() in Flux
The last() function returns the last record in the input table based on the sort order of the data.
If the input data is not explicitly sorted by _time (or another column), the result of last() might be inconsistent because the order of the data in the table can vary.
Potential Causes of Inconsistency
Data Order:

If the data in test_bucket_untagged is not inherently sorted by _time, the last() function might return different results depending on the default order of the data when it is retrieved.
Duplicate Timestamps:

If multiple records have the same _time value, last() may return different records because it does not specify how to handle ties.
Concurrent Data Writes:

If new data is being written to test_bucket_untagged while your query is running, the results might vary depending on the state of the database at the time of execution.
Incomplete Filtering:

The filter operations might return slightly different subsets of the data if the data changes or if there is a mismatch in filtering logic.

2 Likes