MongoDB自带MapReduce功能和用spring-data实现MapReduce

Spring Data(一)|什么是Spring Data 理解 介绍 Spring Data的使命是为数据访问提供熟悉且一致的基于Spring的编程模型,同时仍保留底层数据存储的特​​殊特性。 它使数据访问技术,关系数据库和非关系数据库,map-reduce框架和基于云的数据服务变得简单易用。这是一个伞形项目,其中包含许多特定于给定数据库的子项目。这些项目是通过与这些激动人心的技术背后的许多公司和开发人员合作开发的。 特征 强大的存储库和自定义对象映射抽... 阅读详情

一、使用MongoDB自带shell完成MapReduce。

1、首先插入测试数据。

use test
db.mapreduce.insert({"_id":"1","x":["a","b"]})
db.mapreduce.insert({"_id":"2","x":["b","c"]})
db.mapreduce.insert({"_id":"3","x":["c","d"]})

使用test数据库,在mapreduce collection的表中插入3条数据

使用

db.mapreduce.find()

查看数据中数据。如果有MongoVue也可以使用工具查看,

2、编写Map函数和Reduce函数

Map函数:

var m = function(){
  for(var i = 0; i < this.x.length; i++){
    emit(this.x[i],1);
  }
}

Map函数调用emit(key,value)遍历collection中所有记录,将key与value传递给Reduce函数进行处理。使用this访问当前处理的document。

Reduce函数:

var r = function(key,values){
  var sum = 0;
  for(var i = 0; i < values.length; i++)
    sum += values[i];
  return sum;
}

Reduce函数接受的参数类似Group效果,将Map返回的键值序列组合成{key:[value1,value2,value...]}传递给reduce,在本例中组成{a:[1],b:[1,1],c:[1,1],d:[1]}

3、通过db.runCommand来执行MapReduce操作:

var res = db.runCommand({
 mapreduce:"mapreduce",
 map:m, reduce:r, 
 out:"mapreduce_out"});

mapreduce参数传入对应的collection名,map参数传入Map函数,out为输出的collection名,会在数据库中另外建一张表来保存处理后的结果。这是几个最基本的参数,还有更多参数可以查看Mongo实战,在我资源中有。也可以自己去网上找找。

最后的结果是:
{ "_id" : "a", "value" : 1 }
{ "_id" : "b", "value" : 2 }
{ "_id" : "c", "value" : 2 }
{ "_id" : "d", "value" : 1 }

可以通过

db.mapreduce_out.find()

查看。
 

 

二、使用spring-data-mongodb进行MapReduce

spring-data-mongodb是Apache公司方便javaer操纵mongodb的包。英文文档在我的资源中也有。基本的思想就是拿到MongoTemplete句柄,然后对mongodb进行操作。

1、存入测试数据,可以用shell直接存入,也可以用java代码。

2、定义一个实体类去存贮

public class ValueObject {
  private String id;
  private float value;

  public String getId() {
    return id;
  }
  public float getValue(){
    return value;
  }
  public void setValue(float value) {
    this.value = value;
  }
}

3、Mapreduce

   其实关键代码就一行:

package mongo_repository.mongo_repository;
import java.net.UnknownHostException;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;

import com.mongodb.Mongo;

public class MapReduce {
	public static void main(String[] args) throws UnknownHostException {
		MongoOperations mongoOperation = new MongoTemplate(new Mongo("localhost"), "test");
		String map  = "function () {for(var i=0;i<this.x.length;i++){emit(this.x[i],1);}}";
		String reduce = "function(key, values){ var sum = 0; for(var i = 0; i<values.length;i++ )sum += values[i]; return sum; }";
                //参数分别为:collection名,map函数的字符串,reduce函数的字符串,输出的表名[可选],实体类
		MapReduceResults<ValueObject> results = mongoOperation.mapReduce("mapreduce", map, reduce,new MapReduceOptions().outputCollection("mr_out"), ValueObject.class);
	}
}

暂时做一个这么简单的例子,其实mapreduce还可以做更复杂的功能,更详细的参数设定可以去看官方文档。

 

 


 

SpringCloud集成Spring Data MongoDB 文章目录MongoDB源码spring-mongodb运行 MongoDB   MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案的非关系型数据库。   MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。   MongoDB这种非关系型数据库与我们应用的最广泛的传... 阅读详情

相关推荐

MongoDB中MapReduce的使用方法详解

MapReduce应该算是MongoDB操作中比较复杂的了,下面这篇文章主要给大家介绍了关于MongoDB中MapReduce使用的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起看看吧。

