Eight Eight - 10 months ago 42
Android Question

How to get most popular post?

I am creating an app in which users can make posts and other users can like and comment over these posts.To achieve this facility i am using tables likes POSTS, LIKES, COMMENTS.(I am using parse.com database to store these table).

POSTS have fields like postId, content, userWhoMadeThePost, dateOfPosting

LIKES contains filelds as id, postOnWhichLikeWasMade (foreign key to POSTS(postId)), userWhoLiked, dateofLike

COMMENTS have id, content, postOnWhichCommentWasMade(foreign key to POSTS(postId)), userWhoCommented, dateOfComment

I want to retrieve most popular posts (posts with most no of likes and comments).

  1. First way to do this is count no of post and likes for each post each time whenever a request is made for popular posts but this can become very time consuming if
    there are millions of posts.

  2. Other way to do this one way is to include 'noOfLikes' and 'noOfComments' in POSTS table, so in order to get popular posts I will have to access only post table, but the problem with this approach is whenever a user makes a comment over a post then I will have to increment 'noOfComments' in POSTS table as well as make a entry in COMMENTS table, problem starts when the increment is successfully made to POST table and before making change to the COMMENTS table connection is lost. In that case POST and COMMENTS table would be showing wrong data.

How to do this?

Answer Source

This would be simple, if you had control over the database, but doing this with Parse means that you have two main problems (one of which you already mentioned):

  1. As far as I can tell, Parse does not allow grouping in queries. That means that (with your schema) it's actually impossible to get the most liked/commented posts without retrieving all of them. This is because you can't actually dynamically add a new column with the number of likes/comments like you would in a standard SQL query (using JOIN and GROUP BY).
  2. You can't update more than one object within one transaction, so there is the possibility that a user could add a comment but the number of comments in the post object would not change.

That being said I think (at least if you insist on using parse) you must add the 'noOfLikes' and 'noOfComments' columns to the Post object. Not only does it provide the only viable solution for retrieving N top posts (without getting all of them), but the actual risk of inconsistencies is pretty low in my opinion. You can always catch network (or other) exceptions and temporarely store the update requests locally and retry them later.