Creating indexes with cozyCllient

What did you do?

I’m trying to query a doctype with the cozy client using this =>
.sortBy([{ something: ‘desc’ }, { someOtherThing: ‘desc’ }, { someYetAnOtherThing: ‘desc’ }])

What happened?

I keep getting 400 responses
{“error”:“no_index”,“ok”:false,“reason”:“no matching index found, create an index”,“status”:“400”}
till the index is created ,on the fly, then the query fulfills correctly .


the cozy client calls are made in a react app ( not that I see how relevant that might be to this context)


I’d like if possible to create (or check if it exists then create) and index, before running the client.query(query) queries.


Is there some way of doing this via the cozy client.?


Should my design document be deployed beforehand on the couchdb?


Is there some better and cleaner way of doing this?


When you make a request with a sortBy, you need to create the corresponding index. CozyClient exposes a method to do that : indexFields

.sortBy([{ something: ‘desc’ }, { someOtherThing: ‘desc’ }, { someYetAnOtherThing: ‘desc’ }])
.indexFields(['something', 'someOtherThing', 'someYetAnOtherThing'])

By default all fields in the where() are automatically indexed, but I think this is not the case for the sortBy, you have to do that manually.

When the request (with indexFileds) is done, CozyClient will check automatically if the index exists. If not it will create it, else it will use it. This is the way we use it internally

1 Like

Even though I’m using the .indexFields([‘something’, ‘someOtherThing’, ‘someYetAnOtherThing’]) method of the cozyClient, The 400 status code errors keep creeping up for the first query (when no index is created yet). I keep getting those till the index is created, then I get the 200 status code response with the queried docs.
Is there some way to not get the successive 400 erros ? or shoud I just ignore them?

This is the normal behavior. CozyClient makes a request based on your indexFields, if cozyclient gets a 400 then, it sends the request to create the index. This is done that way to not create the index at every request. So we should just ignore it.

It seems you are talking about several 400, this is because you send several request at the same time ? without waiting for the previous to be done ? If yes, then you should probably send one request first (to ensure the index creation) and wait for its resolution and then send multiple queries

1 Like