How do you filter Algolia Results and omit a specific objectID
Asked Answered
S

1

7

I'm trying to filter algolia results and want to use the name of a product to find similar products in our database. I would prefer to ignore the current product so, in the case no results are found, the removeWordsIfNoResults option will be used.

I'm using the Ruby api.

This is basically what I'm trying but it is not working. Is it possible to filter out a specific objectID?

Product.raw_search("Men's Bridge & Burn Camden Steel Blue", 
  { :hitsPerPage => 10, 
    :page => 0, 
    :attributesToRetrieve => "objectID", 
    :filters => "objectID != '65411'", 
    :removeWordsIfNoResults => 'lastWords' 
  }
)
Smash answered 7/7, 2016 at 0:3 Comment(0)
T
5

objectID is a specific attribute in Algolia that is always a string value and cannot be added to the attributesForFaceting . However, if you're filling it with the ids you have in your database, you can index another attribute (let's say id) with the same value.

Numerical value

As an numerical value, you can directly filter on it using Algolia. However, since you'll only be using the != operator, I recommend you to declare it in the numericAttributesToIndex list with an equalOnly modifier:

index.set_settings({
  numericAttributesToIndex: %w(equalOnly(id))
})

At query time, you can pass it as you did in your example if you remove the quotes around the value:

index.raw_search('Product title', {
  filters: 'id!=65411'
  # Your other parameters
})

String value

With a string value, you want to add it to your attributesForFaceting :

index.set_settings({
  attributesForFaceting: %w(id)
})

Then query it like so:

index.raw_search('Product title', {
  filters: 'id:-65411'
  # Your other parameters
})

(The - for exclusion is described in the facetFilters documentation)

Tensiometer answered 7/7, 2016 at 7:29 Comment(2)
This sounds great. I'll try it outSmash
Worked like a charm. One note - adding numericAttributesToIndex seemed to remove the implicit numericAttributesToIndex that were created by default. I added them back explicitlySmash

© 2022 - 2024 — McMap. All rights reserved.