Beliebte Suchanfragen

Cloud Native



Agile Methoden



JasperReports Tutorial: Dynamic Drill-Down Reports with MongoDB (Part 1 of 2)

21.7.2013 | 19 minutes of reading time

In this article, I will demonstrate by means of a step-by-step tutorial, how one can create an interactive report, using only the community editions (i.e. open source versions) of the JasperReports tools without having to learn the intricacies of how to query the Big Data-storage at hand.

Let’s get our hands dirty!

Not another ‘Hello World’, PLEASE!

Don’t worry.

We are going to create a report on a survey conducted in January ’13 by Princeton Survey Research Associates International (PSRAI), questioning US-Americans as to their usage of mobile phones while shopping during the holiday shopping season of 2012 (‘holiday season’, for us Europeans, is the politically correct expression for ‘Christmas season’).

To make things interesting, this report will feature dynamic drill-downs so that we will be able to filter the results shown depending on the answers given by the respondents. Filtering will be accomplished by the user clicking into the corresponding pie of a pie-chart. Here are a few screenshots showing what the resulting report will look like:

All three screenshots depict the answers to the same question; however, the last two screens show the answers depending on whether the respondent was male or currently not employed.


First things first; you’ll need the following software components installed and running in order to follow the tutorial:

  • MongoDB.
    We want to explore JasperReports connectivity to Big Data, after all. MongoDB is, in my opinion, one of those Big Data storages that are easier to get started with than the others available.
    You can download a version for your operating system of choice directly from their web site and follow these instructstions to install (don’t worry, it’s easy).
    I employed version 2.4.3 while writing this tutorial.
  • JasperReports Server and iReport Designer
    Since our report features dynamic drill-down we need an environment where this can be executed – the easiest way is to use JasperReports Server. Of course, it is possible to implement this execution environment yourself using just the JasperReports library which features a bare-bone servlet for report presentation to get you started. That however is beyond the scope of this tutorial.
    The iReport Designer is essential in efficiently creating reports – even though the reports are written in XML. Directly working with this XML is beyond the scope of this tutorial. Please note that JasperSoft (the company behind JasperReports) is trying to place Jaspersoft Studio as the primary means for creating reports; in my opinion that software is not as robust and feature complete as iReport yet, which is why we will stick to iReport.
    You can access all required packages from the community download page .
    I employed version 5.1.0 of each package.

After you have installed (I chose to use the defaults wherever possible, keeping the installation as simple as possible) and started the software, we will continue by importing the data into the MongoDB instance.


Step 1: The data

The raw data of the survey can be accessed on the pages of the Pew Research Center’s Internet & American Life Project:–Mobile-Shopping-%28omnibus%29.aspx

The data is available in CSV format, which you can import into MongoDB using the command mongoimport.

However, you’ll need to rework the data a bit because it is provided so as to be put directly into a table-based RDBMS – which we don’t want.

Therefore and for your convenience, I have provided a dump of the data I used which you can download from here (in 7-Zip-format):

After you have extraced it (will create directories dump/test) you can import this into your MongoDB instance using the following command
which will restore a collection called ‘omnibus’ in the db ‘test’ of the MongoDB instance accessible on localhost using the default port 27017. If you do not want that to happen and, for example, use another db or collection, you’ll have to provide the corresponding parameters.

Please see for further details.

Let’s have a look at the data: open a shell to your MongoDB with the command mongo and issue the command db.omnibus.find().limit(5). The resulting output should look like this:

2> db.omnibus.find().limit(5)
4{ "_id" : ObjectId("51936e78bf24cbed9348fe83"), "respondent_id" : 100002, "qnr" : 0, "question" : "Do you have a cell phone?", "anr" : 2, "answer" : "No" }
6{ "_id" : ObjectId("51936e78bf24cbed9348fe84"), "respondent_id" : 100002, "qnr" : 1, "question" : "Do you have a handheld device made primarily for e-book reading, such as a Nook or Kindle e-reader?", "anr" : 2, "answer" : "No" }
8{ "_id" : ObjectId("51936e78bf24cbed9348fe85"), "respondent_id" : 100002, "qnr" : 2, "question" : "Do you have a tablet computer such as an iPad, Samsung Galaxy Tab, Google Nexus or Kindle Fire?", "anr" : 2, "answer" : "No" }
10{ "_id" : ObjectId("51936e78bf24cbed9348fe86"), "respondent_id" : 100002, "qnr" : 3, "question" : "Do you have an iPod or other MP3 player?", "anr" : 2, "answer" : "No" }
12{ "_id" : ObjectId("51936e78bf24cbed9348fe87"), "respondent_id" : 100002, "qnr" : 4, "question" : "Do you have a game console like an Xbox or Play Station?", "anr" : 2, "answer" :"No" }

