1

我设置了带有以下结构箱的 aerospike:项目、时间戳、数量、价格、折扣

我正在尝试实现以下等效 SQL

SELECT item, sum(qty), sum(price), sum(discount)
FROM items
WHERE timestamp between 20150101000000 and 20150101235959 GROUP BY item

我试图编写以下 lua 脚本,但是在执行脚本时出现以下错误

错误:(1)AEROSPIKE_ERR_SERVER:“UDF:执行错误 2:/opt/aerospike /usr/udf/lua/aggregateByItem.lua:21:尝试索引零值”

有人可以帮助解决这个问题

local function aggregate_item_stats(itemMap,rec)
  local item = rec.item
  local innerMap = itemMap[item]
  if innerMap == nil then
        innerMap = {qty = 0, price = 0, discount = 0}
  end
  innerMap.qty = innerMap.qty + (tonumber(rec.qty) or 0);
  innerMap.price = innerMap.price + (tonumber(rec.price) or 0);
  innerMap.discount = innerMap.discount + (tonumber(rec.discount) or 0);
  itemMap[item] = innerMap  
  return itemMap
end

local function fn_merge(a,b)
  a.qty = a.qty + b.qty
  a.price = a.price + b.price
  a.discount = a.discount + b.discount
  return a
end
local function reduce_values(a, b)
  return map.merge(a, b, fn_merge)
end
function highUsageReport(stream)
 return stream : aggregate(itemMap{}, aggregate_item_stats) : reduce(reduce_values)
end
4

1 回答 1

1

The working code is, The major change is at line 4

if innerMap == nil then
to
if innerMap == null then

local function aggregate_item_stats(itemMap, rec)
 local key = rec.item
 local innerMap = itemMap[key] 
 if innerMap == null then
  innerMap = map {qty = 0, price = 0, discount = 0}
 end  
 innerMap.qty = (tonumber(rec.qty) or 0)
 innerMap.price = innerMap.price + tonumber(rec.price or 0)
 innerMap.discount = innerMap.discount + tonumber(rec.discount or 0)
 itemMap[key] = innerMap
 return itemMap
end

local function reduce_values(a, b)
 return map.merge(a, b, fn_merge)
end

local function fn_merge(a, b)
 a.qty = tonumber(a.qty) + tonumber(b.qty)
 a.price = tonumber(a.price) + tonumber(b.price)
 a.discount = tonumber(a.discount) + tonumber(b.discount)
 return a
end

function highUsageReport(stream)
 return stream : aggregate(map(), aggregate_item_stats) 
    : reduce(reduce_values)
end
于 2015-02-05T19:25:46.747 回答