Facets are used for grouping documents based on some criteria, for example specific terms or date range.
Term facets group terms, words, or whole strings, and provide a count for each. To retrieve a term facet using the fluent API, use the `
TermsFacetFor` and `
TermsFacetFor` method works on exact values in strings in a case sensitive manner. So, "Foo", "foo," and "foo bar" are treated as three different terms.
TermsFacetForWordsIn` method works on analyzed values of strings in a case-insensitive manner. So, it treats each word in a string a separate term. With this method "Foo", "foo," and "foo bar" are treated as two terms, "foo" and "bar".
Both methods work on values of type string and `
IEnumerable` of string. Also, both have an overload that lets you specify the number of terms to return. Unless specified, 10 is the default number of items returned for a facet. To return more items, use `
x.Size` as in the example below.
Before providing examples, we need to provide a context. Assume there is a class with a string property, a list of strings property, and a property of a complex type that also has a string property.
Assume you indexed three instances of this class with the following values:
|Ten Little Indians||crime, fiction||Agatha Christie|
|The Origin of Species||science||Charles Darwin|
|David Copperfield||scifi, fiction||Charles Dickens|
### Retrieve a tag cloud
Use the `
TermsFacetFor` method to retrieve a list of the most common tags in a search request.
Use the `
Take` method to exclude actual search results, since you are not interested in them in this scenario.
After getting the search results, you can extract the terms facet for the tags.
The above code prints: fiction: 2 crime: 1 science: 1 scifi: 1
### Group authors
If you modify the code to instead retrieve a terms facet for author name, the code would look like this.
The above code prints: Agatha Christie: 1 Charles Darwin: 1 Charles Dickens: 1
### Group by single words
In contrast, if you used the `
TermsFacetForWordsIn` method (instead of the `
TermsFacetFor` method) in the above code, it prints: