How to query Relations with good performance in cloud code?

Hi,

I have a question regarding performance when doing a query on a Parse.Relation in cloud code (I’m using Back4App). Would be super grateful if anyone has some clever input :slight_smile:

In my app I have many-to-many relations between users. It is currently built like this:

I have a class called “UserRelation” that represents the relation between two users. It has columns/properties like this:

user1Id: String // id of one of the users
user2Id: String //id of the other user
+ some other data

Each user class then have a property “userRelations” which is a Parse.Relation containing UserRelations

I don’t expect the average user to have more than 10 UserRelations, however the total number of UserRelations in the database can of course be large.

My issue is that this simple query is very very slow:

userRelations = user.relation("userRelations")
let query = userRelations.query()
let results = await query.find({ useMasterKey: true })

When I test this I have 10 items in “userRelation” and the total number of UserRelations in the db is 100k.

For comparison this query that is performed on the complete set of UserRelations (100k) is at least 20-50 times faster:

let queryPart1 = new Parse.Query("UserRelation").equalTo("user1Id", user.id);
let queryPart2 = new Parse.Query("UserRelation").equalTo("user2Id", user.id)
let completeQuery = Parse.Query.or(queryPart1, queryPart2);
let results = await completeQuery.find({ useMasterKey: true });

I’ve tried different indexes on the UserRelation class but I can’t find anything that speeds it up. The second example uses the indexes for “user1Id” and “user2Id” and is therefore relatively fast, but the first example seem immune to my indexes.

I expected that a Parse.Relation has pointers to the objects in the relation and that a query for the few objects it contains would be faster than doing a query on the complete set of objects, and definitely not a lot slower.

There must be something that I’m missing? I can’t believe that Parse.Relation is built in a way that makes it this slow? Or am I just naive?

//Jens