Indexes: JavaScript Indexes

This feature was created for users who want to create an index and prefer JavaScript over C#. JavaScript indexes can be defined by a user with lower permissions than the C# indexes (admin not required). All other capabilities and features are the same as C# indexes.

Experimental

This is an experimental feature. To enable it, add the following to your settings.json file:

"Features.Availability": "Experimental"

Creating JavaScript Index

If we want to create JavaScript index we need to create an instance of our class that inherits from AbstractJavaScriptIndexCreationTask.
AbstractJavaScriptIndexCreationTask inherits from AbstractIndexCreationTask (Read more about AbstractIndexCreationTask here.)

public class Employees_ByFirstAndLastName : AbstractJavaScriptIndexCreationTask
{
    // ...
}

Map Index

Map indexes, sometimes referred to as simple indexes, contain one (or more) mapping functions that indicate which fields from the documents should be indexed. They indicate which documents can be searched by which fields.

map(<collection-name>, function (document){
        return {
            // indexed properties go here e.g:
            // Name: document.Name
        };
    })

Example I - Simple Map Index

public class Employees_ByFirstAndLastName : AbstractJavaScriptIndexCreationTask
{
    public Employees_ByFirstAndLastName()
    {
        Maps = new HashSet<string>
        {
            @"map('Employees', function (employee){ 
                    return { 
                        FirstName : employee.FirstName, 
                        LastName : employee.LastName
                    };
                })",
        };
    }
}

Example II - Map Index With Additional Sources

public class BlogPosts_ByCommentAuthor : AbstractJavaScriptIndexCreationTask
{
    public class Result
    {
        public string[] Authors { get; set; }

    }

    public BlogPosts_ByCommentAuthor()
    {
        Maps = new HashSet<string>()
        {
            @"map('BlogPosts', function(b){
                var names = [];
                b.Comments.forEach(x => getNames(x, names));
                return {
                    Authors : names
                };})"
        };
        AdditionalSources = new Dictionary<string, string>
        {
            ["The Script"] = @"function getNames(x, names){
                                names.push(x.Author);
                                x.Comments.forEach(x => getNames(x, names));
                         }"
        };
    }
}

Read more about map indexes here.

Multi Map Index

Multi-Map indexes allow you to index data from multiple collections

Example

public class Animals_ByName : AbstractJavaScriptIndexCreationTask
{
    public Animals_ByName()
    {
        Maps = new HashSet<string>()
        {
            @"map('cats', function (c){ return {Name: c.Name}})",
            @"map('dogs', function (d){ return {Name: d.Name}})"
        };
    }
}

Read more about multi map indexes here.

Map-Reduce Index

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.

groupBy(x => {map properties})
        .aggregate(y => {
            return {
                // indexed properties go here e.g:
                // Name: y.Name
            };
        })

this Keyword

this is bound to the state of our JavaScript interpreter, which has no relevance to creating indexes. Using this is unsupported and may cause undefined behavior.

Example I

public class Products_ByCategory : AbstractJavaScriptIndexCreationTask
{
    public class Result
    {
        public string Category { get; set; }

        public int Count { get; set; }
    }

    public Products_ByCategory()
    {
        Maps = new HashSet<string>()
        {
            @"map('products', function(p){
                return {
                    Category: load(p.Category, 'Categories').Name,
                    Count: 1
                }
            })"
        };

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

Example II

public class Product_Sales_ByMonth : AbstractJavaScriptIndexCreationTask
{
    public class Result
    {
        public string Product { get; set; }

        public DateTime Month { get; set; }

        public int Count { get; set; }

        public decimal Total { get; set; }
    }

    public Product_Sales_ByMonth()
    {
        Maps = new HashSet<string>()
        {
            @"map('orders', function(order){
                    var res = [];
                    order.Lines.forEach(l => {
                        res.push({
                            Product: l.Product,
                            Month: new Date( (new Date(order.OrderedAt)).getFullYear(),(new Date(order.OrderedAt)).getMonth(),1),
                            Count: 1,
                            Total: (l.Quantity * l.PricePerUnit) * (1- l.Discount)
                        })
                    });
                    return res;
                })"
            };

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

        OutputReduceToCollection = "MonthlyProductSales";
    }
}

Read more about map reduce indexes here.

Information

Supported JavaScript version : ECMAScript 5.1