how to sort date in cloudant query

痞子三分冷 提交于 2019-12-06 09:35:07

问题


i want to sort my data as par desc date in local cloudant query. i have insert_ts in my database document. my code for simple query is:-

  public List<BasicDocumentMAP> allTasksWithAllArg(Map<String, Object> query, int skip, int limit, List<String> fields, List<Map<String, String>> sortDocument) {
    int nDocs = this.sunDatastore.getDocumentCount();
    QueryResult all = this.im.find(query, skip, limit, fields, sortDocument);
    List<BasicDocumentMAP> arrayListBasicDocumentMAP = new ArrayList<>();

    // Filter all documents down to those of type Task.
    for (DocumentRevision rev : all) {

    }}

please help me to sort data as date wise. thank you


回答1:


Try this code:

Sql query :

Select  _id ,  _rev ,  insert_ts ,  title from table
where year=2010 order by insert_ts

Cloudant query :

{
  "selector": {
    "year": {
      "$gt": 2010
    }
  }, 
  "fields": ["_id", "_rev", "insert_ts", "title"], // 
  "sort": [{"insert_ts": "asc"}]
}



回答2:


Update: The original answer (at the bottom) shows you how to sort by year (OP asked how to get the year, so I assumed that was how they wanted to sort). This is how to sort by date:

Either change the insert_ts field to be a date, or add a new field that is a date, for example:

Date insertTsDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
    insertTsDate = dateFormat.parse(insert_ts);
}
catch (Exception e) {
    // handle exception  
}

Then add a new field to your document called insert_ts_date (or whatever you want to call it), set it to the insertTsDate variable above, and sort like so:

List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByInsertTsDate = new HashMap<String, String>();
sortByInsertTsDate.put("insert_ts_date", "asc");
sortDocument.add(sortByInsertTsDate);

Original Answer:

I think you are going to have to explicitly add a year property to your document. If you have the year then just add it to your document. If you need to parse it from the string you can use regex or the Date/Calendar classes to parse the date:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss-SS");
try {
    Date date = dateFormat.parse(insert_ts);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int year = c.get(Calendar.YEAR);
}
catch (Exception e) {
    // handle exception  
}

Then issue your query as follows:

List<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>();
Map<String, String> sortByYear = new HashMap<String, String>();
sortByYear.put("year", "asc");
sortDocument.add(sortByYear);


来源:https://stackoverflow.com/questions/40624834/how-to-sort-date-in-cloudant-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!