Multi facets and lucene – behind the scenes

So how does the code from the previous article on and the MultiFacetLuceneNet library I have published work?

Well the secret lies in how to run the facet queries. Basically when calculating facets from field “X” we need to dynamically create a query – the original MINUS the X term selection. And same thing when calculating facets for field “Y” we need to remove the Y selection from the original query.

Have a look at the CreateFacetedQuery function.

protected Query CreateFacetedQuery(Query baseQueryWithoutFacetDrilldown, IEnumerable<SelectedFacet> selectedFacets, string facetAttributeFieldName)
    var facetsToAdd = selectedFacets.Where(x => x.FieldName != facetAttributeFieldName).ToList();
    if (!facetsToAdd.Any()) return baseQueryWithoutFacetDrilldown;
    var booleanQuery = new BooleanQuery {{baseQueryWithoutFacetDrilldown, Occur.MUST}};
    foreach (var selectedFacet in facetsToAdd)
        if (selectedFacet.SelectedValues.Count == 1)
            booleanQuery.Add(new TermQuery(new Term(selectedFacet.FieldName, selectedFacet.SelectedValues[0])), Occur.MUST);
            var valuesQuery = new BooleanQuery();
			foreach (var value in selectedFacet.SelectedValues)
				valuesQuery.Add(new TermQuery(new Term(selectedFacet.FieldName, value)), Occur.SHOULD);
			booleanQuery.Add(valuesQuery, Occur.MUST);
	return booleanQuery;

As you can see we feed it with the selected facets (could be “COLOR:blue+green”, “SIZE:Medium” ) but exclude the facet matching the current one we are calculating (facetAttributeFieldName)

Which means when we calculate the COLOR facets we well generate a query saying {original query} AND SIZE:’Medium’

Likewise when we calculate the CATEGORY facets the query will be {original query} AND (COLOR:’blue’ or COLOR:’green’)

Next post will describe the actual facet calculation algoritm, along with the stupid mistake I did which (when found out) gave me 100x times better performance…(the “100x times faster” checkin at )

Also: dont miss the NUGET package for MultiFacet Lucene.NET


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s