How to join 2 collections using MapReduce in C#?

两盒软妹~` 提交于 2019-12-07 19:55:04

问题


In order to join two datasets I tried to translate this example to C# the following way:

I would be very thankful if anyone of you could suggest the appropriate code modification in order to achieve the same result as the example.


回答1:


The solution which produces the same results as this example is the following:

class Program
{
    static void Main(string[] args)
    {
        var connectionString = "mongodb://localhost";
        var client = new MongoClient(connectionString);
        var server = client.GetServer();
        var database = server.GetDatabase("mr_demo");
        var cLifeExpectancy = database.GetCollection("life_expectancy");
        var cEconomicAssistance = database.GetCollection("us_economic_assistance");

        var options = new MapReduceOptionsBuilder();
        options.SetOutput(MapReduceOutput.Inline);


        options.SetOutput(MapReduceOutput.Reduce("result"));
        var result = cLifeExpectancy.MapReduce(life_expect_map, r, options);
        result = cEconomicAssistance.MapReduce(us_econ_map, r, options);

        foreach (var record in result.GetResults())
        {
            Console.WriteLine(record);
        }
    }

    private static string life_expect_map =
        @"function() {
            // Simply emit the age and 0 for the dollar amount.
            // The dollar amount will come from the other collection.
            emit(this.country, {life_expectancy: this.age, dollars: 0});
        }";

    private static string us_econ_map =
        @"function() {
            // The data set contains grant amounts going back to 1946.  I
            // am only interested in 2009 grants.
            if (this.FY2009 !== undefined && this.FY2009 !== null) {
                emit(this.country_name, {
                    dollars: this.FY2009,
                    life_expectancy: 0
                });
            }
        }";

    private static string r =
        @"function(key, values) {
            var result = {dollars: 0, life_expectancy: 0};

            values.forEach(function(value) {
                // Sum up all the money from all the 2009 grants for this
                // country (key)
                result.dollars += (value.dollars !== null) ? value.dollars : 0;
                // Only set life expectancy once
                if (result.life_expectancy === 0 &&
                value.life_expectancy !== null
                ) {
                    result.life_expectancy = value.life_expectancy;
                }
            });

            return result;
        }";
}


来源:https://stackoverflow.com/questions/14022606/how-to-join-2-collections-using-mapreduce-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!