如何在cloudant查询中对日期进行排序

我想在本地cloudant查询中将我的数据排序为par desc date。 我在我的数据库文档中有insert_ts。 我的简单查询代码是: –

public List allTasksWithAllArg(Map query, int skip, int limit, List fields, List<Map> sortDocument) { int nDocs = this.sunDatastore.getDocumentCount(); QueryResult all = this.im.find(query, skip, limit, fields, sortDocument); List arrayListBasicDocumentMAP = new ArrayList(); // Filter all documents down to those of type Task. for (DocumentRevision rev : all) { }} 

请帮我按日期排序数据。 谢谢

试试这段代码:

SQL查询:

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

Cloudant查询:

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

更新:原始答案(在底部)显示如何按年排序(OP询问如何获得年份,所以我认为这是他们想要排序的方式)。 这是按日期排序的方法:

insert_ts字段更改为日期,或添加作为日期的新字段,例如:

 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 } 

然后在文档中添加一个名为insert_ts_date的新字段(或者您想要调用它的任何字段),将其设置为上面的insertTsDate变量,并按如此排序:

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

原答案:

我认为您将不得不在文档中明确添加年份属性。 如果您有年份,那么只需将其添加到您的文档中即可。 如果需要从字符串中解析它,可以使用正则表达式或日期/日历类来解析日期:

 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 } 

然后发出您的查询,如下所示:

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