Skip to content

Blog

Solr Facet Functions and Analytics

Traditional faceted search (also called guided navigation) involves counting search results that belong to categories (also called facet constraints). The new facet functions in Solr extends normal faceting by allowing additional aggregations on document fields themselves. Combined with the new Sub-facet feature, this provides powerful new realtime analytics capabilities. Also see the page about the new JSON Facet API.

Faceting involves breaking up the domain into multiple buckets and providing information about each bucket. There are multiple aggregation functions / statistics that can be used:

Aggregation Example Effect
sum sum(sales) summation of numeric values
avg avg(popularity) average of numeric values
sumsq sumsq(rent) sum of squares
min min(salary) minimum value
max max(mul(price,popularity)) maximum value
unique unique(state) number of unique values (count distinct)
hll hll(state) number of unique values using the HyperLogLog algorithm
percentile percentile(salary,50,75,99,99.9) calculates percentiles
stddev stddev(salary) calculates standard deviation (Solr6.6+)
variance variance(salary) calculates variance (Solr 6.6+)

  Numeric aggregation functions such as avg can be on any numeric field, or on another function of multiple numeric fields.

See Count Distinct in Solr for more information on distributed cardinality estimation / calcDistinct.

 

The faceting domain starts with the set of documents that match the main query and filters. We can ask for statistics over this whole set of documents:

http://localhost:8983/solr/query?q=*:*&
json.facet={x:'avg(price)'}

And the response will contain a facets section:

[...]
"facets":{
"count":32,
"x":164.10218846797943
}
[...]

  If we want to break up the domain into buckets and then calculate a function per bucket, we simply add a nested facet command to the facet parameters. For example (using curl this time):

$ curl http://localhost:8983/solr/query -d 'q=*:*&
json.facet={
categories:{
type : terms, // terms facet creates a bucket for each indexed term (or value) in the field
field : cat,
facet:{
x : "avg(price)",
y : "sum(price)"
}
}
}
'

The response will contain the two stats we asked for in each category bucket.

[...]
"facets":{
"count":32,
"categories":{
"buckets":[
{
"val":"electronics",
"count":12,
"x":231.02666823069254,
"y":2772.3200187683105
},
{
"val":"memory",
"count":3,
"x":86.66333262125652,
"y":259.98999786376953
},
[...]

 

The default sort for a field or terms facet is by bucket count descending. We can optionally sort ascending or descending by any facet function that appears in each bucket. For example, if we wanted to find the top buckets by average price, then we would add sort:"x desc" to the previous facet request:

$ 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)"
}
}
}
'

 

Facet functions and Subfacets are currently only in Solr 5.1. Download the latest release and give it a spin!

Solr Subfacets

Subfacets (also called Nested Facets) is a more generalized form of Solr’s current pivot faceting that allows adding additional facets for every bucket produced by a parent facet.

Subfacet advantages over pivot faceting:

  • Subfacets work with facet functions (statistics), enabling powerful real-time analytics
  • Can add a subfacet to any facet type (field, query, range)
  • A subfacet can be of any type (field/terms, query, range)
  • A given facet can have multiple subfacets
  • Just like top-level facets, each subfacet can have it’s own configuration (i.e. offset, limit, sort, stats)

Subfacets are part of the new Facet Module, and are naturally expressed in the JSON Facet API. Every facet command is actually a sub-facet since there is an implicit top-level facet bucket (the domain) defined by the documents matching the main query and filters. Simply add a facet section to the parameters of any existing facet command.

For example, a terms facet on the “genre” field looks like:

top_genres:{
type: terms,
field: genre,
limit: 5
}

Now if we wanted to add a subfacet to find the top 4 authors for each genre bucket:

top_genres:{
type: terms,
field: genre,
limit: 5,
facet:{
top_authors:{
type: terms,
field: author,
limit: 4
}
}
}

Assume we want to do the following complex faceting request:

  • Facet on the “genre” field and find the top buckets
  • For ever “genre” bucket generated above, find the top 7 authors
  • For ever “genre” bucket, create a bucket of high popularity items (defined by popularity 8 - 10) and call it “highpop”
  • For ever “highpop” bucket generated above, find the top 5 publishers

In short, this request finds the top authors for each genre and finds the the top publishers for high popularity books in each genre. Using the JSON Facet API, the full request (using curl) would look like the following:

$ curl http://localhost:8983/solr/query -d 'q=*:*&
json.facet=
{
top_genres:{
type: terms,
field: genre,
facet:{
top_authors: {
type : terms, // nested terms facet
field: author,
limit: 7
},
highpop:{
type : query, // nested query facet
q: "popularity:[8 TO 10]", // lucene query string
facet:{
publishers:{
type: terms, // nested terms facet under the nested query facet
field: publisher,
limit: 5
}
}
}
}
}
}
'

