Language
C#
Article For
3.0 3.5 4.0 4.1 5.1

Indexes: Map-Reduce Indexes

Map-Reduce indexes allow you to perform complex aggregations of data. The first stage, called the map, runs over documents and extracts portions of data according to the defined mapping function(s). Upon completion of the first phase, reduction is applied to the map results and the final outcome is produced.

The idea behind map-reduce indexing is that aggregation queries using such indexes are very cheap. The aggregation is performed only once and the results are stored inside the index. Once new data comes into the database or existing documents are modified, the map-reduce index will keep the aggregation results up-to-date. The aggregations are never done during querying to avoid expensive calculations that could result in severe performance degradation. When you make the query, RavenDB immediately returns the matching results directly from the index.

For a more in-depth look at how map reduce works, you can read this post: RavenDB 4.0 Unsung Heroes: Map/reduce.

Creating

When it comes to index creation, the only difference between simple indexes and the map-reduce ones is an additional reduce function defined in index definition. To deploy an index we need to create a definition and deploy it using one of the ways described in the creating and deploying article.

Example I - Count

Let's assume that we want to count the number of products for each category. To do it, we can create the following index using LoadDocument inside:

public static class Products_ByCategory extends AbstractIndexCreationTask {
    public static class Result {
        private String category;
        private String count;

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getCount() {
            return count;
        }

        public void setCount(String count) {
            this.count = count;
        }
    }

    public Products_ByCategory() {
        map = "docs.Products.Select(product => new { " +
            "    Product = Product, " +
            "    CategoryName = (this.LoadDocument(product.Category, \"Categories\")).Name " +
            "}).Select(this0 => new { " +
            "    Category = this0.CategoryName, " +
            "    Count = 1 " +
            "})";

        reduce = "results.GroupBy(result => result.Category).Select(g => new { " +
            "    Category = g.Key, " +
            "    Count = Enumerable.Sum(g, x => ((int) x.Count)) " +
            "})";
    }
}
public static class Products_ByCategory extends AbstractJavaScriptIndexCreationTask {
    public Products_ByCategory() {
        setMaps(Sets.newHashSet("map('products', function(p){\n" +
            "            return {\n" +
            "                Category: load(p.Category, 'Categories').Name,\n" +
            "                Count: 1\n" +
            "            }\n" +
            "        })"));

        setReduce("groupBy(x => x.Category)\n" +
            "    .aggregate(g => {\n" +
            "        return {\n" +
            "            Category: g.key,\n" +
            "            Count: g.values.reduce((count, val) => val.Count + count, 0)\n" +
            "        };\n" +
            "    })");
    }
}

and issue the query:

List<Products_ByCategory.Result> results = session
    .query(Products_ByCategory.Result.class, Products_ByCategory.class)
    .whereEquals("Category", "Seafood")
    .toList();
from 'Products/ByCategory'
where Category == 'Seafood'

The above query will return one result for Seafood with the appropriate number of products from that category.

Example II - Average

In this example, we will count an average product price for each category. The index definition:

public static class Products_Average_ByCategory extends AbstractIndexCreationTask {
    public static class Result {
        private String category;
        private double priceSum;
        private double priceAverage;
        private int productCount;

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public double getPriceSum() {
            return priceSum;
        }

        public void setPriceSum(double priceSum) {
            this.priceSum = priceSum;
        }

        public double getPriceAverage() {
            return priceAverage;
        }

        public void setPriceAverage(double priceAverage) {
            this.priceAverage = priceAverage;
        }

        public int getProductCount() {
            return productCount;
        }

        public void setProductCount(int productCount) {
            this.productCount = productCount;
        }
    }

