CouchDB - last log filter for each registered instance from the list

I could use some help filtering various values ​​from the couchdb view. I have a database that stores logs with information about computers. Periodically, new logs for the computer are recorded in db.

In a slightly simplistic way, I store entries like these:

{
   "name": "NAS",
   "os": "Linux",
   "timestamp": "2011-03-03T16:26:39Z",
}
{
   "name": "Server1",
   "os": "Windows",
   "timestamp": "2011-02-03T19:31:31Z",
}
{
   "name": "NAS",
   "os": "Linux",
   "timestamp": "2011-02-03T18:21:29Z",
}

So far I am trying to filter this list with separate entries. What I would like to get is the last log file for each device.

I have a view like this:

function(doc) {
    emit([doc.timestamp,doc.name], doc);
}

Im requesting this view using python (couchdbkit) and the best solution I came up with is like this:

def get_latest_logs(cls):
    unique_names = []
    unique = []
    for log in cls.view("logs/timestamp", descending=True):
        if log.name not in unique_names:
            unique_names.append(log.name)
            unique.append(log)
    return unique

... . , , python ( ).

, ,   , .

, , , - ( couchdb) , .

, Andreas

+3
1

. CouchDB, .

reduce , - . . . . ! , ( ). .

, . . . group. , . ( .)

-, , . value - .

function(doc) {
    emit(doc.name, doc);
}

, . ( ), ! - (- group).

function(keys, vals, re) {
    var challenger, winner = null;
    for(var a = 0; a < vals.length; a++) {
        challenger = vals[a];
        if(!winner) {
            // The title is unchallenged. This value is the winner.
            winner = challenger;
        } else {
            // Fight!
            if(winner.name !== challenger.name) {
                // Stop the fight! He gonna kill him!
                return null; // With a grouping query, this will never happen.
            } else if(winner.timestamp > challenger.timestamp) {
                // The champ wins! (Nothing to do.)
            } else {
                // The challenger wins!
                winner = challenger;
            }
        }
    }

    // Today champion lives to fight another day.
    return winner;
}

( , , , . , , Date.)

, ?group=true, CouchDB ( ) key, .

( , . emit([doc.name, doc.timestamp], doc). , ?reduce=false&startkey=["NAS", null]&endkey=["NAS", {}] ?group_level=1.

, " " . . , , , ​​ , - .

+6

Source: https://habr.com/ru/post/1796372/


All Articles