maxValuesPerFacet or maxFacetHits doesn't seem to work as expected

I have the following facet: "type"
I have the following data:

{
  type: 'OBJECT',
  name: 'item1'
},
{
  type: 'OBJECT',
  name: 'item2'
},
{
  type: 'FIELD',
  name: 'item1'
},
{
  type: 'FIELD',
  name: 'item2'
},

I’m searching for the string “it”, and with filters: "type:OBJECT OR type:FIELD". I want to get just 1 result for each type.
I tried using

index.setSettings({
  maxValuesPerFacet: 1
});

I even tried:

index.setSettings({
  maxFacetHits: 1
});

Expected:

//one item for type OBJECT
{
  type: 'OBJECT',
  name: 'item1'
},
//and another for type FIELD
{
  type: 'FIELD',
  name: 'item1'
}

Actual:
All 4 items are showing. My problem is that I have 200 items of type “OBJECT” and so I don’t even see any items of type “FIELD”.

Hello! Thanks for reaching out. It sounds like you’re trying to just get one result per facet from a single API call. As it turns out, the facet settings you’ve indicate won’t help you here - allow me to explain.

maxValuesPerFacet is used to configure the number of actual facets that can be returned for a given query, not the number of results that match a given facet. For example, imagine that instead of just type: '<OBJECT|FIELD>', you had type: '<OBJECT|FIELD|APPLE|HORSE|YUKON|[...]>', then maxValuesPerFacet would allow you to restrict the number of returned facets; if it were set to 3 you may receive <OBJECT|FIELD|APPLE>.

There are other ways to get the behaviour that you’re looking for. Here are two examples:

Example 1: Make two API requests (one for each of type: 'OBJECT' and type: 'FIELD' respectively) and then display them together as you like. Code: https://jsfiddle.net/kz0tzre6/2/

Example 2: Make use of the deduplication feature which allows results to match on distinct attributes. This feature needs to be enabled as it changes the behaviour of your index - which means you’ll need to disable it at search time if you don’t want it - but it’ll do exactly what you want with only one query. Code: https://jsfiddle.net/4d6chgno/1/

I would suggest going with Example 2 as it requires fewer lines of code and is demonstrably more readable (and thus easier to maintain over time).

I hope that answers your question. If you need anything else, please don’t hesitate to ask!

1 Like