    public Products_Average_ByCategory() {
        map = "docs.Products.Select(product => new { " +
            "    Product = Product, " +
            "    CategoryName = (this.LoadDocument(product.Category, \"Categories\")).Name " +
            "}).Select(this0 => new { " +
            "    Category = this0.CategoryName, " +
            "    PriceSum = this0.Product.PricePerUnit, " +
            "    PriceAverage = 0, " +
            "    ProductCount = 1 " +
            "})";

        reduce = "results.GroupBy(result => result.Category).Select(g => new { " +
            "    g = g, " +
            "    ProductCount = Enumerable.Sum(g, x => ((int) x.ProductCount)) " +
            "}).Select(this0 => new { " +
            "    this0 = this0, " +
            "    PriceSum = Enumerable.Sum(this0.g, x0 => ((decimal) x0.PriceSum)) " +
            "}).Select(this1 => new { " +
            "    Category = this1.this0.g.Key, " +
            "    PriceSum = this1.PriceSum, " +
            "    PriceAverage = this1.PriceSum / ((decimal) this1.this0.ProductCount), " +
            "    ProductCount = this1.this0.ProductCount " +
            "})";
    }
}
public static class Product_Average_ByCategory extends AbstractJavaScriptIndexCreationTask {
    public Product_Average_ByCategory() {
        setMaps(Sets.newHashSet("map('products', function(product){\n" +
            "    return {\n" +
            "        Category: load(product.Category, 'Categories').Name,\n" +
            "        PriceSum: product.PricePerUnit,\n" +
            "        PriceAverage: 0,\n" +
            "        ProductCount: 1\n" +
            "    }\n" +
            "})"));

        setReduce("groupBy(x => x.Category)\n" +
            "        .aggregate(g => {\n" +
            "          var pricesum = g.values.reduce((sum,x) => x.PriceSum + sum,0);\n" +
            "          var productcount = g.values.reduce((sum,x) => x.ProductCount + sum,0);\n" +
            "          return {\n" +
            "            Category: g.key,\n" +
            "            PriceSum: pricesum,\n" +
            "            ProductCount: productcount,\n" +
            "            PriceAverage: pricesum / productcount\n" +
            "          }\n" +
            "        })");
    }
}

and the query:

List<Products_Average_ByCategory.Result> results = session
    .query(Products_Average_ByCategory.Result.class, Products_Average_ByCategory.class)
    .whereEquals("Category", "Seafood")
    .toList();
from 'Products/Average/ByCategory'
where Category == 'Seafood'

Example III - Calculations

This example illustrates how we can put some calculations inside an index using on one of the indexes available in the sample database (Product/Sales).

We want to know how many times each product was ordered and how much we earned for it. In order to extract that information, we need to define the following index:

public static class Product_Sales extends AbstractIndexCreationTask {
    public static class Result {
        private String product;
        private int count;
        private double total;

        public String getProduct() {
            return product;
        }

        public void setProduct(String product) {
            this.product = product;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public double getTotal() {
            return total;
        }

        public void setTotal(double total) {
            this.total = total;
        }
    }

