{"id":125500,"date":"2024-08-12T13:01:06","date_gmt":"2024-08-12T10:01:06","guid":{"rendered":"https:\/\/www.javacodegeeks.com\/?p=125500"},"modified":"2024-08-12T13:01:10","modified_gmt":"2024-08-12T10:01:10","slug":"implementing-an-elasticsearch-aggregation-query-in-java","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html","title":{"rendered":"Implementing an Elasticsearch Aggregation Query in Java"},"content":{"rendered":"<p><a href=\"https:\/\/www.javacodegeeks.com\/2018\/03\/elasticsearch-tutorial-beginners.html\" target=\"_blank\" rel=\"noreferrer noopener\">Elasticsearch<\/a> is a distributed search engine that is designed for scalability, flexibility, and high performance. It allows us to store, search, and analyze large volumes of data quickly. One of its key features is the capability to perform aggregations, allowing us to conduct complex data analysis and extract statistical insights from our indexed data. In this article, we will walk through how to add an aggregation to an Elasticsearch query using Spring Data Elasticsearch.<\/p>\n<h2 class=\"wp-block-heading\">1. Understanding Aggregations<\/h2>\n<p>Aggregations in Elasticsearch are tools that enable us to perform complex data analysis and generate insightful metrics on our indexed data. They work by processing and grouping our data in various ways, allowing us to compute statistics, histograms, and other advanced analytics. <\/p>\n<h3 class=\"wp-block-heading\">1.1 Sample Application Overview<\/h3>\n<p>The sample application used in this article is designed to manage a collection of Product entities, which include fields such as <code>id<\/code>, <code>name<\/code>, <code>category<\/code>, and <code>price<\/code>. The application&#8217;s primary focus is to demonstrate how to perform aggregation queries in Elasticsearch using Spring Data, specifically how to count the number of documents per category.<\/p>\n<p>To create an index named <code>product-items<\/code> in Elasticsearch and add a few documents to it, we will use the <code>curl<\/code> command to interact with Elasticsearch&#8217;s REST API.<\/p>\n<p>First, create the <code>product-items<\/code> index.<\/p>\n<pre class=\"brush:bash\">\ncurl -X PUT \"localhost:9200\/product-items\" -H 'Content-Type: application\/json' -d'\n{\n  \"settings\": {\n    \"number_of_shards\": 1,\n    \"number_of_replicas\": 1\n  }\n}\n'\n<\/pre>\n<p>This command will create an index named <code>product-items<\/code> with one shard and one replica.<\/p>\n<p>Next, add a few documents to the <code>product-items<\/code> index. Each document will represent a product item, with fields like <code>name<\/code>, <code>price<\/code>, and <code>category<\/code>.<\/p>\n<p><strong>Document 1<\/strong><\/p>\n<pre class=\"brush:bash\">\ncurl -X POST \"localhost:9200\/product-items\/_doc\/1\" -H 'Content-Type: application\/json' -d'\n{\n  \"name\": \"Laptop\",\n  \"price\": 999.99,\n  \"category\": \"Electronics\"\n}\n'\n<\/pre>\n<p><strong>Document 2<\/strong><\/p>\n<pre class=\"brush:bash\">\ncurl -X POST \"localhost:9200\/product-items\/_doc\/2\" -H 'Content-Type: application\/json' -d'\n{\n  \"name\": \"Smartphone\",\n  \"price\": 699.99,\n  \"category\": \"Electronics\"\n}\n'\n<\/pre>\n<p><strong>Document 3<\/strong><\/p>\n<pre class=\"brush:bash\">\ncurl -X POST \"localhost:9200\/product-items\/_doc\/3\" -H 'Content-Type: application\/json' -d'\n{\n  \"name\": \"Vans\",\n  \"price\": 399.99,\n  \"category\": \"Clothing\"\n}\n'\n<\/pre>\n<p>To verify that the documents were added successfully, we can retrieve them using a search query:<\/p>\n<pre class=\"brush:bash\">\ncurl -X GET \"localhost:9200\/product-items\/_search\" -H 'Content-Type: application\/json' -d'\n{\n  \"query\": {\n    \"match_all\": {}\n  }\n}\n'\n<\/pre>\n<h3 class=\"wp-block-heading\">1.2 How Aggregations Work<\/h3>\n<p>Aggregations operate on the documents that match a query. Aggregations allow us to perform statistical operations on groups of documents. For instance, we can count the number of documents matching a specific criteria, calculate averages, find minimum and maximum values, or group data based on specific fields.<\/p>\n<h4 class=\"wp-block-heading\">1.2.1 Basic Structure of an Elasticsearch Query with Aggregations<\/h4>\n<p>An Elasticsearch query with aggregations has the following structure:<\/p>\n<pre class=\"brush:java\">\n{\n  \"query\": {\n    \"match_all\": {}\n  },\n  \"aggs\": {\n    \"by_category\": {\n      \"terms\": {\n        \"field\": \"category.keyword\"\n      },\n      \"aggs\": {\n        \"average_price\": {\n          \"avg\": {\n            \"field\": \"price\"\n          }\n        }\n      }\n    }\n  }\n}\n\n<\/pre>\n<p>In this query:<\/p>\n<ul class=\"wp-block-list\">\n<li>The <code>match_all<\/code> query matches all documents.<\/li>\n<li>The <code>terms<\/code> aggregation <code>by_category<\/code> groups documents by the <code>category<\/code> field.<\/li>\n<li>Within each category bucket, an <code>avg<\/code> aggregation <code>average_price<\/code> calculates the average price of products.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">2. Project Setup<\/h2>\n<p>First, we set up a Spring Boot project with the necessary dependencies. In the <code>pom.xml<\/code> file, include the following dependencies:<\/p>\n<pre class=\"brush:xml\">\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-data-elasticsearch&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-web&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.elasticsearch.client&lt;\/groupId&gt;\n            &lt;artifactId&gt;elasticsearch-rest-high-level-client&lt;\/artifactId&gt;\n            &lt;version&gt;7.17.11&lt;\/version&gt;\n        &lt;\/dependency&gt;\n<\/pre>\n<h3 class=\"wp-block-heading\">2.1 Configure Elasticsearch<\/h3>\n<p>Next, we set up Elasticsearch by creating a configuration class.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:java\">\n@Configuration\n@EnableElasticsearchRepositories\npublic class ElasticsearchConfig {\n\n    @Bean\n    public RestClient restHighLevelClient() {\n        return RestClient.builder(\n                new HttpHost(\"localhost\", 9200, \"http\"),\n                new HttpHost(\"localhost\", 9201, \"http\"))\n                .build();\n    }\n\n    @Bean\n    public ElasticsearchClient elasticsearchClient(RestClient restClient) {\n        return ElasticsearchClients.createImperative(restClient);\n    }\n\n    @Bean(name = { \"elasticsearchOperations\", \"elasticsearchTemplate\" })\n    public ElasticsearchOperations elasticsearchOperations(ElasticsearchClient searchClient) {\n\n        ElasticsearchTemplate template = new ElasticsearchTemplate(searchClient);\n        template.setRefreshPolicy(RefreshPolicy.NONE);\n        return template;\n    }\n}\n\n<\/pre>\n<ul class=\"wp-block-list\">\n<li><strong><code>RestClient<\/code> Bean<\/strong>: The <code>RestClient<\/code> is the main client that interacts with Elasticsearch. It is set up to connect to an Elasticsearch cluster running on <code>localhost<\/code> at ports <code>9200<\/code> and <code>9201<\/code>. You can adjust the <code>HttpHost<\/code> values to match your specific Elasticsearch setup.<\/li>\n<li>The <code>ElasticsearchClient<\/code> is a client provided by Elasticsearch. We create the <code>ElasticsearchClient<\/code> by wrapping the <code>RestClient<\/code> using the <code>ElasticsearchClients.createImperative()<\/code> method.<\/li>\n<li><code>ElasticsearchOperations<\/code> is an abstraction provided by Spring Data Elasticsearch, which simplifies the interaction with Elasticsearch. <code>ElasticsearchTemplate<\/code> is an implementation of <code>ElasticsearchOperations<\/code>, leveraging the <code>ElasticsearchClient<\/code> for its operations. <\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">2.2 Create the Model<\/h3>\n<p>Next, let&#8217;s define the <code>Product<\/code> class. This class will represent the documents stored in our Elasticsearch index.<\/p>\n<pre class=\"brush:java\">\n@Document(indexName = \"product-items\")\npublic class Product {\n    \n    @Id\n    private String id;\n    \n    @Field(type = Keyword)\n    private String name;\n    \n    @Field(type = Keyword)\n    private String category;\n    \n    @Field(type = Keyword)\n    private float price;\n\n    public String getId() {\n        return id;\n    }\n\n    public void setId(String id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getCategory() {\n        return category;\n    }\n\n    public void setCategory(String category) {\n        this.category = category;\n    }\n\n    public float getPrice() {\n        return price;\n    }\n\n    public void setPrice(float price) {\n        this.price = price;\n    }   \n}\n<\/pre>\n<p>This code snippet defines a Java class <code>Product<\/code> that is used to map documents in an Elasticsearch index named <code>product-items<\/code> using Spring Data Elasticsearch. The <code>@Document<\/code> annotation specifies that instances of the <code>Product<\/code> class will be indexed in Elasticsearch under the index name <code>product-items<\/code>. <\/p>\n<p>Within the <code>Product<\/code> class, the <code>@Field<\/code> annotations are used to define the type of each field in the Elasticsearch index. In this case, all fields (<code>name<\/code>, <code>category<\/code>, <code>price<\/code>) are of type <code>Keyword<\/code>. The <code>Keyword<\/code> type is suitable for exact matches and aggregations, and is typically used for fields where the value should not be analyzed, such as categories.<\/p>\n<h3 class=\"wp-block-heading\">2.3 Create the Repository<\/h3>\n<p>Next, create an interface to return the number of products grouped by category.<\/p>\n<pre class=\"brush:java\">\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.data.elasticsearch.core.SearchPage;\n\npublic interface ProductItemRepository {\n\n    SearchPage&lt;Product&gt; getProductsCountByCategory(Pageable pageable);\n}\n<\/pre>\n<p>This interface declares a method that will return the number of products grouped by category, with results paginated according to the <code>Pageable<\/code> parameter.<\/p>\n<p>Next, create a repository interface for <code>Product<\/code>: <\/p>\n<pre class=\"brush:java\">\n@Repository\npublic interface ProductRepository extends ElasticsearchRepository&lt;Product, String&gt;, ProductItemRepository {\n\n}\n<\/pre>\n<p>Here, we are extending <code>ElasticsearchRepository&lt;Product, String&gt;<\/code> which is a Spring Data Elasticsearch interface that provides standard CRUD (Create, Read, Update, Delete) operations for the <code>Product<\/code> entity. By extending <code>ProductItemRepository<\/code> interface, the <code>ProductRepository<\/code> inherits the custom method to perform the query on our <code>Product<\/code> entity.<\/p>\n<h3 class=\"wp-block-heading\">2.4 Add Aggregations<\/h3>\n<p>Now, let&#8217;s focus on adding aggregations. We will add a simple aggregation to count the number of products in each category. We will create a service class that uses <code>ElasticsearchOperations<\/code> to execute the aggregation queries.<\/p>\n<pre class=\"brush:java\">\n@Service\npublic class ProductService implements ProductItemRepository {\n\n    @Autowired\n    private ElasticsearchOperations elasticsearchOperations;\n\n    @Override\n    public SearchPage&lt;Product&gt; getProductsCountByCategory(Pageable pageable) {\n        Query query = NativeQuery.builder()\n                .withAggregation(\"category_aggregation\",\n                        Aggregation.of(b -&gt; b.terms(t -&gt; t.field(\"category.keyword\"))))\n                .build();\n\n        SearchHits&lt;Product&gt; response = elasticsearchOperations.search(query, Product.class);\n        return SearchHitSupport.searchPageFor(response, pageable);\n    }\n\n        public Map&lt;String, Long&gt; countByCategory() {\n        Query query = NativeQuery.builder()\n                .withAggregation(\"category_aggregation\",\n                        Aggregation.of(b -&gt; b.terms(t -&gt; t.field(\"category.keyword\"))))\n                .build();\n\n        SearchHits&lt;Product&gt; searchHits = elasticsearchOperations.search(query, Product.class);\n\n        Map&lt;String, Long&gt; aggregatedData = ((ElasticsearchAggregations) searchHits\n                .getAggregations())\n                .get(\"category_aggregation\")\n                .aggregation()\n                .getAggregate()\n                .sterms()\n                .buckets()\n                .array()\n                .stream()\n                .collect(Collectors.toMap(bucket -&gt; bucket.key().stringValue(), MultiBucketBase::docCount));\n\n        return aggregatedData;\n    }\n}\n\n<\/pre>\n<p>Here, we use <code>NativeQuery.builder()<\/code> to build a query with a terms aggregation. In the <code>getProductsCountByCategory(Pageable pageable)<\/code> method, the aggregation, named <code>\"category_aggregation\"<\/code>, counts the number of documents for each unique value in the <code>category<\/code> field. The query is executed using <code>elasticsearchOperations.search()<\/code>, and the result is converted to a <code>SearchPage<\/code> for pagination.<\/p>\n<p>The <code>countByCategory<\/code> method executes a terms aggregation query that counts the number of documents in each category. <\/p>\n<h3 class=\"wp-block-heading\">2.5 Expose the Aggregation Result via REST<\/h3>\n<p>Finally, expose the aggregation results via a REST controller:<\/p>\n<pre class=\"brush:java\">\n@RestController\npublic class ProductController {\n\n    @Autowired\n    private ProductService productService;\n\n    @GetMapping(\"\/products-count-by-category\")\n    public List&lt;Product&gt; getProductsCountByCategory(@RequestParam(defaultValue = \"2\") int size) {\n        SearchHits&lt;Product&gt; searchHits = productService.getProductsCountByCategory(Pageable.ofSize(size))\n                .getSearchHits();\n\n        return searchHits.getSearchHits()\n                .stream()\n                .map(SearchHit::getContent)\n                .collect(Collectors.toList());\n    }\n\n    @GetMapping(\"\/count-by-category\")\n    public Map&lt;String, Long&gt; countByCategory() {\n        return productService.countByCategory();\n    }\n\n\n<\/pre>\n<p>The <code>ProductController<\/code> class exposes two endpoints. <\/p>\n<ul class=\"wp-block-list\">\n<li>The <code>\/products-count-by-category<\/code> endpoint takes <code>size<\/code> as a query parameter for pagination. It calls the <code>getProductsCountByCategory()<\/code> method from the <code>ProductService<\/code> to fetch the aggregated data.<\/li>\n<li>The <code>\/count-by-category<\/code> endpoint calls the <code>countByCategory<\/code> method and returns the counts as a JSON object.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">3. Running and Testing the Application<\/h2>\n<p>With everything set up, we can run the application. The endpoint <code>\/products-count-by-category<\/code> will return a list of <code>Product<\/code> objects, grouped by category with the number of documents (products) in each category. <\/p>\n<p>We can test the <code>\/products-count-by-category<\/code> endpoint using the following <code>curl<\/code> command:<\/p>\n<pre class=\"brush:bash\">\ncurl -X GET \"http:\/\/localhost:8080\/products-count-by-category?size=2\" -H \"Content-Type: application\/json\"\n<\/pre>\n<p>We can test the new <code>\/count-by-category<\/code> endpoint using the following <code>curl<\/code> command:<\/p>\n<pre class=\"brush:bash\">\ncurl -X GET \"http:\/\/localhost:8080\/count-by-category\" -H \"Content-Type: application\/json\"\n<\/pre>\n<p>The response will be a JSON object where the keys are the category names and the values are the number of documents in each category. The screenshot below shows the output when viewed from a web browser.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/08\/elasticsearchcountagg.png\"><img decoding=\"async\" width=\"451\" height=\"142\" src=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/08\/elasticsearchcountagg.png\" alt=\"Elasticsearch aggregation query example results displayed in a web browser.\" class=\"wp-image-125542\" srcset=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/08\/elasticsearchcountagg.png 451w, https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/08\/elasticsearchcountagg-300x94.png 300w\" sizes=\"(max-width: 451px) 100vw, 451px\" \/><\/a><\/figure>\n<\/div>\n<p>This output shows that there are <strong>2<\/strong> products in the &#8220;<strong>Electronics<\/strong>&#8221; category and <strong>1<\/strong> in &#8220;<strong>Clothing<\/strong>.&#8221; The exact counts will depend on the data in your Elasticsearch index.<\/p>\n<h2 class=\"wp-block-heading\">4. Conclusion<\/h2>\n<p>In this article, we&#8217;ve explored how to integrate and configure Elasticsearch in a Spring Boot application. We set up a basic configuration using a configuration class, which included defining essential beans like <code>RestClient<\/code>, <code>ElasticsearchClient<\/code>, and <code>ElasticsearchOperations<\/code>. These components are crucial for interacting with Elasticsearch leveraging advanced features like aggregations.<\/p>\n<h2 class=\"wp-block-heading\">5. Download the Source Code<\/h2>\n<p>This was an article on how to perform an Elasticsearch aggregation query.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/08\/aggElasticSearchExample.zip\"><strong>elasticsearch aggregation query<\/strong><\/a>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Elasticsearch is a distributed search engine that is designed for scalability, flexibility, and high performance. It allows us to store, search, and analyze large volumes of data quickly. One of its key features is the capability to perform aggregations, allowing us to conduct complex data analysis and extract statistical insights from our indexed data. In &hellip;<\/p>\n","protected":false},"author":128888,"featured_media":65382,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[732,321],"class_list":["post-125500","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-elasticsearch","tag-spring-data"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/web.facebook.com\/omos.aziegbe\" \/>\n<meta property=\"article:published_time\" content=\"2024-08-12T10:01:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-12T10:01:10+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Omozegie Aziegbe\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/OAziegbe\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Omozegie Aziegbe\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html\"},\"author\":{\"name\":\"Omozegie Aziegbe\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/7d3eac6e45542536e961129ae0fb453e\"},\"headline\":\"Implementing an Elasticsearch Aggregation Query in Java\",\"datePublished\":\"2024-08-12T10:01:06+00:00\",\"dateModified\":\"2024-08-12T10:01:10+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html\"},\"wordCount\":997,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2017\\\/04\\\/elastic-logo.png\",\"keywords\":[\"Elasticsearch\",\"Spring Data\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html\",\"name\":\"Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2017\\\/04\\\/elastic-logo.png\",\"datePublished\":\"2024-08-12T10:01:06+00:00\",\"dateModified\":\"2024-08-12T10:01:10+00:00\",\"description\":\"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2017\\\/04\\\/elastic-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2017\\\/04\\\/elastic-logo.png\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/implementing-an-elasticsearch-aggregation-query-in-java.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Implementing an Elasticsearch Aggregation Query in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/7d3eac6e45542536e961129ae0fb453e\",\"name\":\"Omozegie Aziegbe\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"caption\":\"Omozegie Aziegbe\"},\"description\":\"Omos Aziegbe is a technical writer and web\\\/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.\",\"sameAs\":[\"https:\\\/\\\/web.facebook.com\\\/omos.aziegbe\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/omosaziegbe\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/OAziegbe\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/omozegie-aziegbe\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks","description":"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html","og_locale":"en_US","og_type":"article","og_title":"Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks","og_description":"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.","og_url":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_author":"https:\/\/web.facebook.com\/omos.aziegbe","article_published_time":"2024-08-12T10:01:06+00:00","article_modified_time":"2024-08-12T10:01:10+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png","type":"image\/png"}],"author":"Omozegie Aziegbe","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/OAziegbe","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Omozegie Aziegbe","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html"},"author":{"name":"Omozegie Aziegbe","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/7d3eac6e45542536e961129ae0fb453e"},"headline":"Implementing an Elasticsearch Aggregation Query in Java","datePublished":"2024-08-12T10:01:06+00:00","dateModified":"2024-08-12T10:01:10+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html"},"wordCount":997,"commentCount":0,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png","keywords":["Elasticsearch","Spring Data"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html","url":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html","name":"Implementing an Elasticsearch Aggregation Query in Java - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png","datePublished":"2024-08-12T10:01:06+00:00","dateModified":"2024-08-12T10:01:10+00:00","description":"Learn how to add an Elasticsearch aggregation query in Java using Spring Data Elasticsearch with detailed examples and explanations.","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2017\/04\/elastic-logo.png","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/implementing-an-elasticsearch-aggregation-query-in-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"Implementing an Elasticsearch Aggregation Query in Java"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/7d3eac6e45542536e961129ae0fb453e","name":"Omozegie Aziegbe","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","caption":"Omozegie Aziegbe"},"description":"Omos Aziegbe is a technical writer and web\/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.","sameAs":["https:\/\/web.facebook.com\/omos.aziegbe","https:\/\/www.linkedin.com\/in\/omosaziegbe\/","https:\/\/x.com\/https:\/\/twitter.com\/OAziegbe"],"url":"https:\/\/www.javacodegeeks.com\/author\/omozegie-aziegbe"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/125500","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/128888"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=125500"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/125500\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/65382"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=125500"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=125500"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=125500"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}