dragon87836215 2016-08-23 12:09
浏览 83
已采纳

Aerospike查询返回最高值

I'm trying to create a query for my Aerospike database, that would return the highest value in a specific bin; similar to the way that the MAX() function works in MySQL. For example, if I had a set like this:

+--------------+---------+
| filename     | version |
+--------------+---------+
| alphabet.doc | 4       |
| people.doc   | 2       |
| alphabet.doc | 6       |
| people.doc   | 3       |
+--------------+---------+

What I need is to only return the filename with the highest version number. At the moment I can add a filter like this:

    stmt := db.NewStatement(DBns, DBset, "filename", "version")
    stmt.Addfilter(db.NewEqualFilter("filename", "alphabet.doc"))

    // run database query
    records := runQuery(stmt)

Anyone know how to do this?

  • 写回答

1条回答 默认 最新

  • dongwuqi4243 2016-08-24 16:55
    关注

    You can apply a Lua user-defined function (UDF) to the query to filter the results efficiently.

    E.g. here is a Stream UDF that would return the record with the max. version number:

    function maxVersion(stream, bin)
      -- The stream function cannot return record objects directly,
      -- so we have to map to a Map data type first.
      local function toArray(rec)
        local result = map()
        result['filename'] = rec['filename']
        result['version'] = rec['version']
        return result
      end
      local function findMax(a, b)
        if a.version > b.version then
          return a
        else
          return b
        end
      end
      return stream : map(toArray) : reduce(findMax)
    end
    

    Using the Go client you would execute the function like this:

      stmt := NewStatement(ns, set)
      recordset, _ := client.QueryAggregate(nil, stmt, "udfFilter", "maxVersion")
    
      for rec := range recordset.Results() {
        res := rec.Record.Bins["SUCCESS"].(map[interface{}]interface{})
        fmt.Printf("filename with max. version: %s (ver. %d)
    ", res["filename"], res["version"])
    }
    

    I've uploaded a fully working example as a Gist here: https://gist.github.com/jhecking/b98783bea7564d610ea291b5ac47808c

    You can find more information about how to work with Stream UDFs for query aggregation here: http://www.aerospike.com/docs/guide/aggregation.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置