    public Product_Sales() {
        map = "docs.Orders.SelectMany(order => order.Lines, (order, line) => new { " +
            "    Product = line.Product, " +
            "    Count = 1, " +
            "    Total = (((decimal) line.Quantity) * line.PricePerUnit) * (1M - line.Discount) " +
            "})";


        reduce = "results.GroupBy(result => result.Product).Select(g => new { " +
            "    Product = g.Key, " +
            "    Count = Enumerable.Sum(g, x => ((int) x.Count)), " +
            "    Total = Enumerable.Sum(g, x0 => ((decimal) x0.Total)) " +
            "})";
    }
}
public static class Product_Sales extends AbstractJavaScriptIndexCreationTask {
    public Product_Sales() {
        setMaps(Sets.newHashSet("map('orders', function(order){\n" +
            "            var res = [];\n" +
            "            order.Lines.forEach(l => {\n" +
            "              res.push({\n" +
            "                Product: l.Product,\n" +
            "                Count: 1,\n" +
            "                Total:  (l.Quantity * l.PricePerUnit) * (1- l.Discount)\n" +
            "              })\n" +
            "            });\n" +
            "            return res;\n" +
            "        })"));

        setReduce("groupBy(x => x.Product)\n" +
            "    .aggregate(g => {\n" +
            "        return {\n" +
            "            Product : g.key,\n" +
            "            Count: g.values.reduce((sum, x) => x.Count + sum, 0),\n" +
            "            Total: g.values.reduce((sum, x) => x.Total + sum, 0)\n" +
            "        }\n" +
            "    })");
    }
}

and send the query:

List<Product_Sales.Result> results = session
    .query(Product_Sales.Result.class, Product_Sales.class)
    .toList();
from 'Product/Sales'

Reduce Results as Artificial Documents

Map-Reduce Output Documents

In addition to storing the aggregation results in the index, the map-reduce index can also output those reduce results as documents to a specified collection. In order to create these documents, called "artificial", you need to define the target collection using the outputReduceToCollection property in the index definition.

Writing map-reduce outputs into documents allows you to define additional indexes on top of them that give you the option to create recursive map-reduce operations. This makes it cheap and easy to, for example, recursively create daily, monthly, and yearly summaries on the same data.

In addition, you can also apply the usual operations on artificial documents (e.g. data subscriptions or ETL).

If the aggregation value for a given reduce key changes, we overwrite the output document. If the given reduce key no longer has a result, the output document will be removed.

Reference Documents

To help organize these output documents, the map-reduce index can also create an additional collection of artificial reference documents. These documents aggregate the output documents and store their document IDs in an array field ReduceOutputs.

The document IDs of reference documents are customized to follow some pattern. The format you give to their document ID also determines how the output documents are grouped.

Because reference documents have well known, predictable IDs, they are easier to plug into indexes and other operations, and can serve as an intermediary for the output documents whose IDs are less predictable. This allows you to chain map-reduce indexes in a recursive fashion, see Example II.

Learn more about how to configure output and reference documents in the Studio: Create Map-Reduce Index.

Artificial Document Properties

IDs

The identifiers of map reduce output documents have three components in this format:

<Output collection name>/<incrementing value>/<hash of reduce key values>

The index in Example I might generate an output document ID like this:

DailyProductSales/35/14369232530304891504

  • "DailyProductSales" is the collection name specified for the output documents.
  • The middle part is an incrementing integer assigned by the server. This number grows by some amount whenever the index definition is modified. This can be useful because when an index definition changes, there is a brief transition phase when the new output documents are being created, but the old output documents haven't been deleted yet (this phase is called "side-by-side indexing"). During this phase, the output collection contains output documents created both by the old version and the new version of the index, and they can be distinguished by this value: the new output documents will always have a higher value (by 1 or more).
  • The last part of the document ID (the unique part) is the hash of the reduce key values - in this case: hash(Product, Month).

The identifiers of reference documents follow some pattern you choose, and this pattern determines which output documents are held by a given reference document.

The index in Example I has this pattern for reference documents:

sales/daily/{Date:yyyy-MM-dd}

And this produces reference document IDs like this:

sales/daily/1998-05-06

The pattern is built using the same syntax as the StringBuilder.AppendFormat method. See here to learn about the date formatting in particular.

Metadata

Artificial documents generated by map-reduce indexes get the following @flags in their metadata:

"@flags": "Artificial, FromIndex"

These flags are used internally by the database to filter out artificial documents during replication.

Syntax

The map-reduce output documents are configured with these properties of IndexDefinition:

private String outputReduceToCollection;

private String patternReferencesCollectionName;

private String patternForOutputReduceToCollectionReferences;
Parameters Type Description
outputReduceToCollection String Collection name for the output documents.
patternReferencesCollectionName String Optional collection name for the reference documents - by default it is <outputReduceToCollection>/References.
patternForOutputReduceToCollectionReferences String Document ID format for reference documents. This ID references the fields of the reduce function output, which determines how the output documents are aggregated. The type of this parameter is different depending on if the index is created using IndexDefinition or AbstractIndexCreationTask.

Examples

Example I

Here is a map-reduce index with output documents and reference documents:

public Product_Sales_ByMonth() {
    map = "docs.Orders.SelectMany(order => order.Lines, (order, line) => new { " +
        "    Product = line.Product, " +
        "    Month = new DateTime(order.OrderedAt.Year, order.OrderedAt.Month, 1), " +
        "    Count = 1, " +
        "    Total = (((decimal) line.Quantity) * line.PricePerUnit) * (1M - line.Discount) " +
        "})";

    reduce = "results.GroupBy(result => new { " +
        "    Product = result.Product, " +
        "    Month = result.Month " +
        "}).Select(g => new { " +
        "    Product = g.Key.Product, " +
        "    Month = g.Key.Month, " +
        "    Count = Enumerable.Sum(g, x => ((int) x.Count)), " +
        "    Total = Enumerable.Sum(g, x0 => ((decimal) x0.Total)) " +
        "})";

    outputReduceToCollection = "MonthlyProductSales";
    patternReferencesCollectionName = "DailyProductSales/References";
    patternForOutputReduceToCollectionReferences = "sales/daily/{Date:yyyy-MM-dd}";
}
    }
