Force exact match on attribute

I was wondering if there is a way to specify that certain attributes either have an exact match or nothing. For example, I want to match based on exact objectID, but do not want to allow for partial matches of objectID.

@oco I think you could use getObject to retrieve an object by id.

I would be interested whether it’s possible to perform an exact match search for an attribute other than objectID, e.g.

// Objects
// { productId: 'a' },
// { productId: 'aa' },
// { productId: 'aaa' },
// { productId: 'aaaa' }

const result = await index.search({
    query: 'aa',
    restrictSearchableAttributes: ['productId'],
    typoTolerance: false,
});

expect(result.hits.length).toBe(1);
expect(result.hits[0].id).toBe('aa');

I think I figured it out. You need to use filter to perform an exact match. For a filter to work on a non-numeric attribute it must be marked as a facet. If you don’t need the faceting features, e.g. listing values, counts, search etc. you can mark it as filterOnly, e.g.

// Objects
// { productId: 'a' },
// { productId: 'aa' },
// { productId: 'aaa' },
// { productId: 'aaaa' }

await index.setSettings({
    attributesForFaceting: [
        'filterOnly(productId)'
    ]
});

const result = await index.search({
    filters: 'productId:aa'
});

expect(result.hits.length).toBe(1);
expect(result.hits[0].id).toBe('aa');
expect(result.facets).toEqual({});
1 Like

Thanks for the answer, should be in the docs.

This can be used to exact or matches as well:

  await index
  .search(searchValue, {
    filters: 'email:' + searchValue + ' OR phone:' + searchValue
  })

I noticed when I was using algolia UI that you can also wrap your query term in quotes within the string and get an exact match, I’d imagine programmatically you have to use your outer quotes as single and inner as double, but this shows in the raw query builder UI in algolia:

index.search('"744"', { /* any options here */ });
                ^ notice the ' then " -- quotes tell it to exact match

solution: