How to Find the Min with Aggregations in Elasticsearch Using NodeJS

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Aggregation is a very powerful functionality in Elasticsearch. In this article we’ll be showing you how to use aggregations to find the minimum value for a field in a dataset. Aggregations can do many things like histograms, sums, or averages but finding the min and max are a good way to get your feet wet with aggregations. Calculating the minimum and maximum are also your most commonly used type of aggregations.

We’ll show you how step-by-step. But if you’d just rather see the example code, scroll to jump to the Just the Code section.

Prerequisites

  • NodeJS Installed.
  • A Node application setup.
  • The elasticsearch npm module installed.
  • Elasticsearch installed and running.

Use the ‘min’ Aggregation

We love to show by example. In this example we use an index representing a small grocery store called store. The store index contains the type products which lists all the stores products. To keep it simple our dataset only has a small number of products with just a few fields including the id, price, quantity, and department. Here is our dataset:

idnamepricequantitydepartment
1Multi-Grain Cereal4.994Packaged Foods
21lb Ground Beef3.9929Meat and Seafood
3Dozen Apples2.4912Produce
4Chocolate Bar1.292Packaged FoodsCheckout
51 Gallon Milk3.2916Dairy
60.5lb Jumbo Shrimp5.2912Meat and Seafood
7Wheat Bread1.295Bakery
8Pepperoni Pizza2.995Frozen
912 Pack Cola5.296Packaged Foods
10Lime Juice0.9920Produce
1112 Pack Cherry Cola5.595Packaged Foods
121 Gallon Soy Milk3.3910Dairy
131 Gallon Vanilla Soy Milk3.499Dairy
141 Gallon Orange Juice3.294Juice

And here is the json we used to make the mapping:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "mappings": {`
        "products": {
            "properties" : {`
                "name": { "type": "text"},
                "price": { "type": "double"},
                "quantity": { "type": "integer"},
                "department": { "type": "keyword"}
            }
        }
    }
}

To demonstrate how to find the minimum we will take our store index and find the product with the lowest quantity in stock. If you look at our data, there are only 2 Chocolate Bars left so we will use that to verify our aggregator worked correctly. Let’s look at the code first and then explain it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var elasticsearch = require("elasticsearch");

var client = new elasticsearch.Client({
  hosts: ["http://localhost:9200"]
});

/* Aggregate Min */
client
  .search({
    index: "store",
    type: "products",
    body: {
      aggs: {
        min_quantity: {
          min: {
            field: "quantity"
          }
        }
      }
    }
  })
  .then(
    function(resp) {
      console.log("Successful query!");
      console.log(resp);
    },
    function(err) {
      console.trace(err.message);
    }
  );
  • First we required the elasticsearch library because it gives us the library of functions that make it easy to access Elasticsearch.
  • Then we created a variable var client which creates and stores our connection to Elasticsearch. From this point on we’ll use this client to do all our interactions with Elasticsearch.
  • We use the search function on the client to create a query with an aggregator.
  • Then we define the aggregator by using the aggs keyword.
  • We gave our aggregator a name min_quantity that can be anything but choose something that makes sense.
  • Then We specify the type of aggregator as min.
  • We specify what field the aggregator should evaluate, quantity.

Now let’s see the result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ node index.js
Successful query!
{ took: 6,
  timed_out: false,
  _shards: { total: 5, successful: 5, skipped: 0, failed: 0 },
  hits:
   { total: 13,
     max_score: 1,
     hits:
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ] },
  aggregations: { min_quantity: { value: 2 } } }

As you can see our min_quantity returned a value of 2 just as we expected.

This is just as easily done for finding the maximum by replacing the min with max.

Conclusion

In this tutorial we demonstrated how to use Elasticsearch aggregations to get the minimum value for a field in a given dataset. Remember that these are the most basic of aggregators and the to explore the myriad of other options available in Elasticsearch. We hope you found tutorial helpful and you can apply it to your specific application. If you have questions or this didn’t work for you please reach out to us so we can help. Thank you.

Just the Code

If you’re already comfortable with NodeJS and aggregations here’s all the code we used to demonstrate how to find the minimum for a given field in our dataset.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var elasticsearch = require("elasticsearch");

var client = new elasticsearch.Client({
  hosts: ["http://localhost:9200"]
});

/* Aggregate Min */
client
  .search({
    index: "store",
    type: "products",
    body: {
      aggs: {
        min_quantity: {
          min: {
            field: "quantity"
          }
        }
      }
    }
  })
  .then(
    function(resp) {
      console.log("Successful query!");
      console.log(resp);
    },
    function(err) {
      console.trace(err.message);
    }
  );

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.