MongoDB mapReduce和Spring Data配合使用详解

经过几天的折腾, 终于弄明白了MongoDB mapReduce在和Spring Data配合使用的方法,简单来说,首先要弄清楚什么是Map Reduce,为什么我们要用map reduce做统计,一般来说, 对应sql语句的group by的场景,都需要用到map reduce。 map reduce的map函数和reduce函数都是javascript写的,因此先要在mongo client先...

caodaoxi的专栏 203

1.安装EMQX服务器

阿里云;EMQX

hfh8130的博客 5319

MongodbMapReduce的简单使用

MongodbMapReduced的简单使用简单理解:mongodb shell原数据mongo shell 执行结果springboot 使用mongodb MapReduceJava代码执行结果 简单理解: mongodb 的mapReduce 很类似于分组语句(group by) ,map 函数按照key进行分组而后reduce函数进行计算。reduce的语法是类似于JavaScript,不知道在哪看到的。因为用的少,所以很复杂的用法不是很清楚,但是如果是使用分组聚合操作,那么使用MapReduce是

Myueye的博客 789

LLC谐振电路增益公式推导

LLC谐振电路增益公式理解

金凯*博客 1万+

ICESat-2数据下载的两种方法

ICESat-2数据下载

weixin_46341898的博客 2912

一篇文章带你搞定 MongoDB 中 MapReduce 使用

玩过 Hadoop 的小伙伴对 MapReduce 应该不陌生,MapReduce 的强大且灵活,它可以将一个大问题分解为多个小问题,将各个小问题发送到不同的机器上去处理,所有的机器都完成计算后,再将计算结果合并为一个完整的解决方案,这就是所谓的分布式计算。此处我们就来看看 MongoDB 中 MapReduce 的使用。 文章目录一、mapReduce二、runCommand 实现 一、mapReduce MongoDB 中的 MapReduce 可以用来实现更复杂的聚合命令,使用 MapReduce 主

南淮北安的博客 3491

numeca linux 11,NUMECA FINE/Turbo16下载-NUMECA FINE/Turbo16官方版v16.0 最新版 - 起点软件园...

NUMECA FINE/Turbo16,空气动力学模拟工具,帮助小伙伴随时仿真模拟,让小伙伴可以模拟出最真实的环境,让小伙伴可以轻松完成环境模拟的服务,帮助小伙伴更好的解决自己的课题研究!NUMECA FINE/Turbo16说明1、支持在64位WINDOWS操作系统和LINUX操作系统下运行2、基于全二阶精度的数值格式,保证了计算精度3、采用先进的全多重网格技术和基于密度的求解方法保证了快速的流...

weixin_39858298的博客 1640

Altium Designer 20.2 高效PCB设计技巧:从安装到出GERBER全流程

PCB设计是电子工程中的核心环节,而Altium Designer作为业界主流的电子设计自动化工具,其稳定性和可扩展性深受工程师信赖。合理运用设计工具的原理与功能,能显著提升从原理图绘制到电路板布线的整体效率。在实际工程中,掌握DRC检查、元件库管理、交互式布线等基础操作,是保证设计质量与可制造性的关键。面对生产交付阶段,GERBER文件的输出规范与自检流程更直接关系到打样成败。本文从软件安装环境适配、工程文件瘦身、快捷键配置等日常高频场景切入,系统梳理了一套覆盖全流程的PCB设计实践策略,帮助工程师规避常

weixin_34221112的博客 374

什么是论文的创新点?公式化描述算是创新点吗?

写科研论文时,挑战之一就是如何让你的工作“脱颖而出”,也就是要有创新性。不管实验多么精确、推导多么复杂,若没有真正的创新,论文很可能会被拒。关于如何创新问题上,我最近在看刘雪峰老师的《科技论文写作指南》,看到了很多关于写作的新论述,在这里和大家进行分享。

加百力 的技术博客 1934

大数据领域数据产品的交通运输行业应用

您是否经历过早高峰被堵在桥上,看着导航显示“前方5公里缓行”却无能为力?是否见过货车司机绕远路导致成本飙升?这些“交通痛点”的背后,是传统交通管理依赖经验决策的局限。本文将聚焦“大数据数据产品”这一核心工具,从技术原理到实际应用,全面解析它如何为交通运输行业“开天眼”,解决从城市拥堵到物流效率的一系列难题。本文将按照“问题引入→概念拆解→技术原理→实战案例→应用场景→未来趋势”的逻辑展开,用生活化比喻降低理解门槛,用代码和数学模型提升专业性,最终帮您建立“大数据+交通”的完整认知框架。交通数据。