An example response would look like the following:

[...]
"facets":{
"top_genres":{
"buckets":[{
"val":"Fantasy",
"count":5432,
"top_authors":{ // these are the top authors in the "Fantasy" genre
"buckets":[{
"val":"Mercedes Lackey",
"count":121},
{
"val":"Piers Anthony",
"count":98}]}},
"highpop":{ // bucket for books in the "Fantasy" genre with popularity between 8 and 10
"count":876
"publishers":{ // top publishers in this bucket (highpop fantasy)
"buckets":[{
"val":"Bantam Books",
"count":346},
{
"val":"Tor",
"count":217}]}},
{
"val":"Science Fiction", // the next genre bucket
"count":4188,
[...]

  All the reporting and sorting was done using document count (i.e. number of books). If instead, we wanted to find top authors by total revenue (assuming we had a “sales” field), then we could simply change the author facet from the previous example as follows:

top_authors:{
type: terms,
field: author,
limit: 7,
sort: "revenue desc",
facet:{
revenue: "sum(sales)"
}
}

 

Facet functions and Subfacets are in Solr 5.1 and later, but the syntax used on this page requires Solr 5.3 or later. Download the latest release and give it a spin!

Solr 5.1 Features

Solr 5.1 has been released! Here’s an overview of how to use some of the new features.

Also see Solr download links and upcoming features of the next Solr release.

The new facet module has a native JSON Facet API, first-class support for statistics and analytics via facet functions (aggregations), and supports unlimited nesting of facets within other facets via sub-facets.

One can calculate statistics such as averages, number of unique values (distinct values), and percentiles over each facet bucket (groups of documents), and even sort facet buckets by any calculated metrics.

A JSON Request API that allows passing a full Solr query request in JSON.

Example:

curl http://localhost:8983/solr/query -d '
{
query : "*:*",
filter : [
"author:brandon",
"genre_s:fantasy"
],
offset : 0,
limit : 5,
fields : ["title","author"], // we could also use the string form "title,author"
sort : "sequence_i desc",
facet : { // the JSON Facet API is nicely integrated as well
avg_price : "avg(price)",
median_price : "percentile(price,50)",
top_authors : {terms : author}
}
}'

Parameter substitution is now done across the entire query request. It supports default values, multiple levels of indirection, and it even works within the body of a JSON request. This can also be viewed as a powerful form of request templates.

Example:

q=price:[ ${low} TO ${high} ]
&low=100
&high=200

Parameters can also be passed in the params block of a JSON request.

Syntax within the standard lucene/solr query parser for constant score queries quit the general form of ^=<constant_score>. Think of a query boost with ^ replaced with ^=. Example:

q=(color:blue color:green)^=2.0 text:shoes

There is a new general purpose parallel computing framework for SolrCloud. The Streaming API is (currently) a Java API that can do streaming aggregations (like sum and average) and streaming transformations (like group-by and join).

The admin UI can show segment info such as size, number of docs, and number of deletions for each segment in the index. For the “demo” collection, simply point your browser at http://localhost:8983/solr/#/demo/segments Or click on the “Segments Info” link in the admin UI after you select the core/collection you are interested in. segments_info

The bulk schema API how has the ability to replace or remove fields, fieldTypes, dynamic fields, and copy fields.

Example of adding a field (this was already possible):

curl http://localhost:8983/solr/demo/schema -d '
{
"add-field":{
"name" : "powerLevel",
"type" : "int",
"indexed" : true,
"stored" : true
}
}'

Now we can replace the field definition:

curl http://localhost:8983/solr/demo/schema -d '
{
"replace-field":{
"name" : "powerLevel",
"type" : "int",
"indexed" : false,
"stored" : true
}
}'

We can verify that Solr now has the updated field definition with

curl http://localhost:8983/solr/demo/schema/fields/powerLevel

And solr returns:

"field":{
"name":"powerLevel",
"type":"int",
"indexed":false,
"stored":true}

And lastly, we can delete the field definition with

curl http://localhost:8983/solr/demo/schema -d '
{
"delete-field":{ "name" : "powerLevel" }
}'

Solr can now execute a two dimensional facet on RPT field types (Spatial Recursive Prefix Tree).

Parameters Example:

q=*:*
&facet=true
&facet.heatmap=location_rpt
&facet.heatmap.geom=["-180 -90" TO "180 90"]
&facet.heatmap.gridLevel=6
&facet.heatmap.distErrPct=0.15
&facet.heatmap.format=ints2D

The facet.heatmap.format=ints2D parameter causes a 2D array of counts to be returned:

{
"counts_ints2D":[[4, 0, 1, 3, ....],[2, 0, 1, 2, ...],...]
}

If facet.heatmap.format=png is passed instead, a basic base64-encoded PNG (picture) will be returned of the heatmap grid.

There is now an explicit API in SolrJ to use Real-time Get

HttpSolrClient client = new HttpSolrClient("http://localhost:8983/solr/demo");
SolrDocument sdoc = client.getById("book1");
System.out.println("I found book " + sdoc);
client.close(); // shut down the client when we are done

StatsComponent Enable/disable individual stats

Section titled “StatsComponent Enable/disable individual stats”

Localparams may now be used to selectively enable or disable specific stats in the StatsComponent. Example: stats.field={!min=true max=true}field_name

Both the new facet module and the stats component gained support for percentiles.

json.facet={ median_age : "percentile(age,50)" }
stats.field={!percentiles='50'}age

Many additional configuration items can now be managed via the Config API. This includes managing named components such as requestHandler, queryParser, queryResponseWriter, valueSourceParser, transformer, and queryConverter.

Changes do not directly change solrconfig.xml, but instead are reflected in configoverlay.json which override settings in solrconfig.xml.

Upload config sets to zookeeper with CloudSolrClient

Section titled “Upload config sets to zookeeper with CloudSolrClient”

Named config sets (schema.xml, solrconfig,xml, etc) are referenced by name when creating new collections in SolrCloud. These config sets may now be uploaded and downloaded via SolrJ to and from the local filesystem. The following methods were added to CloudSolrClient:

public void uploadConfig(Path configPath, String configName);
public void downloadConfig(String configName, Path downloadPath);

There is a new API to add a jar to a collection’s classpath (as well as update and delete a jar). Components that depend on such a jar should have a new attribute called runtimeLib set to true since a separate classloader is used for these jars.

Example of uploading a jar:

curl http://localhost:8983/solr/demo/config -d '{
"add-runtimelib" : {"name": "jarname" , "version":2 }
}'

Example registering a new value source parser using a class in the jar:

curl http://localhost:8983/solr/demo/config -d '{
"create-valuesourceparser" : {
"name": "nvl",
"runtimeLib" : true,
"class" : "solr.org.apache.solr.search.function.NvlValueSourceParser ,
"nvlFloatValue" : 0.0
}
}'

Solr 5.2 Features

Here’s an overview of some of the new features in Solr 5.2 Also see Solr download links and upcoming features of the next Solr release.

Caches using the LRUCache implementation can specify a new parameter maxRamMB that will evict based on RAM use rather than number of elements in the cache. Least recently used items are evicted until the RAM use is brought under the limit. RAM use calculations do not currently cover the cache keys, so using this for the query cache and caching large queries can still lead to greater memory use than expected.

To make a backup, we can send a request to the replication handler:

curl -XPOST "http://localhost:8983/solr/demo/replication?command=backup&name=my_backup100"

This will create a backup of the index in Solr’s data directory (this can be changed via the location parameter) named snapshot.my_backup100

This index snapshot can later be restored with the following command:

curl -XPOST "http://localhost:8983/solr/demo/replication?command=restore&name=my_backup100"

Flatter request structure for the JSON Facet API

Section titled “Flatter request structure for the JSON Facet API”

Here’s an example of a terms facet in Solr 5.1:

top_authors : { terms : {
field : author,
limit : 5,
}}

In the Solr 5.2 JSON Facet API, the “type” can optionally be specified in the same object as the facet arguments:

top_authors : {
type : terms,
field : author,
limit : 5
}

Range facets now support the mincount parameter to screen out range facet buckets that don’t meet a minimum document count.

prices:{
type:range,
field:price,
mincount:1,
start:0, end:100, gap:10
}

The unique facet function now works on numeric and date fields. Example:

json.facet={
num_codes : "unique(error_code)"
}

Multi-select faceting is a powerful faceting style that allows users to see and select multiple facet constraints (facet values) for a facet. For example, one may want to select multiple price ranges or multiple colors they are interested in.

The new Facet Analytics Module / JSON Facet API now supports multi-select faceting via filter exclusions. A new excludeTags parameter will disregard any top-level filters with matching tags.

Here’s a Multi-Select Faceting Example, using the JSON Facet API.

Both the older Stats component and the new Facet Analytics Module have added support for HyperLogLog based statistical cardinality estimate. For the JSON Facet API, a new hll facet function was added as an alternative to the existing faster (but less accurate for high cardinality) unique function. Example:

json.facet={ numProducts : "hll(product_id)" }

See Solr Count Distinct functionality for examples that calculate the number of distinct values in a given field per facet bucket.

“facet.range.method” (traditional query-parameter API)

Section titled ““facet.range.method” (traditional query-parameter API)”

Add a new “facet.range.method” parameter to let users choose how to do range faceting between an implementation based on filters (previous algorithm, using “facet.range.method=filter”) or DocValues (“facet.range.method=dv”). Input parameters and output of both methods are the same.

If you have a field value that consists of well formed XML or JSON, you can return those raw values in the appropriate response writer. Example: ?fl=id,name,json_s:[json],xml_s:[xml]

This new SolrCloud feature allows the specification of rules which govern placement of replicas in the cluster. Rules are specified during collection creation and persisted in zookeeper.

See the blog post from LucidWorks for further details and examples.

Solr Streaming Expressions adds an expression based interface to the Streaming API added in Solr 5.1.

Some examples from include

// merge two distinct searches together on common fields
merge(
search(collection1, q="id:(0 3 4)", fl="id,a_s,a_i,a_f", sort="a_f asc, a_s asc"),
search(collection2, q="id:(1 2)", fl="id,a_s,a_i,a_f", sort="a_f asc, a_s asc"),
on="a_f asc, a_s asc")
// find top 20 unique records of a search
top(
n=20,
unique(
search(collection1, q=*:*, fl="id,a_s,a_i,a_f", sort="a_f desc"),
over="a_f desc"),
sort="a_f desc")

See the Solr Reference Guide for more documentation.

An authentication framework and Kerberose authentication module. See the Security section of the Solr Reference Guide.

Percentiles for Solr Faceting

The percentile aggregation function was just added to the new Solr Facet Module. This allows one to calculate one or more percentiles for each facet bucket (i.e. each group of documents produced by faceting), and even sort facet buckets by any given percentile.

The percentile aggregation even works with distributed search! The algorithm used is Ted Dunnings “t-digest”, which gives good approximations with relatively little memory consumption.

NOTE: requires Solr 5.3 or later.

First, let’s start Solr and create a “demo” collection.

$ bin/solr start
$ bin/solr create -c demo
# HINT: use "bin/solr stop -all" when you're finished.

Now, lets index some salary survey data in CSV format, using dynamic fields:

$ curl http://localhost:8983/solr/demo/update?commitWithin=5000 -H 'Content-type:text/csv' -d '
id,gender_s,loc_s,year_i,job_s,salary_d
mark,M,NJ,2011,clerk,21250
john,M,NY,2011,engineer,42500
mary,F,CT,2015,manager,87299
alice,F,NJ,2013,dentist,75000
mike,M,NY,2012,sales,59500
nancy,F,CT,2014,engineer,110000
greg,M,NJ,2012,manager,74000
cindy,F,NJ,2012,engineer,81000
janet,F,NJ,2015,clerk,30150
joe,M,NY,2014,dentist,74000
luke,M,CT,2015,dentist,78000
zoe,F,NY,2013,manager,89500
eli,M,CT,2011,sales,66000
anna,F,CT,2012,sales,59500
evan,M,NY,2014,clerk,2920
'

Now we can use Solr’s analytics / facet functions to slice and dice our data!

Let’s say we want the 25%, 50%, and 75% percentile salaries across all our jobs:

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&json.facet={salary_percentiles:"percentile(salary_d,25,50,75)"}'

And at the end of our response, we’ll get our facet results:

[...]
"facets" : {
"count" : 15,
"salary_percentiles" : [51000.0, 74000.0, 79500.0]
}
}

  We can add in other statistics such as the average salary, the number of different jobs, and the number of different states in our salary survey:

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&
json.facet={
average_salary : "avg(salary_d)",
num_jobs : "unique(job_s)",
num_states : "unique(loc_s)",
salary_percentiles : "percentile(salary_d,25,50,75)"
}'
"facets":{
"count":15,
"average_salary":63374.6,
"num_jobs":5,
"num_states":3,
"salary_percentiles":[51000.0,74000.0,79500.0]
}

  Now let’s take a look at median salary broken out by gender:

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&
json.facet={
by_gender:{
type:terms
field:gender_s,
facet:{
median_salary:"percentile(salary_d,50)"
}
}
}'
"facets":{
"count":15,
"by_gender":{
"buckets":[
{
"val":"M",
"count":8,
"median_salary":62750.0
},
{
"val":"F",
"count":7,
"median_salary":81000.0
}
]
}
}

  We can also sort by a percentile statistic. If you request more than one percentile value, the sort will be on the first value in the list requested. Let’s find the top states by 99.9th percentile salary:

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&
json.facet={
rich_states:{
type : terms,
field : loc_s,
sort : {sal:desc}, // specifying the sort as a string, like sort:"sal desc" will also work
facet : {
sal : "percentile(salary_d,99.9)"
}
}
}'
"facets":{
"count":15,
"rich_states":{
"buckets":[{
"val":"CT",
"count":5,
"sal":109909.19600000001},
{
"val":"NY",
"count":5,
"sal":89438.00000000001},
{
"val":"NJ",
"count":5,
"sal":80976.0}]}}

  We can get even more interesting by nesting facets. How about finding the highest earning occupation (99.9th percentile) for every state?

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&
json.facet={
states:{
type:terms,
field:loc_s,
facet:{
top_jobs:{ // nested terms facet
type : terms,
field : job_s,
sort : "sal desc", // sort will be on first percentile (99.9)
limit : 1, // only show top occupation
facet:{
sal : "percentile(salary_d,99.9,50,10)"
}
}
} // end facet block for the loc_s field
}
}'

The response has been omitted since we don’t have enough data for it to be interesting.

  We can also show how median salary has changed over time for each individual state:

$ curl http://localhost:8983/solr/demo/query -d 'q=*:*&
json.facet={
states:{
type:terms,
field:loc_s,
facet:{
over_time:{ // nested range facet
type : range,
field : year_i,
start : 2011,
end : 2015,
gap : 1,
facet:{
median_salary : "percentile(salary_d,50)"
}
}
} // end facet block for the loc_s field
}
}'
"facets":{
"count":15,
"states":{
"buckets":[{
"val":"CT",
"count":5,
"over_time":{
"buckets":[{
"val":2011,
"count":1,
"median_salary":66000.0},
{
"val":2012,
"count":1,
"median_salary":59500.0},
{
"val":2013,
"count":0},
{
"val":2014,
"count":1,
"median_salary":110000.0}]}},
{
"val":"NJ",
"count":5,
"over_time":{
"buckets":[{
"val":2011,
"count":1,
"median_salary":21250.0},
{
"val":2012,
"count":2,
"median_salary":77500.0},
{
"val":2013,
"count":1,
"median_salary":75000.0},
{
"val":2014,
"count":0}]}},
{
"val":"NY",
"count":5,
"over_time":{
"buckets":[{
"val":2011,
"count":1,
"median_salary":42500.0},
{
"val":2012,
"count":1,
"median_salary":59500.0},
{
"val":2013,
"count":1,
"median_salary":89500.0},
{
"val":2014,
"count":2,
"median_salary":38460.0}]}}]}}

Noggit, the JSON Streaming Parser

Noggit is the world’s fastest streaming JSON parser for Java.

Section titled “Noggit is the world’s fastest streaming JSON parser for Java.”

Noggit is the streaming JSON parser used in Solr. It lives here on github.

Noggit supports a number of extensions to the JSON grammar. All of these extensions are optional and may be disabled.

{ // This is a single line comment
# This is also a single line comment
/* This is a multi-line
* C-style comment.
*/
}
{
first : Yonik,
last : Seeley
}

JSON strings are normally encapsulated by double quotes. It’s often desirable to use single quotes if for example you are embedding some JSON in another double quoted string in a program.

['how', 'now', 'brown', 'cow']

Sometimes one may not know exactly what characters need to be backslash escaped. It can be useful to accept this without throwing an exception.

'This is just a " string'

Allowing trailing commas or extra commas can make it easier to produce JSON that doesn’t throw a parse exception. One use-case is templating JSON. Given the following template,

{
filters:["instock:true", ${FILT1}]
} # Note: templating is not part of JSON or Noggit... but may happen before parsing.

If FILT1 is not defined and is replaced with empty space, this results in the following JSON:

{
filters:["instock:true", ] // this will be parsed as filters:["instock:true"]
}

Noggit ignores all extra commas, not just trailing commas:

[
[,] // equivalent to []
, {,} // equivalent to {}
, [,,3,,,6,,] // equivalent to [3,6]
]

Large string values can optionally be handled in a streaming fashion a piece at a time. Noggit will only construct a single String object in memory if asked. This allows for stream processing with very little memory overhead.

{
"big_string" : "A very large string... pretend its's 1GB in size... we can process it and send it on without reading it all into memory at once!"
}

Noggit can handle huge values that are JSON compliant but may be too large to be parsed into a Java primitive.

{
"big_int" : 1234567890987654321334325343534535342325786237862578625725867258672356711107,
"big_float" : 112412133377778226524562431234215423.23421434645743234564758453322342,
"big_sci" : 2.342669039282149050282364845982748592e-94321
}

Noggit can also handle multiple JSON values streamed over a single connection and simply catenated together. Primitive values should of course be separated by whitespace to avoid ambiguity.

{first_object:10}
['another array object']['yet another object']
{more:objects}{another:object}
['who knows how many json values will be streamed by the writer...']
42
"is this the end?"

Noggit can parse huge JSON messages with minimal overhead.

  • A single byte of state needed per nested object or array. This is needed to keep track of the type of enclosing entity.
  • A user can optionally provide an input buffer for Noggit to use when parsing from a Reader, allowing re-use across different parsers and thus lower memory consumption and garbage collection activity.
  • Streaming values: very large values (such as strings) can be obtained in chunks, thus the whole value never needs to reside in memory at once.

Switching between Java7 and Java8 in Lucene/Solr

Lucene/Solr trunk (the future 6.0 release) is now on Java8, while version 5.x is still on Java7. Linux and Windows allows one to install a JDK any place in the filesystem, and I use the convention of installing in /opt/jdk7 and /opt/jdk8. Things are a little more difficult on Mac OS-X however, as you can’t chose the install location. Luckily there is a command called java_home to show you where a JDK is installed.

Here’s a snippet from my .profile to help manage working with different java versions:

Terminal window
OS=`uname`
case "$OS" in
CYGWIN*)
OS=cygwin
OPT=c:/opt
;;
*)
OPT=/opt
;;
esac
set-java () {
export JAVA_HOME="$*"
if [ $OS = "cygwin" ]; then
export PATH="`cygpath $JAVA_HOME/bin`:$PATH"
else
export PATH="$JAVA_HOME/bin:$PATH"
fi
}
if [ $OS = "Darwin" ]; then
JAVA7=`/usr/libexec/java_home -v 1.7`
JAVA8=`/usr/libexec/java_home -v 1.8`
else
JAVA7=$OPT/jdk7
JAVA8=$OPT/jdk8
fi
set-java $JAVA8

