2017-04-24 83 views
0

以下是每幾分鐘10臺設備的記錄。我需要爲每個ID返回唯一的記錄集,每個記錄只應該是最新的。如何使用多個參數過濾json對象?

我該如何使用彈性搜索或任何其他解決方案來做到這一點。

{ 
    {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 
} 
+0

只是爲了澄清,你試圖返回集合對象,每個ID一個,它應該是對象與最新的時間值爲其各自的ID? – Ken

+0

在10000條記錄中,我只會返回10條記錄,其中包含唯一ID和最新/最大時間值。 – DragonKnight

回答

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);

+0

謝謝Ken,但我正在努力通過彈性搜索來解決它,因爲實際問題更復雜。 – DragonKnight

1

我想,你正在尋找這一點,它會給最大time具有獨特id: -

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