[英]How to find document by _id in couchdb?
我正在尝试通过其_id获取文档表格ouchdb
如果文档存在于数据库中,则它将返回文档JSON,
否则,如果数据库中没有文档,它将返回异常。
我在我的代码中尝试此:。
String dbname="abc";
String Email_Id="uvw@xyz.com";
Session session = new Session("localhost", 5984);
Database database = session.getDatabase(dbname);
Document doc = database.getDocument(Email_id);
*(这里dbname是数据库的名称, Email_id是文档的._id)*
我必须检查是否存在带有此email_id的文档。 使用getDocument("")
函数,对于数据库中不存在的文档,抛出异常
例外:。 net.sf.json.JSONException: JSONObject["error"] is not a JSONObject.
如果数据库中不存在该文档,则必须创建该文档。
导入为(要使用的jar文件为CouchDb4j.0.1.2.jar)
import com.fourspaces.couchdb.Database;
import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.Session;
import com.fourspaces.couchdb.ViewResults;
创建以下方法来检查电子邮件是否存在
boolean emailexists= checkIfExists(couchdbServer, couchdbserverPort, couchDbName, emailid)
{
if (emailexists)
{
log.debug("email already exists in the database");
}
else
{
CouchDBHandler cdb = new CouchDBHandler(couchDbName,couchdbServer,couchdbserverPort);
String addedid = cdb.addEmail(email);
}
}
public static boolean checkIfExists(String couchdbServer,String couchdbserverPort,String couchDbName,String idtoCheck) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
StringBuffer sbserverURL = new StringBuffer(); sbserverURL.append("http://").append(couchdbServer).append(":").append(couchdbserverPort).append("/").append(couchDbName).append("/").append(idtoCheck);
log.debug("Server URL is:"+sbserverURL.toString());
HttpGet get = new HttpGet(sbserverURL.toString());
HttpResponse response = httpclient.execute(get);
HttpEntity entity=response.getEntity();
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String strdata = null;
StringBuffer sb = new StringBuffer();
while( (strdata =reader.readLine())!=null)
{
sb.append(strdata);
}
if (sb.toString().indexOf("not_found") > -1) {
return false;
}
else
return true;
}
public String addEmail(email)
{
Document doc = new Document();//CouchDb4j jar file has this function
doc.setId(email);
db.saveDocument(doc); //private Database db; //CouchDb4j jar file has this function
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.