Tutorial: Solr grouping

jpmckinney edited this page Jan 6, 2012 · 4 revisions

This tutorial was contributed by Peter Nachbaur. Throughout the tutorial, replace GROUP_FIELD with the field on which you want to group results.

Parameters

To enable Solr grouping (field collapsing), first add the parameters below. See the Solr wiki for more information on grouping parameters.

var params = {
  group: true,
  'group.field': ['GROUP_FIELD'],
  'group.ngroups': true
};
for (var name in params) {
  Manager.store.addByValue(name, params[name]);
}

Results

In your widget for displaying results, instead of iterating over documents, this.manager.response.response.docs, you will want to iterate over groups, this.manager.response.grouped.GROUP_FIELD.groups. Each group has a doclist field which itself has a docs field, which is an array of every document in the group.

If you are using the ResultsWidget from the Reuters tutorial, you would modify its afterRequest method to read:

for (var i = 0, l = this.manager.response.grouped.GROUP_FIELD.groups.length; i < l; i++) {
  for (var j = 0, m = this.manager.response.grouped.GROUP_FIELD.groups[i].doclist.docs.length; j < m; j++) {
    var doc = this.manager.response.grouped.GROUP_FIELD.groups[i].doclist.docs[j];

Note that, by default, group.limit is 1, so instead of the inner loop above, you can just write:

var doc = this.manager.response.grouped.GROUP_FIELD.groups[i].doclist.docs[0];

Pagination

If group.limit is 1 (default) and you are using the PagerWidget from the Reuters tutorial, make a copy and change:

var total = parseInt(this.manager.response.response.numFound);

to:

var total = parseInt(this.manager.response.grouped.GROUP_FIELD.ngroups);

If group.limit is not 1, you may have to do one of the following:

var total = parseInt(this.manager.response.grouped.GROUP_FIELD.matches);

or:

var total = 0;
for (var i = 0, l = this.manager.response.grouped.GROUP_FIELD.groups.length; i < l; i++) {
  total += this.manager.response.grouped.GROUP_FIELD.groups[i].doclist.numFound;
}

or yet another method depending on which Solr grouping parameters you set.

Solr schema

Your group field must be single-valued. In your Solr schema, your field definition may look like, for example:

<field name="GROUP_FIELD" type="string" indexed="true" stored="true" multiValued="false"/>
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.