How to use secured key with filter constraints in a multi-index query?

In the example on https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#examples a single client (with API key) is used to execute the multiple queries. How does a secured key with filter constraints work in this context?

For instance, say I have 2 indexes, orders and movies, with the following attributes:

  • orders
    • number
    • userId
    • title
  • movies
    • title

If I make a secured key with:

var params = {
  filters: 'userId = 1',
  userToken: '1'
};

Won’t both indexes have a userId constraint applied to them? And won’t this cause issues since movies doesn’t have that attribute?

1 Like

Hi @robert.reinhard,

When you generate an API key with some specific filters, they will always be apply on the query.

In your given example the search on the first index orders will contain all the hits where the userId is equal to 1. On the second one, the search on movies will not return any results since no records match the given filters (userId = 1).

You will need to perform the second request with an other API key that not contains these filters.

Hope that helps, let me know if you have questions :wink:.

Is there a way with a multiple index query to specify a different key for each query?

Or, is there a way to specify the index in the filter? Like filters: 'orders.userId = 1',?

Hi @robert.reinhard,

You can’t specify the key at query time, so you can’t pass different one for each query. The key is specified at the instantiation of the client, it can’t be changed afterwards.

You can’t specify on which index the filter will be applied. But instead you can add a type on your records in order to be able to correctly filter the results. According to your example you can add a type property to your records. The orders records will have the value 0 and the movies records will have the value 1. Then you can set the filters with userId = 1 OR type = 1. It means that the query will return all the results with the userId = 1 for your orders records but it will also return all the movies since all the movies records have type = 1.

Note that I intentionally use a numeric filter for the type, because we can’t mix different type of filters with the OR operator.

Hope that helps :slightly_smiling_face:

1 Like