聊天应用程序:在Parse查询中获取2个用户之间的消息

时间:2014-04-30 03:26:12

标签: java android parse-platform

我正在使用Parse构建聊天应用。我想检索2个用户之间的聊天记录。在SQL中,它可以表示如下:

SELECT * FROM Message WHERE (sender = user1 AND receiver = user2) OR (sender = user2 AND receiver = user1)

但我不知道如何转换为Parse查询。

这是我的消息模型:

import java.util.Date;

import com.parse.ParseClassName;
import com.parse.ParseObject;
import com.parse.ParseUser;

@ParseClassName("Message")
public class Message extends ParseObject {

    public Message() {

    }

    public String getId() {
        return getObjectId();
    }

    public Date getDate() {
        return getCreatedAt();
    }

    public ParseUser getSender() {
        return getParseUser("sender");
    }

    public void setSender(ParseUser user) {
        put("sender", user);
    }

    public ParseUser getReceiver() {
        return getParseUser("receiver");
    }

    public void setReceiver(ParseUser user) {
        put("receiver", user);
    }

    public String getContent() {
        return getString("content");
    }

    public void setContent(String content) {
        put("content", content);
    }
}

2 个答案:

答案 0 :(得分:1)

你可以使用类似的东西:

String user1;
String user2;

// build first AND condition
ParseQuery<ParseObject> queryPart1 = ParseQuery.getQuery("Message");
queryPart1.whereEqualTo("sender", user1);
queryPart1.whereEqualTo("receiver", user2);

// build second AND condition
ParseQuery<ParseObject> queryPart2 = ParseQuery.getQuery("Message");
queryPart2.whereEqualTo("sender", user2);
queryPart2.whereEqualTo("receiver", user1); 

// list all queries condition for next step
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(queryPart1);
queries.add(queryPart2);

// Compose the OR clause 
ParseQuery<ParseObject> innerQuery = ParseQuery.or(queries);
innerQuery.addAscendingOrder("createdAt"); // apply sorting for creation date ascending (use addDescendingOrder for Desc sorting)

// *** Parse does not allow selection result greater than 1000 elements for query, so you may need to paging your system
//innerQuery.setSkip(10); // skip the first 10 results
//innerQuery.setLimit(200); // limit selection to first 200 elements ( from your skip offset if set, from the first otherwise )

// Run selection asynchronously 
innerQuery.findInBackground(new FindCallback<ParseObject>() {

  public void done(List<ParseObject> results, ParseException e) {
    // Do your stuff with 'results' list, if no error has been occurred
    // ...
    // ..
    // .
  }

});

希望它有所帮助!

答案 1 :(得分:0)

您真的应该关注如何存储聊天消息,而不是如何查询它们。在我看来,你的模型非常SQL,当你以后想要显示历史时,这会导致相当复杂和缓慢的查询和计算。

您应该以更NoSQL的方式设计模型,以从Parse的NoSQL后端(MongoDB)中获益。

在设计模型时,首先要定义要对其执行的查询。您可以通过查询和排序来解决聊天记录,但性能更好的方法是确保您的聊天记录已经存在于服务器上。这将使历史查询超快,并且用户设备上的负载最小。

此处建议采用一种解决方案:Storing send message history on parse.com for a messaging app?