Ankit Ostwal
Ankit Ostwal

Reputation: 1051

Group by date field in solrj

i want to group the output i am getting through date type. But i am storing the data in solr using datetime type. Date Format i am using is

          Date format :: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

 For e.g. Date is stored in solr as "2013-03-01T20:56:45.000+00:00"

What i want as output is count of dates :: for .e.g.

   Date1:: "2013-03-01T20:56:45.000+00:00"
   Date2:: "2013-03-01T21:56:45.000+00:00"
   Date3:: "2013-03-01T22:56:45.000+00:00"
   Date3:: "2013-03-02T22:56:45.000+00:00"
   Date4:: "2013-03-02T23:56:45.000+00:00"

So i want the output as two columns ::

     Date           Count
     2013-03-01       3  
     2013-03-02       2  

Here is the code i am using

    String url = "http://192.168.0.4:8983/solr";
SolrServer server = new HttpSolrServer(url);
SolrQuery query = new SolrQuery();


query.setQuery("*:*");
query.addFilterQuery("sessionStartTime:[2013-03-01T00:00:00Z TO 2013-03-04T24:00:00Z]");

query.add("group", "true");
query.add("group.field","uniqueId"); // uniqueId is grouping the data 
query.add("group.main","true");
query.setRows(9999);

QueryResponse rs=server.query(query);

Iterator<SolrDocument> iter = rs.getResults().iterator();

Help is appreciated.

Upvotes: 1

Views: 2136

Answers (2)

jbird
jbird

Reputation: 506

I know that this is an older question but I am working on something related to this so I thought I would share my solution. Since you are using grouping, rs.getResults() will likely be null. After reading through the SolrJ API and doing some testing on my end, you will find that the results are indeed grouped as you want them to be. To access them, create a variable like such:

List<Group> groupedData = rs.getGroupResponse().getValues().get(0).getValues()

Note that Group is the class org.apache.solr.client.solrj.response.Group

Then, iterate through groupedData, usinig groupedData.get(i).getResult() to get a SolrDocumentList of results for each grouped value. In your example, (assuming the data is ordered as you said it would be), groupedData.get(0) would give you a SolrDocumentList of the three matches that have the date 2013-03-01.

I understand that this is quite the chain of method calls but it does end up getting the results to you. If anyone does know a faster way to get to the data, please feel free to let me know as I would like to know as well.

Refer to the API for GroupResponse for more information

Note that this answer is working on Solr 5.4.0

Upvotes: 1

Paige Cook
Paige Cook

Reputation: 22555

The output that you are trying to achieve, I believe is better suited to Faceting over grouping. Check out the documentation on Date Faceting more specifically and SolrJ fully supports faceting, see SolrJ - Advanced Usage. For an introduction to Faceting I would recommend reading Faceted Search with Solr

Upvotes: 0

Related Questions