public static class Product_Sales_ByMonth extends AbstractJavaScriptIndexCreationTask {
    public Product_Sales_ByMonth() {
        setMaps(Sets.newHashSet("map('orders', function(order){\n" +
            "            var res = [];\n" +
            "            order.Lines.forEach(l => {\n" +
            "            res.push({\n" +
            "                Product: l.Product,\n" +
            "                Month: new Date( (new Date(order.OrderedAt)).getFullYear(),(new Date(order.OrderedAt)).getMonth(),1),\n" +
            "                Count: 1,\n" +
            "                Total: (l.Quantity * l.PricePerUnit) * (1- l.Discount)\n" +
            "            })\n" +
            "        });\n" +
            "        return res;\n" +
            "    })"));

        setReduce("groupBy(x => ({Product: x.Product, Month: x.Month}))\n" +
            "    .aggregate(g => {\n" +
            "        return {\n" +
            "            Product: g.key.Product,\n" +
            "            Month: g.key.Month,\n" +
            "            Count: g.values.reduce((sum, x) => x.Count + sum, 0),\n" +
            "            Total: g.values.reduce((sum, x) => x.Total + sum, 0)\n" +
            "        }\n" +
            "    })");

        setOutputReduceToCollection("MonthlyProductSales");
        setPatternReferencesCollectionName("DailyProductSales/References");
        setPatternForOutputReduceToCollectionReferences("sales/daily/{Date:yyyy-MM-dd}");
    }
}

In the LINQ index example above (which inherits AbstractIndexCreationTask), the reference document ID pattern is set with a lambda expression:

PatternForOutputReduceToCollectionReferences = "sales/daily/{Date:yyyy-MM-dd}";

This gives the reference documents IDs in this general format: sales/monthly/1998-05-01. The reference document with that ID contains the IDs of all the output documents from the month of May 1998.

In the JavaScript index example (which uses IndexDefinition), the reference document ID pattern is set with a String:

PatternForOutputReduceToCollectionReferences ("sales/daily/{Date:yyyy-MM-dd})"

This gives the reference documents IDs in this general format: sales/daily/1998-05-06. The reference document with that ID contains the IDs of all the output documents from May 6th 1998.

Remarks

Saving documents

Artificial documents are stored immediately after the indexing transaction completes.

Recursive indexing loop

It's forbidden to output reduce results to the collection that:

  • the current index is already working on (e.g. index on DailyInvoices collections outputs to DailyInvoices),
  • the current index is loading a document from it (e.g. index has LoadDocument(id, "Invoices") outputs to Invoices),
  • it is processed by another map-reduce index that outputs results to a collection that the current index is working on (e.g. one index on Invoices collection outputs to DailyInvoices, another index on DailyInvoices outputs to Invoices)

Since that would result in the infinite indexing loop (the index puts an artificial document that triggers the indexing and so on), you will get the detailed error on attempt to create such invalid construction.

Existing collection

Creating a map-reduce index which defines the output collection that already exists and it contains documents will result in an error. You need to delete all documents from the relevant collection before creating the index or output the results to a different one.