Book Image

ElasticSearch Cookbook

By : Alberto Paro
Book Image

ElasticSearch Cookbook

By: Alberto Paro

Overview of this book

Table of Contents (20 chapters)
ElasticSearch Cookbook Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Counting matched results


It is often required to return only the count of the matched results and not the results themselves. The advantages of using a count request is the performance it offers and reduced resource usage, as a standard search call also returns hits count.

A lot of scenarios involve counting, as follows:

  • To return the number of, for example, posts for a blog or comments for a post.

  • To validate that some items are available. Are there posts? Are there comments?

Getting ready

You need a working ElasticSearch cluster and an index populated with the script chapter_05/populate_query.sh, available in the code bundle for this book.

How to do it...

In order to execute a counting query, perform the following steps:

  1. From the command line, execute a count query:

    curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_count?pretty=true' -d '{"query":{"match_all":{}}}'
    
  2. The following result should be returned by ElasticSearch if everything works all right:

    {
      "count" : 3,
      "_shards" : {
       ...