Now, if I switch from working on trunk to working on Lucene 5 or Solr 5, I can easily switch the default JDK for a single terminal via the set-java shell function.

Terminal window
/opt/heliosearch$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
/opt/heliosearch$ set-java $JAVA7
/opt/heliosearch$ java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)
/opt/heliosearch$

Solr Terms Query for matching many terms

Solr 4.10 and Heliosearch .07 have added a terms query (or terms filter) to more efficiently match many terms in a single field. A large number of terms are often useful for things like access control lists or security filters. Previously, the only way to do this was a large boolean query with many clauses, which has unnecessary overhead when scoring is not needed.

Solr’s implementation uses Lucene’s TermFilter class, as does Elasticsearch’s terms filter.

The Heliosearch terms query implementation has some additional features:

  • prefix compression including off-heap construction
  • direct creation of off-heap filter for faster execution and less garbage production
  • native code bit-setting
  • ability to skip sorting the terms if desired

For reference, specifying a filter query (fq) in the normal lucene syntax via a boolean query looks like the following (assumes default boolean operator of OR):

fq=id:doc334 id:doc125 id:doc777 id:doc321 id:doc253

or in a more compact form, like:

fq=id:(doc334 doc125 doc777 doc321 doc253)

Be aware that going over the limit of 1024 terms in Solr will cause an exception by default. Heliosearch has no such limit.

