2

Is it possible to query solr usign spring data to get an average/sum etc for one field? I tried to do facets (but there is only count available).

I found that there are Stats Components available with solr. Adding to query some parameters like stats.field or stats.facet should help.

Is it possible to get this using spring-data-solr?

wojtek
  • 493
  • 1
  • 7
  • 12

1 Answers1

2

This isn't implemented yet on spring-data-solr. A new feature request was done here, and meanwhile you could use spring-data-solr SolrOperations implementation to perform such operation with a callback that allows you directly use the underlying SolrServer as follows:

Map<String, FieldStatsInfo> response = template.execute(new SolrCallback<Map<String, FieldStatsInfo>>() {

    @Override
    public Map<String, FieldStatsInfo> doInSolr(SolrServer solrServer) throws SolrServerException, IOException {
        SolrQuery params = new SolrQuery("*:*");
        params.add(StatsParams.STATS, "true");
        params.add(StatsParams.STATS_FIELD, "price");
        QueryResponse query = solrServer.query(params);
        return query.getFieldStatsInfo();
    }

});

System.out.println("Price sum....: " + response.get("price").getSum());
System.out.println("Price mean...: " + response.get("price").getMean());
System.out.println("Price min....: " + response.get("price").getMin());
System.out.println("Price max....: " + response.get("price").getMax());

From spring-data-solr version 1.4 M1 you could implement this using StatsOptions as follows:

SimpleQuery statsQuery;
...
statsQuery.setStatsOptions(new StatsOptions().addField("price"));
...    
StatsPage<Product> statsPage = solrTemplate.queryForStatsPage(statsQuery, Product.class);

FieldStatsResult priceStatResult = statResultPage.getFieldStatsResult("price");
Object max = priceStatResult.getMax();
Long missing = priceStatResult.getMissing();
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106