cloudant Java客户端getDocsAs()

时间:2016-09-14 20:27:01

标签: java cloudant

我正在尝试使用Java客户端API,特别是getViewRequestBuildergetDocAs()

我的Cloudant数据如下所示:

{
  "_id": "30984feadf2246a68d97cbeff8bf06a0",
  "_rev": "1-8df71f2f874f9228fffb831779063fa9",
  "correlationID": "qweriwern34924df02342jk33",
  "status": "Received",
  "contactType": "EMAIL",
  "ttlHours": 0,
  "requestingId": "123456",
  "requestingApplication": "JUnit",
  "logTimeMs": 1466446389064,
  "logTimeString": "20-06-2016 14:13:09",
  "tsdHitStatus": false,
  "emailContact": {
    "to": "bob@foo,com",
    "bcc": "jane@foo.com"
  },
  "sendSecure": false
}

我创建了一个返回三个字段的视图。

if ( doc. emailContact.to && doc.correlationID) {   
  emit(doc.logTimeMs, 
    {
    correlationID:  doc.correlationID,
    emailAddress: doc.emailContact.to,
    contactType: doc.contactType
    });

我正在尝试根据时间范围获取查询并返回电子邮件对象。 PostMan的视图效果很好。当我从Java尝试这个时,我得到两个字段,但emailAddress字段始终为null。我想知道getDocAs()是否无法理解“doc.emailContact.to”字段。

我认为视图中的“emailAddress:doc.emailContact.to”行允许数据和类之间的映射。

从视图中获取数据的Java代码:

db.getViewRequestBuilder("ch_queries","Email).newRequest(Key.Type.NUMBER, Object.class).startKey(time0).endKey(time1).includeDocs(true).reduce(false).build().getResponse().getDocsAs(Email.class);

电子邮件课程

public class Email  implements Serializable {

    private String correlationID;
    private String emailAddress;
    private String contactType;

    public String getContactType() {
        return contactType;
    }
    public void setContactType(String contactType) {
        this.contactType = contactType;
    }
    public String getCorrelationID() {
        return correlationID;
    }
    public void setCorrelationID(String correlationID) {
        this.correlationID = correlationID;
    }
    public String getEmailAddress() {
        return emailAddress;
    }
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

1 个答案:

答案 0 :(得分:1)

之所以没有按预期工作,是因为您试图将您在视图结果中包含的文档作为Email的实例。因此,首先要做的是从查询中删除includeDocs(true)

接下来你要做的就是输入ViewRequest

ViewResponse<Integer, Email> response;
response =   db.getViewRequestBuilder("ch_queries","Email")
               .newRequest(Key.Type.NUMBER,Email.class)
               .startKey(time0)
               .endKey(time1)
               .reduce(false)
               .build()
               .getResponse()

您可以使用增强型for循环迭代响应,如下所示:

for (ViewResponse.Row<Integer, Email> row : response.getRows()) {
    Email email = row.getValue();
}