The corresponding new terms query in both Solr and Heliosearch is:

fq={!terms f=id}doc334,doc125,doc777,doc321,doc253

Performance of terms queries is shown relative to using a Boolean query in Solr. For example the last column in the first chart represents a 10 term filter that matches 10,000,000 documents (1 million per term). The request execution time is:

  • 381,342 microseconds with a Solr Boolean Querty
  • 122,119 microseconds with a Solr Terms Query
  • 67,075 microseconds with a Heliosearch Terms Query

Benchmark details:

  • 10M document index
  • 64 bit Java 1.8.0_20 Oracle JDK
  • Windows 8 64 bit, quad-core Intel i5-3570K @ 3.4GHz
  • Request time was measured externally and includes the entire request time, including the time for the client to send the request and read the response.
  • Solr versions: Apache Solr 4.10.0, Heliosearch 0.07 (based on Solr 4.10)

  The first set of tests consist of 10 term queries that match various number of documents.: terms_perf_10

  The next set of tests deal with 100 term queries that match various number of documents: terms_perf_100

  And finally the last test deals with term queries on the id field (i.e. each term matches a single document): terms_perf_ids

The first performance tests were run multiple times and the amount of garbage produced was recorded. terms_perf_memory

The Heliosearch off-heap optimizations clearly pay dividends here, resulting in much less heap usage, less garbage production (which will mean less garbage collection work), and a smaller process size.

