algoliasearch-client-javascript
algoliasearch-client-javascript copied to clipboard
Can't paginate with browseObjects
I'm using browseObjects for multiple situations. Always works well using when using filters, query and attributesToRetrieve parameters. However, I can't make pagination work (tried hitsPerPage, and length/offset pair). For example, this code will give me the right results but not limited to 2 items:
const algoliasearch = require("algoliasearch");
const client = algoliasearch("APP_ID", "KEY");
const index = client.initIndex("INDEX_NAME");
let hits = [];
index
.browseObjects({
batch: (batch) => {
hits = hits.concat(batch);
},
query: "coco",
hitsPerPage: 2,
attributesToRetrieve: ["name"],
})
.then(() => console.log(hits));
browseObjects does a complete browse of the index, not a single "browsed page", for that you can use client.transporter.read
https://github.com/algolia/algoliasearch-client-javascript/blob/master/packages/client-search/src/methods/index/browseObjects.ts#L21-L28
OK I understand and we were able to make it work. However, this is not documented anywhere. The browseObjects documentation even explicitly states the opposite. I quote :
Browse compatible search parameters can contain any of the search parameters. Some useful ones for browse include: (...) for pagination: hitsPerPage, length, offset, page.
You're right, this is indeed confusing, as the pagination is used under the hood, so a different hitsPerPage or length will give a different number of hits per page, but without specifying shouldStop
to something like shouldStop: () => true
, it will start at that page, but it will continue to extract the whole index.
I'll think to how that could be clarified in the documentation
The documentation has been updated to avoid mentioning the problematic page
documentation, although you could in theory get a single "browsed" page like this:
browseObjects({ page: 100, hitsPerPage: 800, shouldStop: () => true, batch })
This is really important and yet it's not available in the documentation.