user1372829
user1372829

Reputation: 1131

Anyone know how to shrink this query in QueryForTable (using Parse.com)

Anyone know how to shrink this, so that I don't have to run querys in the main thread in the QueryForTable method? I'm using Parse.com

//Find who are the users following (RELATIONSHIP OBJECT)
PFQuery *followeesQuery = [PFQuery queryWithClassName:@"Relationship"];
[followeesQuery whereKey:@"Follower" equalTo:[PFUser currentUser]];
NSArray *followees = [followeesQuery findObjects];
//Filter followees
self.followees = [[NSMutableArray alloc] initWithCapacity:[followees count]];
for (int i = 0; i < [followees count]; i++) {
    PFObject *followee = followees[i];
    PFUser *user = (PFUser *)[followee objectForKey:@"User"]; //USER OBJECT
    [self.followees addObject:user];
}


PFQuery *nearbyPhotosQuery = [PFQuery queryWithClassName:@"Photo"]; //PHOTO OBJECT
[nearbyPhotosQuery whereKey:@"User" notContainedIn:self.followees];
[nearbyPhotosQuery whereKey:@"Location" nearGeoPoint:self.userCurrentLocation withinKilometers:10];

PFQuery *followersPhotoQuery = [PFQuery queryWithClassName:@"Photo"]; //PHOTO OBJECT
[followersPhotoQuery whereKey:@"User" containedIn:self.followees];

NSMutableSet *set = [NSMutableSet setWithArray:[nearbyPhotosQuery findObjects]];
[set addObjectsFromArray:[followersPhotoQuery findObjects]];

NSArray *targetPhotoObjects = [set allObjects];

NSMutableArray *targetIDs = [[NSMutableArray alloc] initWithCapacity:[targetPhotoObjects count]];
for (int i = 0; i < [targetPhotoObjects count] ; i++) {
    PFObject *photoObject = targetPhotoObjects[i];
    [targetIDs addObject:photoObject.objectId];
}


PFQuery *targetPhotoQuery = [PFQuery queryWithClassName:@"Photo"];
[targetPhotoQuery whereKey:@"objectId" containedIn:targetIDs];


return targetPhotoQuery;

Upvotes: 0

Views: 776

Answers (1)

Thomas Bouldin
Thomas Bouldin

Reputation: 3725

If I read this correctly, you want a query for all photos by followers or near you. Why not use:

PFQuery *followeesQuery = [PFQuery queryWithClassName:@"Relationship"];
[followeesQuery whereKey:@"Follower" equalTo:PFUser.currentUser];

PFQuery *followeesPhotosQuery = [PFQuery queryWithClassName:@"Photo"];
[followeesPhotosQuery whereKey:@"User" matchesKey:@"User" inQuery:followeesQuery];

PFQuery *nearbyPhotosQuery = [PFQuery queryWithClassName:@"Photo"];
[nearbyPhotosQuery whereKey:@"Location"
               nearGeoPoint:self.userCurrentLocation
            withinKilometers:10];

return [PFQuery orQueryWithSubqueries:@[followeesPhotosQuery, nearbyPhotosQuery]];

This is a query which matches what you're looking for which doesn't require server-side trips to create. You may need to play with the maximum number of elements returned by inner queries if you expect more than 100 elements to be returned along any step in the process; each query along the way is subject to its own query limit.

Upvotes: 1

Related Questions