<p>As you can see, the data is very structured with all the documents having the same one:</p><ul><li>_id: the unique identifier of the document. Generated by MongoDB.</li><li>respondent_id: the ID of the respondent giving the answers.</li><li>qnr: the number of the question.</li><li>question: the question itself.</li><li>anr: the number of the answer the respondent gave to the question.</li><li>answer: the answer that the respondent gave to the question.</li></ul><p>I’ll admit that the example is contrived: in real life, you would store the survey data in a table-based RDBMS and never worry about Big Data. The available questions and answers for each would be stored in separate tables and you would link the respondent ID to the answer ID given for each available question ID.</p><p>However, what if you had different surveys that featured some similar questions and you needed to analyze them together? How would you go about that with a table-based RDBMS? Not so easy, isn’t it?</p><p>With a document based system like MongoDB it becomes easy: you pick the fields that are available in most collections and copy that data into a new collection (no joins in MongoDB) and then start to extract information.</p><p>The point to make is that with NoSQL-systems you get a flexibility that is not available with the same kind of ease in traditional table-based RDBMS, yet. In general, you have to carefully design your data model upfront and even then you run the risk of having to invest a lot of work if circumstances change in unexpected ways. Not so with NoSQL, where you have less to worry about to get things started.</p><p>On a side note, you can access more background information and interpretation of the survey data on the Pew Internet site at <a href=""></a> .</p><h3>Step 2: The report</h3><p>Now that we have the data available, we can create the reports; you actually need two to make drill-down available.<br /> Let’s continue by starting iReport Designer (MongoDB should be kept running).</p><h4>Step 2.1: The datasource</h4><p>In general, the first step in creating a JasperReport with iReport is creating and/or selecting a datasource to use.<br /> Click on the “Report datasource”-button (marked by red borders in the screenshot):</p><p><a href=""><img loading="lazy" alt="Screen 4" src="" width="300" height="159" /></a> </p><p>This opens a dialogue -window in which you can modify and select one of the available datasources, delete one or create a new one.</p><p>Click on the “New” button to do the latter.</p><p>Select “MongoDB Connection” from the list of available connection types and click on “Next”.</p><p>In the following dialogue you have to provide a name for the datasource as well as the actual connection data. If, during the installation of MongoDB, you chose to use the defaults (like me), all you have to enter for connection data is host (i.e. ‘localhost’) and db-name (i.e. ‘test’):</p><p><a href=""><img loading="lazy" alt="Screen 5" src="" width="253" height="300" /></a> </p><p>Hit “Test” to check if the connection works and then “Save” to store the datasource. Return to the main screen and make sure that the datasource you just created is the active one:<br /> <a href=""><img loading="lazy" alt="Screen 6" src="" width="300" height="102" /></a> </p><h4>Step 2.2: The query</h4><p>With the datasource available, we can begin creating the report.<br /> Select “File” -> “New” and choose “Launch Report Wizard” in the “Report” subsection in the following dialogue:</p><p><a href=""><img loading="lazy" alt="Screen 7" src="" width="300" height="227" /></a> </p><p>In the next screen you need to enter a name for your report (I used “omnibus_main”) and select the location where it should be stored. Do that and hit “Next”.</p><p>Now, it gets interesting: we need to provide the query with which JasperReports is to obtain the data.</p><p>In case of MongoDB, the query language to use is the Jaspersoft MongoDB Query Language, which is a JSON-style declarative language; you can find all the details here:</p><p><a href=""></a> </p><p>The resulting queries look almost identical to the queries one would write in the Javascript shell of MongoDB. Because I want to demonstrate how JasperReports can help if one is not an expert in the query language of the given storage system, I will not get into too much detail.</p><p>We only need to define one mandatory parameter, collectionName, and that is exactly what we’ll do:</p><p><a href=""><img loading="lazy" alt="Screen 8" src="" width="300" height="187" /></a> </p><p>A query like this results in all the documents of the specified collection to be returned. In our example, that is not a problem because our collection is small. However, it is called Big Data for a reason and even though JasperReports Server is capable of handling terabytes of data, it will require resources to do that. Besides, when designing a report with iReport you want to preview the report regularly to check if all the components fit into place as desired and then you do not want to wait too long for the preview to be created.</p><p>Therefore, even though we will not be using it, I strongly suggest keeping the following additional query-parameter in mind:</p><p><code>limit</code>: this limits the amount of documents returned by the query</p><p>Click “Next” to proceed.</p><p>Now iReport executes the query and scans the documents returned by it for the fields contained in each. This is necessary, because the structure of the documents in a MongoDB collection can be very different from document to document. iReport makes the fields found available to you to work with.</p><p>By default, iReport scans only the first 5 documents returned by the query. If you have a collection with very disparate documents that amount may not be enough. Therefore, JasperReports offers an additional query-parameter that is not available in MongoDB:</p><p><code>rowsToProcess</code>: sets the number of rows that will be processed to determine the list of fields.</p><p>In our case, the results of the scan are as follows:</p><p><a href=""><img loading="lazy" alt="Screen 9" src="" width="300" height="187" /></a> </p><p>We will be working with all the fields so click “>>” to select them all followed by “Next” to continue.</p><p>This next screen allows us to group the data by one or more fields (up to 4). We want to group our data by the questions and corresponding answers given by each respondent. Therefore, select <code>question</code> as <code>Group 1</code> and <code>answer</code> as <code>Group 2</code>:</p><p><a href=""><img loading="lazy" alt="Screen 10" src="" width="300" height="187" /></a> </p><p>Click “Next” followed by “Finish” to complete the wizard.</p><h4>Step 2.3: The report (this time for real)</h4><p>Behold, your first JasperReport connecting to MongoDB!</p><p>It is fully functional as you can check out by clicking the “Preview”-button in the report view:</p><p><a href=""><img loading="lazy" alt="Screen 11" src="" width="243" height="91" /></a> </p><p>Of course, since we haven’t placed anything on the report yet, it will be blank. Even so, the preview will take some noticeable time to generate and will be more than 3000 pages long!</p><p>The reason lies in the band-based design of JasperReports: each band follows a specific function. For example, the detail band (marked red in the following screen shot) works on each row of the query’s resultset and, if it is present, causes something to be print for each one. By ‘something’ I mean that which was designed for the detail band in the design view; JasperReports tries to honor the space the detail band takes up in the design view when generating the report – based on our current design, around 4 detail bands fit on one page, so we get the more than 3000 pages, but not 15868 which would be the total size of our collection.</p><p>You can see what is happening by dragging one of the fields unto the detail band (marked green) and hitting “Preview” again:</p><p><a href=""><img loading="lazy" alt="Screen 12" src="" width="300" height="169" /></a> </p><p>The resulting report should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 13" src="" width="300" height="263" /></a> </p><p>Now, let’s get rid of the detail band (and some others as well)!</p><p>For our report, we are mainly interested in presenting the grouped data and the other bands will only get in the way. Therefore, right-click on each of the following bands in the Report Inspector and select “Delete Band”:</p><ul><li>Column Header</li><li>Detail 1</li><li>Column Footer</li><li>Summary</li></ul><p>Correspondingly, right-click on each of the following bands in the Report Inspector and select “Add Band”:</p><ul><li>question Group Header 1</li><li>answer Group Footer 1</li><li>question Group Footer 1</li></ul><p>The resulting report should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 14" src="" width="300" height="129" /></a> </p><p>If you haven’t done so already, now’s the time to save your work.</p><p>We will now work our way from the title-band down to the page footer.</p><h5>“Title”-band</h5><p>This band contains two labels. If you haven’t done so, open the palette by selecting “Window” -> “Palette”. This brings up a menu with all available report elements. Select the element “Static Text” and then drag two of it unto the title band. Now, if the properties window is not open, select “Window” -> “Properties” to open it:</p><p><a href=""><img loading="lazy" alt="Screen 15" src="" width="286" height="300" /></a> </p><p>The first label should have the following properties set:</p><ul><li>Text: “In-store Mobile Commerce During the 2012 Holiday Shopping Season”</li><li>Size: 26</li><li>Bold: true</li><li>Horizontal Alignment: Center</li></ul><p>The second one the following properties:</p><ul><li>Text: “This omnibus survey contains questions about device ownership and cell phone usage during purchase decisions.”</li><li>Horizontal Alignment: Center</li></ul><p>You will need to resize and rearrange the two label elements to fit them unto the report as desired. Also, you will find that the orientation of the report needs to be changed, because the heading will not fit entirely into the band.</p><p>This can be accomplished by right-clicking on the report-name in the Report Inspector (‘omnibus_main’), selecting “Properties” and changing the orientation to “Landscape”:</p><p><a href=""><img loading="lazy" alt="Screen 16" src="" width="300" height="89" /></a> </p><p>After that, your title band should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 17" src="" width="300" height="40" /></a> </p><p>When you hit “Preview”, you will see that this title is only printed on the first page.</p><h5>“Page Header”-band</h5><p>This band only contains one label, with the following properties:</p><ul><li>Text: “In-store Mobile Commerce During the 2012 Holiday Shopping Season”</li><li>Size: 16</li><li>Bold: true</li></ul><p>The resulting band should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 18" src="" width="300" height="17" /></a> </p><p>However, when you preview the report, you will find that the first page will also contain this header:</p><p><a href=""><img loading="lazy" alt="Screen 19" src="" width="300" height="58" /></a> </p><p>Looks odd, doesn’t it?</p><p>Fortunately, this can be remedied by using an expression to prevent the page header to be rendered on the first page.</p><p>In the Report Inspector, select “Page Header” and then click the button marked “…” in the property named “Print When Expression” to open the expression editor:</p><p><a href=""><img loading="lazy" alt="Screen 20" src="" width="300" height="89" /></a> </p><p>Our goal is to prevent the page header from being print on the first page. Luckily for us, JasperReports provides a set of variables that allow us to access the state of the report execution. Among others, the current page number is accessible.</p><p>In the expression editor select “Variables” from the list of available categories and then double-click the variable named “PAGE_NUMBER”. By default, JasperReports expressions are written in Groovy (can be changed to Java or JavaScript) and generally need to return a boolean value (true/false).</p><p>On the first page, the variable “PAGE_NUMBER” will have the value 1. So, to prevent the page header from being print on the first page, we change our expression to evaluate to true when the page number is greater than 1:</p><p><a href=""><img loading="lazy" alt="Screen 21" src="" width="300" height="288" /></a> </p><p>Click “OK”, save your work and hit “Preview” to check if that change worked; the first page of the report should now look like this:</p><p><a href=""><img loading="lazy" alt="Screen 22" src="" width="300" height="55" /></a> </p><p>While the subsequent pages should look thus:</p><p><a href=""><img loading="lazy" alt="Screen 23" src="" width="300" height="38" /></a> </p><h5>“question Group Header 1”-band</h5><p>Finally, we actually get to show some data (and not just static text)!</p><p>This band consists of a vertical line functioning as a separator and a text field presenting the current question.</p><p>First, select the element called “Line” from the palette and drag it into the band. Then lengthen it so that it encompasses the whole band width.</p><p>Next, select the element called “Text Field” from the palette and place it beneath the line. Its properties should be configured as follows:</p><ul><li>Text Field Expression: use the expression editor to print the text ‘Question: ‘, followed by the value of the field ‘question’ (“Question: “+ $F{question}).</li><li>Stretch With Overflow: true. This ensures, that the text will be printed even if it does not fit into the box.</li><li>Size: 14</li><li>Bold: true</li></ul><p>The resulting band should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 24" src="" width="300" height="21" /></a> </p><p>If you preview your report, you should get something like this (5000+ pages!):</p><p><a href=""><img loading="lazy" alt="Screen 25" src="" width="300" height="214" /></a> </p><p>First of all, we want each question to be printed on a separate page.</p><p>In the Report Inspector, select “question Group Header 1” and then enable the property named “Start on new page”:</p><p><a href=""><img loading="lazy" alt="Screen 26" src="" width="300" height="140" /></a> </p><p>By the way, as you can see, you can always edit the expression used to calculate the group using the property “Group Expression”.</p><p>The preview should now show each question on a new page. However, it should also be around 15000 pages long!</p><p>What’s wrong here? It looks like grouping is not working at all!</p><p>Yes and no – yes, it apparently does not work, but no, it’s not because the grouping feature is broken.</p><p>The reason is our query: currently it is returning the documents sorted by respondent_id because that is the order the data is stored in the collection. This means that JasperReports gets to see all questions for respondent A before seeing the questions for respondent B and so on – under that circumstance, JasperReport cannot group the data by question and answer.</p><p>Therefore, we need to change the order the documents are returned by the query. This can be accomplished using the sort query-parameter:</p><p><code>sort</code>: Specifies the fields and order of each one of the them that will be used to sort; 1 for natural order, -1 for reverse order.</p><p>In the Report Inspector, right-click on the report name and select “Edit Query” to open the query editor. Then, change the query to sort the documents first by question number followed by the answer number:</p><p><a href=""><img loading="lazy" alt="Screen 27" src="" width="300" height="188" /></a> </p><p>If we now generate a new preview, we will get the desired result, that is: 17 pages for 17 questions in all.</p><h5>“answer Group Footer 1”-band</h5><p>This band contains two text fields to show the answers given for each question and the corresponding count for each.</p><p>The first text field should have the following properties set:</p><ul><li>Forecolor: [0,153,153]</li><li>Text Field Expression: $F{answer}+”: “</li><li>Stretch With Overflow: true</li><li>Size: 12</li><li>Bold: true</li><li>Horizontal Alignment: Right</li></ul><p>The second one, which is to be located right beside the first, should have the following properties set:</p><ul><li>Text Field Expression: $V{answer_COUNT}. JasperReports provides a COUNT-variable for each group defined holding the count of elements in that particular group.</li><li>Size: 12</li></ul><p>When you create a preview, it should look thus:</p><p><a href=""><img loading="lazy" alt="Screen 28" src="" width="300" height="80" /></a> </p><p><a href=""><img loading="lazy" alt="Screen 29" src="" width="300" height="73" /></a> </p><p>We are getting close….but the biggest part is yet to come.</p><h5>“question Group Footer 1”-</h5><p>Finally, the pie chart!</p><p>Grab the “Chart” element from the palette and drag it into the band. This opens a dialogue letting you chose from various diagram types. We want a simple, flat pie chart which is incidentally the first option available. Select it and press “OK” to continue.</p><p>In the following wizard we need to provide the data the pie chart will use to render itself. First, we need to specify the dataset, which should be “Main report dataset”; this will almost always be the same, the only exception being subreports which can specify their own datasets:</p><p><a href=""><img loading="lazy" alt="Screen 30" src="" width="300" height="173" /></a> </p><p>Click “Next” to continue.</p><p>Now we need to provide a unique identifier to be used for each pie slice as well as the corresponding numeric value. This wizard page may be sized too small so that you won’t see the corresponding fields – if so, resize the dialogue window until you can see the fields.</p><p>Since we want to show the statistics of the answers given for each question, we select the answer-field as the unique identifier and the answer_COUNT-variable as the numeric value for each slice:</p><p><a href=""><img loading="lazy" alt="Screen 31" src="" width="300" height="215" /></a> </p><p>Click “Next” followed by “Finish” to close the wizard.</p><p>You’ll probably need to resize the pie chart, after which your band should look like this:</p><p><a href=""><img loading="lazy" alt="Screen 32" src="" width="300" height="108" /></a> </p><p>And the preview report like…. what is this? That’s not right:</p><p><a href=""><img loading="lazy" alt="Screen 33" src="" width="300" height="177" /></a> </p><p>I’ve highlighted the wrong values with red borders.</p><p>The problem is that currently the pie chart does not know that it is rendering different groups. This causes all group values to be added on each subsequent page resulting in the following “thing” on the last page:</p><p><a href=""><img loading="lazy" alt="Screen 34" src="" width="300" height="122" /></a> </p><p>To remedy this problem, right-click into the pie chart and select “Chart Data”.</p><p>In the tab “Dataset” of the following dialogue, select “group” under “Reset type” and “question” under “Reset group”:</p><p><a href=""><img loading="lazy" alt="Screen 35" src="" width="243" height="300" /></a> </p><p>Save your work and recreate the preview.</p><p>I’ll skip a screenshot this time, because we are very close to the finish line now.</p><h5>“Page Footer”-band</h5><p>Almost there!</p><p>This band is supposed to contain a text showing the current page and the total number of pages in the style “Page X of Y”.</p><p>For convenience, iReport provides a predefined element to render such a text: it is located in the palette in the section called “Tools” and is named… “Page X of Y” (what did you expect?)</p><p>Drag it into the band at the rightmost position and…</p><p><a href=""><img loading="lazy" alt="Screen 36" src="" width="300" height="212" /></a> <br /> <a href=""><img loading="lazy" alt="Screen 37" src="" width="300" height="212" /></a> </p><p>… we are done!</p><p>You will probably need to fiddle around a bit with the positions and sizes of the various bands and elements to get each question, its answers and the pie chart to fit on one page (actually, there are two questions that have so many possible answers that the components don’t fit completely on one page; that’s why my report has 19 pages instead of 17).</p><p>(Don’t forget to save your work).</p><p>Not done! No sir!</p><p>That’s right; I said that the report will feature drill-downs to filter the answers which will be executed on JasperReports Server.<br /> On to <a href="">part two</a> !</p>

share post




More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.


Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.