2016-11-16 78 views
2

我想按本地雲查詢中的參數desc日期排序我的數據。 我在我的數據庫文檔中有insert_ts。 我簡單的查詢代碼: -如何在雲查詢中對日期進行排序

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) { 

    }} 

請幫我把數據作爲最新明智排序。謝謝

+0

請JSON數據共享 –

+0

@ Ahmd我的數據庫中有「_id」:「0c7c-5d47-ec66」,「_rev」:「2-534bc2bc2bc4014a9884052cd2d0551e」,「device_id」:「BT:DEMO」,「user_id」:「0c7c-5d47」 「insert_ts」:「11-Jul-2014-07-59-41-34」如果我想對insert_ts進行​​排序,那麼我如何從字符串中獲得年份? –

回答

0

試試這個代碼:

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"}] 
} 
+0

我想爲混亂的查詢。 –

+0

thankx查詢我有一個像 「_id」 在我的數據庫中的數據: 「0c7c-5d47-ec66」, 「_rev」: 「2-534bc2bc2bc4014a9884052cd2d0551e」, 「hw_device_id」:「SHS:BT:DEMO:CODE 「, 」user_id「:」0c7c-5d47「, 」insert_ts「:」11-Jul-2014-07-59-41-34「 如果我想對insert_ts進行​​排序,那麼我如何從字符串中獲得年? –

+0

: - \t 我想要幫助http://stackoverflow.com/questions/41313089/issue-in-preparedattachment-in-cloudant –

0

更新:原創答案(底部)向您展示如何按年份排序(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<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); 

原來的答案:

我認爲你將不得不明確地添加一年屬性到你的文檔。如果你有一年,那麼只需將它添加到你的文檔。如果您需要從字符串解析它,你可以使用正則表達式或日期/日曆類分析日期:

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<Map<String, String>> sortDocument = new ArrayList<Map<String, String>>(); 
Map<String, String> sortByYear = new HashMap<String, String>(); 
sortByYear.put("year", "asc"); 
sortDocument.add(sortByYear); 
+0

感謝ans。有一個問題..雲端如何知道「insert_ts_date」是日期?不需要提供任何種類的數據格式? –

+0

好吧。所以當我插入日期然後我想發送insert_ts作爲日期格式(java.util.Date)? –

+0

我需要幫助http://stackoverflow.com/questions/41313089/issue-in-preparedattachment-in-cloudant –