Creating indexes with cozyCllient

What did you do?

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

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 .

Context

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

Questions

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

1.

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

2.

Should my design document be deployed beforehand on the couchdb?

3.

Is there some better and cleaner way of doing this?

Hi!

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

client.query(client.find(doctype)
.where({})
.sortBy([{ something: ‘desc’ }, { someOtherThing: ‘desc’ }, { someYetAnOtherThing: ‘desc’ }])
.indexFields(['something', 'someOtherThing', 'someYetAnOtherThing'])
.limitBy(1))

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

Hi,
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