【问题标题】:How to filter json object with multiple parameters?如何过滤具有多个参数的json对象?
【发布时间】:2017-09-21 18:33:23
【问题描述】:

以下是每分钟 10 台设备的记录。我需要为每个 id 返回唯一的记录集,并且每个都应该是最新的。

如何使用弹性搜索或任何其他解决方案来做到这一点会很好。

{
    {id: 1, time: 12345}, 
    {id: 2, time: 12346}, 
    {id: 1, time: 12347}, 
    {id: 2, time: 12348}, 
    {id: 1, time: 12349}, 
    {id: 3, time: 12350}, 
    ... // 10 different ids and 10000 records
}

【问题讨论】:

  • 澄清一下,您正在尝试返回一个对象集合,每个 id 一个对象,它应该是其各自 id 具有最新时间值的对象?
  • @ken 在 10000 条记录中,我将只返回 10 条具有唯一 id 和最新/最大时间值的记录。

标签: javascript angularjs json elasticsearch filter


【解决方案1】:

这是我能得到的最接近的。如果您在原始数据集中说出超过 10 个唯一 ID,不确定如何选择返回哪 10 个结果。

var rawData = [
    {id: 1, time: 12345}, 
    {id: 2, time: 12346}, 
    {id: 1, time: 12347}, 
    {id: 2, time: 12348}, 
    {id: 1, time: 12349}, 
    {id: 3, time: 12350}, 
    {id: 4, time: 12351}, 
    {id: 2, time: 12352}, 
    {id: 7, time: 12353}, 
    {id: 5, time: 12354}, 
    {id: 3, time: 12355}, 
    {id: 6, time: 12356}, 
    {id: 3, time: 12357}, 
    {id: 7, time: 12358}, 
    {id: 6, time: 12359}, 
    {id: 9, time: 12360}
]

var maxSet = {};
// Get all of the max values
rawData.forEach(function (currentValue, index, array) {
  var currentMax = maxSet[currentValue.id] || null;
  if(currentMax) {
    if(currentValue.time > currentMax){
      maxSet[currentValue.id] = currentValue.time;
    }
  } else {
    maxSet[currentValue.id] = currentValue.time;
  }
});
console.log(maxSet);
// Convert back to object if necessary
var keys = Object.keys(maxSet);
var resultObjs = [];
for(var key in keys) {
    resultObjs.push({id: keys[key], time: maxSet[keys[key]]});
}
console.log(resultObjs);

【讨论】:

  • 感谢 Ken,但我正在努力通过弹性搜索来解决它,因为实际问题更复杂。
【解决方案2】:

我想,你正在寻找这个,它会给最大time 和独特的id :-

{
    "_source":false,
    "aggs": {
        "byId": {
            "terms": {
                "field": "id"
            },
            "aggs": {
                "byTime": {
                    "max": {
                        "field": "time"
                    }
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 2019-08-09
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多