Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solr: how to get total number of results for grouped query using the Java API

Tags:

solr

grouping

I have the following:

43 documents indexed in Solr

If I use the Java API to do a query without any grouping, such as:

SolrQuery query = new SolrQuery("*:*");
query.setRows(10);

I can then obtain the total number of matching elements like this:

solrServer.query(query).getResults().getNumFound(); //43 in this case

The getResults() method returns a SolrDocumentList instance which contains this value.

If however I use grouping, something like:

query.set("group", "true");
query.set("group.format", "simple");
query.set("group.field", "someField");

Then the above code for retrieving query results no loger works (throws NPE), and I have to instead use:

List<GroupCommand> groupCommands = solrServer.query(query).getGroupResponse().getValues();
List<Group> groups = groupCommand.getValues();
Group group = groups.get(groupIndex);

I don't understand how to use this part of the API to get the overall number of matching documents (the 43 from the non-grouping query above). First I thought that with grouping is no longer possible to get that, but I've noticed that if I do a similar query in the Solr admin console, with the same grouping and everything, it returns the exact same results as the Java API and also numFound=43. So obviously the code used for the console has some way to retrieve that value even when grouping is used:

enter image description here

My question is, how can I get that overall number of matching documents for a query using grouping executed via Solr Java API?

like image 533
Shivan Dragon Avatar asked Apr 19 '13 11:04

Shivan Dragon


2 Answers

In looking at the source for Group that is returned from your groups.get(groupIndex) call, it has a getResults() method that returns a SolrDocumentList. The SolrDocumentList has a getNumFound() method that should return the overall number, I believe...

So you should be able to get this as the following:

  int numFound = group.getResults().getNumFound();

Hope this helps.

Update: I believe as OP stated, group.getResults().getNumFound() will only return the number of items in the group. However, on the GroupCommand there is a getMatches() method that may be the corresponding count that is desired.

 int matches = groupCommands.getMatches();
like image 138
Paige Cook Avatar answered Nov 17 '22 14:11

Paige Cook


If you set the ngroups parameter to true (default false) this will return the number of groups.

eg:

solrQuery.set("group.ngroups", true);

https://cwiki.apache.org/confluence/display/solr/Result+Grouping

this can then be retrieved from your responding GroupCommand with:

int numGroups = tempGroup.getNGroups();

At least that was my understanding?

like image 40
sonicscorpion Avatar answered Nov 17 '22 16:11

sonicscorpion