Native Code Faceting

Native code faceting for Solr has just been added to Heliosearch, and benchmarks show an impressive 2x performance increase! This is faceting code written in C++ and statically compiled for maximum performance, and loaded into the JVM via JNI (Java Native Interface).

nCache, Heliosearch’s off-heap version of the Lucene/Solr FieldCache, was instrumental in allowing this level of optimization. Java arrays (and other on-heap memory) cannot be efficiently accessed from native code. Moving the data structures off-heap not only provided great decreases in garbage collection overhead, but also allowed for practical native code optimizations. Top-level nCache string support was recently added, paving the way for native code faceting on single valued string fields.

Benchmark details:

  • 10M document index
  • Documents consist of an ID field, and 6 different single-valued string fields with varying numbers of unique values ranging from 10 to 1 Million
  • Faceting request throughput was measured for 1000 requests after 50 request warmup.
  • Client had 4 request threads
  • Each individual client request uses a random field to make the test realistic and to avoid hotspot overspecializing the code for a specific field.
  • Solr versions: Apache Solr 4.8.1, Heliosearch/Solr snapshot (based on Solr 4.9)

native_faceting_perf

  The different operating systems were run on different hardware (hence the large performance differences of the same code across the different platforms).

OS CPU Native code compiler performance vs solr
Ubuntu Linux 13.10 quad core AMD Phenom II gcc 4.7.3 227%
Windows 8.1 quad core Intel i5 gcc 4.8.2 202%
OS-X Mavericks 10.9.3 dual core Intel i5 gcc 4.8.2 246%
OS-X Mavericks 10.9.3 dual core Intel i5 LLVM 5.1 235%

 

