<p>Assume that I have a field called <em>price</em> for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?</p>

<p>I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?</p>

[{'answer_id': 34027, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 2, 'selected': False, 'text': "<p>There may well be a better Solr-specific answer, but I work with straight Lucene, and since you're not getting much traction I'll take a stab. There, I'd create a populate a <code>Filter</code> with a <code>FilteredQuery</code> wrapping the original <code>Query</code>. Then I'd get a <code>FieldCache</code> for the field of interest. Enumerate the hits in the filter's bitset, and for each hit, you get the value of the field from the field cache, and add it to a SortedSet. When you've got all of the hits, divide the size of the set into the number of ranges you want (five to seven is a good number according the user interface guys), and rather than a single-valued constraint, your facets will be a range query with the lower and upper bounds of each of those subsets.</p>\n\n<p>I'd recommend using some special-case logic for a small number of values; obviously, if you only have four distinct values, it doesn't make sense to try and make 5 range refinements out of them. Below a certain threshold (say 3*your ideal number of ranges), you just show the facets normally rather than ranges.</p>\n"}, {'answer_id': 170477, 'author': 'Mauricio Scheffer', 'author_id': 21239, 'author_profile': 'https://Stackoverflow.com/users/21239', 'pm_score': 4, 'selected': False, 'text': '<p>To answer your first question, you can get facet ranges by using the the generic facet query support. <a href="http://wiki.apache.org/solr/SimpleFacetParameters#head-1da3ab3995bc4abcdce8e0f04be7355ba19e9b2c" rel="nofollow noreferrer">Here</a>\'s an example:</p>\n\n<pre><code>http://localhost:8983/solr/select?q=video&amp;rows=0&amp;facet=true&amp;facet.query=price:[*+TO+500]&amp;facet.query=price:[500+TO+*]\n</code></pre>\n\n<p>As for your second question (automatically suggesting facet ranges), that\'s not yet implemented. Some argue that this kind of querying would be best implemented on your application rather that letting Solr "guess" the best facet ranges.</p>\n\n<p>Here are some discussions on the topic:</p>\n\n<ul>\n<li>(Archived) <a href="https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html" rel="nofollow noreferrer">https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html</a></li>\n<li>(Archived) <a href="https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html" rel="nofollow noreferrer">https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html</a></li>\n<li>(Archived) <a href="https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html" rel="nofollow noreferrer">https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html</a></li>\n</ul>\n'}, {'answer_id': 10599043, 'author': 'Garytxo', 'author_id': 174816, 'author_profile': 'https://Stackoverflow.com/users/174816', 'pm_score': 2, 'selected': False, 'text': '<p>You can use solr facet ranges</p>\n\n<p><a href="http://wiki.apache.org/solr/SimpleFacetParameters#Facet_by_Range" rel="nofollow">http://wiki.apache.org/solr/SimpleFacetParameters#Facet_by_Range</a></p>\n'}, {'answer_id': 11329853, 'author': 'Graham', 'author_id': 130988, 'author_profile': 'https://Stackoverflow.com/users/130988', 'pm_score': 3, 'selected': False, 'text': '<p>I have worked out how to calculate sensible dynamic facets for product price ranges.  The solution involves some pre-processing of documents and some post-processing of the query results, but it requires only one query to Solr, and should even work on old version of Solr like 1.4.</p>\n\n<h1>Round up prices before submission</h1>\n\n<p>First, before submitting the document, <strong>round up</strong> the the price to the nearest "nice round facet boundary" and store it in a "rounded_price" field.  Users like their facets to look like "250-500" not "247-483", and rounding also means you get back hundreds of price facets not millions of them.  With some effort the following code can be generalised to round nicely at any price scale:</p>\n\n<pre><code>    public static decimal RoundPrice(decimal price)\n    {\n        if (price &lt; 25)\n            return Math.Ceiling(price);\n        else if (price &lt; 100)\n            return Math.Ceiling(price / 5) * 5;\n        else if (price &lt; 250)\n            return Math.Ceiling(price / 10) * 10;\n        else if (price &lt; 1000)\n            return Math.Ceiling(price / 25) * 25;\n        else if (price &lt; 2500)\n            return Math.Ceiling(price / 100) * 100;\n        else if (price &lt; 10000)\n            return Math.Ceiling(price / 250) * 250;\n        else if (price &lt; 25000)\n            return Math.Ceiling(price / 1000) * 1000;\n        else if (price &lt; 100000)\n            return Math.Ceiling(price / 2500) * 2500;\n        else\n            return Math.Ceiling(price / 5000) * 5000;\n    }\n</code></pre>\n\n<p>Permissible prices go 1,2,3,...,24,25,30,35,...,95,100,110,...,240,250,275,300,325,...,975,1000 and so forth.  </p>\n\n<h1>Get all facets on rounded prices</h1>\n\n<p>Second, when submitting the query, request all facets on rounded prices sorted by price: <code>facet.field=rounded_price</code>.  Thanks to the rounding, you\'ll get at most a few hundred facets back.</p>\n\n<h1>Combine adjacent facets into larger facets</h1>\n\n<p>Third, after you have the results, the user wants see only 3 to 7 facets, not hundreds of facets.  So, combine adjacent facets into a few large facets (called "segments") trying to get a roughly equal number of documents in each segment. The following rather more complicated code does this, returning tuples of (start, end, count) suitable for performing range queries.  The counts returned will be correct provided prices were been rounded <em>up</em> to the nearest boundary:</p>\n\n<pre><code>    public static List&lt;Tuple&lt;string, string, int&gt;&gt; CombinePriceFacets(int nSegments, ICollection&lt;KeyValuePair&lt;string, int&gt;&gt; prices)\n    {\n        var ranges = new List&lt;Tuple&lt;string, string, int&gt;&gt;();\n        int productCount = prices.Sum(p =&gt; p.Value);\n        int productsRemaining = productCount;\n        if (nSegments &lt; 2)\n            return ranges;\n        int segmentSize = productCount / nSegments;\n        string start = "*";\n        string end = "0";\n        int count = 0;\n        int totalCount = 0;\n        int segmentIdx = 1;\n        foreach (KeyValuePair&lt;string, int&gt; price in prices)\n        {\n            end = price.Key;\n            count += price.Value;\n            totalCount += price.Value;\n            productsRemaining -= price.Value;\n            if (totalCount &gt;= segmentSize * segmentIdx)\n            {\n                ranges.Add(new Tuple&lt;string, string, int&gt;(start, end, count));\n                start = end;\n                count = 0;\n                segmentIdx += 1;\n            }\n            if (segmentIdx == nSegments)\n            {\n                ranges.Add(new Tuple&lt;string, string, int&gt;(start, "*", count + productsRemaining));\n                break;\n            }\n        }\n        return ranges;\n    }\n</code></pre>\n\n<h1>Filter results by selected facet</h1> \n\n<p>Fourth, suppose ("250","500",38) was one of the resulting segments.  If the user selects "$250 to $500" as a filter, simply do a filter query <code>fq=price:[250 TO 500]</code></p>\n'}]
['https://Stackoverflow.com/questions/33956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448/']