操作系统内核探秘的博客 241

mongoDB实现MapReduce

一、MongoDB Map Reduce Map-Reduce是一种计算模型,简单的说就是将大批量的工作(数据)分解(MAP)执行,然后再将结果合并成最终结果(REDUCE)。MongoDB提供的Map-Reduce非常灵活,对于大规模数据分析也相当实用。 基本语法: db.collection.mapReduce( function() {emit(key,value);}, ...

weixin_30251587的博客 489

【WRF-Urban数据集】中国60个城市的1 km分辨率城市冠层参数(UCPs)

中国60个城市的1 km分辨率城市冠层参数(UCPs)

WW、forever的博客 1073

MongoDB mapReduce和Spring Data配合使用详解

经过几天的折腾, 终于弄明白了MongoDB  mapReduce在和Spring Data配合使用的方法,简单来说,首先要弄清楚什么是Map Reduce,为什么我们要用map reduce做统计,一般来说, 对应sql语句的group by的场景,都需要用到map reduce。 map reduce的map函数和reduce函数都是javascript写的,因此先要在mongo client

西涛offbye-移动全栈技术博客 7026

【WorkBuddy从入门到精通实战教程】实战案例 第 41 章 论文阅读与文献综述

本文系统讲解如何用WorkBuddy高效阅读论文并撰写文献综述。针对“读了一天没记住”的痛点,提出“三遍阅读法”:快速评估相关性、结构化提炼核心内容、批判性分析局限。结合提示词工程,实现单篇精读、多篇对比与综述框架搭建,显著提升效率。强调学术诚信,严防AI幻觉,要求所有引用与数据必须回源核对。最终目标是借助AI辅助理解与组织,但坚持自主思考与写作,真正掌握科研能力。

企鹅码农的专属播客,分享10多年的实战案例和经验解读,包含YOLO、RT-DETR、AI等各个工作领域。 158

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Using MongoDB/GridFS and Spring Data

I recently delved into MongoDB for the first time, and albeit I was skeptical at first, I now believe it is my preference to use a NOSQL database over a traditional RDBMS. I rarely just fall in love w

Ryan Z 的技术日志 3606

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

MongoDB - Spring Data MongoTemplate使用

Spring Data MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate类,方便我们通过java代码对MongoDB进行CRUD的操作。 一、增加:save、insert <T> T save(T var1); <T> T save(T var1, String var2); 1. 传入对象,不传集...

Lupu's journey - 生活、分享 1140

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java连接MongoDB所需要实现得 org.springframework.data.mongodb.core.mapreduce.GroupBy

分组查询主要使用org.springframework.data.mongodb.core.mapreduce.GroupBy这个spring中的类: 例: GroupBy groupBy = GroupBy.key("logonIp") .initialDocument(initial) .reduceFunction(reduceFunction); GroupByResults<T...

weixin_42726306的博客 1128

mongodb视频课程以及spring data mongodb视频

MongoDB 是一个基于分布式文件存储的数据库。 由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。 MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。 mongodb是目前在IT行业非常流行的一种非关系型数据库(NoSql) 其灵活的数据存储方式,备受当前IT从业人员的青睐 各

u010889990的专栏 3075

mongo java mapreduce_[Spring Data MongoDB]学习笔记--MapReduce

mongodb的MapReduce主要包含两个方法:map和reduce。举个例子,假设现在有下面3条记录{ "_id" : ObjectId("4e5ff893c0277826074ec533"), "x" : [ "a", "b"] }{"_id" : ObjectId("4e5ff893c0277826074ec534"), "x" : [ "b", "c"] }{"_id" : Objec...

weixin_29044157的博客 229

mongodb sum 操作

Mongodb 统计某个字段的和,可以使用聚合函数。 数据结构如下: &gt; db.message.findOne() { "_class" : "com.cyou.appwiki.bean.Message", "_id" : ObjectId("53997f80c451bf833288b882"), "content" : "power9li的回答2",

garyli 2014

spring data简介

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。 Spring Data 包含多个子项目: Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化 Hadoop - 基于 Spring 的 Hadoop 作

刘琦的专栏 857

mongodb 通过MapReduce统计用户Pv Uv

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33964094的博客 439
上一篇: Hbase的基本介绍
下一篇: 使用Android Host模式与Arduino进行通信
hello_java_
博客等级 码龄15年 20粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址