The gcc/g++ included with OS-X is actually clang/LLVM - clang is the C language front end and LLVM is the back end that produces executable code. At least for this initial native code, g++ 4.8.2 was about 5% faster than clang/LLVM 5.1, hence we’ll most likely use gcc/g++ by default. The easiest way to get gcc/g++ on your Mac is

$ brew install gcc48

After installation, gcc/g++ will continue pointing to the clang/LLVM versions, but there will be gcc-4.8 and g++-4.8 you can use in /usr/local/bin.

 

Besides the incredible over 2x faceting performance improvement, native code has other advantages as well:

  • Avoidance of Java hotspot bugs in compiling code. Compiling the code just once statically means it’s the same for every run, for everyone.
  • No variations from run-to-run due to how hotspot compiles the code (unexplained slowdowns).
  • No hotspot warm-up period, or time spent optimizing, or de-optimizing code.

It’s easy to take advantage of these performance improvements and new features since Heliosearch/Solr is currently a drop-in replacement (at the HTTP-API level) for Apache Solr. Download the latest release and try it out.

We’d love to hear how it’s working for you… drop by the user mailing list and let us know. Want to dabble in C/C++ code again? Drop by the dev mailing list to help out with development!

Solr Cross Data Center Replication

Solr needs a flexible cross-datacenter architecture that can handle both a variety of application needs as well as a variety of infrastructure resources.

  • Accommodate 2 or more data centers
  • Accommodate active/active uses
  • Accommodate limited band-with cross-datacenter connections
  • Minimize coupling between peer clusters to increase reliability
  • Support both full consistency and eventual consistency

