如何在 PouchDB 上模拟聚合函数 avg、sum、max、min 和 count?

How to simulating the aggregate functions avg, sum, max, min, and count on PouchDB?(如何在 PouchDB 上模拟聚合函数 avg、sum、max、min 和 count?)

本文介绍了如何在 PouchDB 上模拟聚合函数 avg、sum、max、min 和 count?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何在 PouchDB 数据库上创建聚合函数,例如 avg、sum、max 和 min.我创建了一个简单的应用程序来测试 PouchDB.我仍然不知道如何运行这些命令.提前致谢.

Does anyone know how to create aggregate functions, for example avg, sum, max and min on PouchDB database. I created a simple application to test the PouchDB. I'm still not figured out how to run these commands. Thanks in advance.

例如.您如何获得数字"字段的最高、最低或平均值?

For example. How do you get the highest, lowest or average for the "number" field?

我的主要 Ionic 2 组件

My main Ionic 2 component

import {Component} from '@angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
declare var require: any;
var pouch = require('pouchdb');
var pouchFind = require('pouchdb-find');
@Component({
    template: '<ion-nav [root]="rootPage"></ion-nav>'
})
export class MyApp {
    rootPage: any = HomePage;
    db: any;
    value: any;
    constructor(platform: Platform) {
        platform.ready().then(() => {
            StatusBar.styleDefault();
        });
        pouch.plugin(pouchFind);
        this.db = new pouch('friendsdb');
        let docs = [
            {
                '_id': '1',
                'number': 10,
                'values': '1, 2, 3',
                'loto': 'fooloto'
            },
            {
                '_id': '2',
                'number': 12,
                'values': '4, 7, 9',
                'loto': 'barloto'
            },
            {
                '_id': '3',
                'number': 13,
                'values': '9, 4, 5',
                'loto': 'fooloto'
            }
        ];
        this.db.bulkDocs(docs).then(function (result) {
            console.log(result);
        }).catch(function (err) {
            console.log(err);
        });
    }
}
ionicBootstrap(MyApp);

推荐答案

您可以使用 map/reduce 函数 来自 PouchDB 的 db.query() 方法 以获得平均值、总和、最大或任何其他类型的聚合文档.

You can use the map/reduce functions of the db.query() method from PouchDB to get the average, sum, largest or any other kind of aggregation of the docs.

我创建了一个 演示 JSBin fiddle 和一个正在运行的示例.我将函数的解释直接添加到代码中(如下)作为注释,因为我认为它会更简单.

I have created a demo JSBin fiddle with a running example. I added the explanation of the functions directly into the code (below) as comments, as I thought it'd be simpler.

var db = new PouchDB('friendsdb');
var docs = [
      {'_id': '1', 'number': 10, 'values': '1, 2, 3', 'loto': 'fooloto'},
      {'_id': '2', 'number': 12, 'values': '4, 7, 9', 'loto': 'barloto'},
      {'_id': '3', 'number': 13, 'values': '9, 4, 5', 'loto': 'fooloto'}
];

db.bulkDocs(docs).then(function(result) {
  querySum();
  queryLargest();
  querySmallest();
  queryAverage();
}).catch(function(err) {
  console.log(err);
});

function querySum() {
  function map(doc) {
    // the function emit(key, value) takes two arguments
    // the key (first) arguments will be sent as an array to the reduce() function as KEYS
    // the value (second) arguments will be sent as an array to the reduce() function as VALUES
    emit(doc._id, doc.number);
  }
  function reduce(keys, values, rereduce) {
    // keys:
    //   here the keys arg will be an array containing everything that was emitted as key in the map function...
    //   ...plus the ID of each doc (that is included automatically by PouchDB/CouchDB).
    //   So each element of the keys array will be an array of [keySentToTheEmitFunction, _idOfTheDoc]
    //
    // values
    //   will be an array of the values emitted as value
    console.info('keys ', JSON.stringify(keys));
    console.info('values ', JSON.stringify(values));
    // check for more info: http://couchdb.readthedocs.io/en/latest/couchapp/views/intro.html


    // So, since we want the sum, we can just sum all items of the values array
    // (there are several ways to sum an array, I'm just using vanilla for to keep it simple)
    var i = 0, totalSum = 0;
    for(; i < values.length; i++){
        totalSum += values[i];
    }
    return totalSum;
  }
  db.query({map: map, reduce: reduce}, function(err, response) {
    console.log('sum is ' + response.rows[0].value);
  });
}

function queryLargest() {
  function map(doc) {
    emit(doc._id, doc.number);
  }
  function reduce(keys, values, rereduce) {
    // everything same as before (see querySum() above)
    // so, this time we want the larger element of the values array

    // http://stackoverflow.com/a/1379560/1850609
    return Math.max.apply(Math, values);
  }
  db.query({map: map, reduce: reduce}, function(err, response) {
    console.log('largest is ' + response.rows[0].value);
  });
}

function querySmallest() {
  function map(doc) {
    emit(doc._id, doc.number);
  }
  function reduce(keys, values, rereduce) {
    // all the same... now the looking for the min
    return Math.min.apply(Math, values);
  }
  db.query({map: map, reduce: reduce}, function(err, response) {
    console.log('smallest is ' + response.rows[0].value);
  });
}

function queryAverage() {
  function map(doc) {
    emit(doc._id, doc.number);
  }
  function reduce(keys, values, rereduce) {
    // now simply calculating the average
    var i = 0, totalSum = 0;
    for(; i < values.length; i++){
        totalSum += values[i];
    }
    return totalSum/values.length;
  }
  db.query({map: map, reduce: reduce}, function(err, response) {
    console.log('average is ' + response.rows[0].value);
  });
}

注意:这只是一种方法.还有其他几种可能性(不将 ID 作为键发出,使用组和不同的 reduce 函数,使用内置的 reduce 函数,例如 _sum,...),我只是认为一般来说这是更简单的选择.

Note: This is just one way to do it. There are several other possibilities (not emitting IDs as keys, using groups and different reduce functions, using built-in reduce functions, such as _sum, ...), I just thought this was the simpler alternative generally speaking.

这篇关于如何在 PouchDB 上模拟聚合函数 avg、sum、max、min 和 count?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 PouchDB 上模拟聚合函数 avg、sum、max、min 和 count?

基础教程推荐