Search code examples
sortingsearchsolrgroupingsolarium

Sum field and sort on Solr


I'm implementing a grouped search in Solr. I'm looking for a way of summing one field and sort the results by this sum. With the following data example I hope it will be clearer.

{
  [
    {
      "id" : 1,
      "parent_id" : 22,
      "valueToBeSummed": 3
    },
    {
      "id" : 2,
      "parent_id" : 22,
      "valueToBeSummed": 1
    },
    {
      "id" : 3,
      "parent_id" : 33,
      "valueToBeSummed": 1
    },
    {
      "id" : 4,
      "parent_id" : 5,
      "valueToBeSummed": 21
    }
  ]
}

If the search is made over this data I'd like to obtain

{
  [
    {
      "numFound": 1,
      "summedValue" : 21,
      "parent_id" : 5
    },
    {
      "numFound": 2,
      "summedValue" : 4,
      "parent_id" : 22
    },
    {
      "numFound": 1,
      "summedValue" : 1,
      "parent_id" : 33
    }
  ]
}

Do you have any advice on this ?


Solution

  • Solr 5.1+ (and 5.3) introduces Solr Facet functions to solve this exact issue.

    From Yonik's introduction of the feature:

    $ curl http://localhost:8983/solr/query -d 'q=*:*&
     json.facet={
       categories:{
         type : terms,
         field : cat,
         sort : "x desc",   // can also use sort:{x:desc}
         facet:{
           x : "avg(price)",
           y : "sum(price)"
         }
       }
     }
    '
    

    So the suggestion would be to upgrade to the newest version of Solr (the most recent version is currently 5.2.1, be advised that some of the syntax that's on the above link will be landed in 5.3 - the current release target).