Issues with running SolrCloud cross data center

Section titled “Issues with running SolrCloud cross data center”

Running a single SolrCloud cluster across two data centers can be done, but has multiple drawbacks:

  • Same update is forwarded multiple times (once per replica) over the bandwidth limited cross-DC pipe.
  • Can’t implement extra compression or security
  • Requires a 3rd data center to contain a zookeeper node for tie-breaking
  • Burst indexing limited by cross-DC bandwidth.
  • Lack of a true backup cluster if the cluster gets into a bad state
  • Extra latency for all indexing operations
  • Search requests are not data center aware (extra latency + bandwidth)
  • Normal recovery mechanism (full index copy) may not be viable across DC connections

Clusters will be configured to know about each other, most likely through keeping a cluster peer list in zookeeper. One essential piece of information will be the zookeeper quorum address for each cluster peer. Any node in one cluster can know the configuration of another cluster via a zookeeper client.

Update flow will go from the shard leader in one cluster to the shard leader in the peer clusters. This can be bi-directional, with updates flowing in both directions. Updates can be either synchronous or asynchronous, with per-update granularity.

Solr transaction logs are currently removed when no longer needed. They will be kept around (potentially much longer) to act as the source of data to be sent to peer clusters. Recovery can also be bi-directional with each peer cluster sending the other cluster missed updates.

  • Scalable – no required single points of aggregation / dissemination that could act as a bottleneck.
  • Per-update choice of synchronous/asynchronous forwarding to peer clusters.
  • Peer clusters may have different configuration, such as replication factor.
  • Asynchronous updates allow for bursts of indexing throughput that would otherwise overload cross-DC pipes.
  • “Push” operation for lowest latency async updates.
  • Low-overhead… re-uses Solr’s existing transaction logs for queuing.
  • Leader-to-leader communication means update is only sent over cross-DC connection once.

CDCR

  1. An update will be received by the shard leader and versioned
  2. Update will be sent from the leader to it’s replicas
  3. Concurrently, update will be sent (synchronously or asynchronously) to the shard leader in other clusters
  4. Shard leader in the other cluster will receive already versioned update (and not re-version it), and forward the update to it’s replicas

The shard leader versions a document and then forwards it to replicas. Update re-orders are handled by the receiver by dropping updates that are detected to be older than the latest document version in the index. This works given that complete documents are always sent to replicas, even if it started as a partial update on the leader.

Solr version numbers are derived from a timestamp (the high bits are milliseconds and the low bits are incremented for each tie in the same millisecond to guarantee a monotonically increasing unique version number for any given leader).

If updates are accepted for the same document in two different clouds (implying two different leaders versioning the document), then having the correct last document “win” relies on clock synchronization between the two leaders. Updates to the same document at different data centers within the clock skew time risk being incorrectly ordered.

Solr only has versions at the document level. The current partial update implementation (because of other constraints) reads the current stored fields of the document, makes the requested update, and indexes the new resulting document. This creates a problem with accepting Solr atomic updates / partial updates to the same document in both data-centers.

Example:

DC1: writes document A, version=time1
DC2: receives document A (version=time1) update from DC1
DC1: updates A.street_address (Solr reads version time1, writes version time2)
DC2: updates A.phone_number (Solr reads version time1, writes version time3)
DC1: receives document A (version=time3) from DC2, writes it.
DC2: received document A (version=time2) from DC1, ignores it (older version)

Although both data-centers became “consistent”, the partial update of street_address was completely lost in the process.

Option 1: Configure the update for full synchronization. All peer clusters must be available for any to be writeable.

Option 2: Use client versioning, where the update clients specify a user-level version field.

Option 3: For a given document, consider one cluster the primary for the purposes of document changes/updates. See “Primary Cluster Routing”.

To deal with potential update conflicts arising from updating the same document in different data centers, each document can have a primary cluster.

A routing enhancement can ensure that a document sent to the wrong cluster will be forwarded to the correct cluster.

Routing can take as input a request parameter, a document field, or the unique id field. The primary cluster could be determined by hash code (essentially random), or could be determined by a mapping specified in the cluster peer list. Changes to this mapping for fail-over would not happen automatically in Solr. If a data center becomes unreachable, the application/client layers have responsibility for deciding that a different cluster should become the primary for that set of documents.

Primary cluster routing will be optional. Many applications will naturally not trigger the type of undesirable update behavior described, or will have the ability to work around update limitations.

Implement true partial updates with vector clocks and/or finer grained versioning so that updates to different fields can be done conflict free if re-ordered. This would also lower the bandwidth costs of partial updates since the entire document would no longer be sent to all replicas and to other peer clusters.

One could potentially further minimize cross-DC traffic by introducing traffic aggregator nodes (one per cluster) that all udpates would flow through. This would likely only improve bandwidth utilization in low update environments. The improvements would come from fewer connections (and hence less connection overhead) and better compression (a block of many small updates would generally have a better compression ratio than the same updates compressed individually).

Many zookeeper clients in a peer cluster could generate significant amounts of traffic between data centers. There could be a designated listener to the remote cluster state that could disseminate this state to others in the local cluster rather than hitting ZK directly.

Also worth investigating is the use of a local zookeeper observer node that could service all local ZK reads for the remote ZK quorum.

The first phase of this design only deals with updates. Collection level operations such as adding a new shard, splitting a shard, and changing replication levels, must be performed by the client on every cluster as applicable.

The collections API (and other higher level APIs) could be made peer-aware such that these operations would also be forwarded to peer clusters, as well as including a queuing mechanism for the cases when a peer cluster is unreachable.

Forwarding of updates from one cloud to another should be done via standard SolrJ client. Any needed enhancements/modification should be done to a SolrJ client such that those enhancements may also be used in other contexts.