How to create equivalent view in cloudant for distinct and cout query in mysql

两盒软妹~` 提交于 2019-12-11 14:31:47

问题


I have 1000 documents of type below and I want to design a document in cloudant (write a view) equivalent to this Mysql query:

 (SELECT 
      COUNT(DISTINCT(correlationassetid)), PERIOD 
  FROM 
      view_asset 
  WHERE 
      ((PERIOD >= '201705') AND (PERIOD <= '201705')) 
  GROUP BY 
      PERIOD 
  ORDER BY 
      PERIOD ASC)

I have tried below view but it does not give proper result. could any one help me?

function (doc) {
  if(doc.type == "asset"){
    emit(doc.period,1);
  }

{
  "_id": "24dee0ec910e22605fe8fc4189000c56",
  "_rev": "1-d667f0b4ce3d984c0d7aafadd223674a",
  "parentName": "",
  "period": "201701",
  "providerGlobalAssetId": "",
  "cost": "5",
  "providerRegionCode": "",
  "owner": "",
  "snapshotId": "659c5f7a-35d62", 
  "correlationAssetId": "aws-6082634880291"
}

回答1:


I'm a bit confused by your example query and your sample document because there are some inconsistencies, but I am going to try to answer your question based on a couple assumptions.

If you are filtering by a single PERIOD value no GROUPBY clause should be required in your SQL statement:

SELECT COUNT(DISTINCT(correlationassetid))
FROM view_asset 
WHERE PERIOD = '201705' 

Defining the following design document

{
  "_id": "_design/howdoi",
  "views": {
    "filter-by": {
      "map": "function (doc) {\n  if(doc.type === \"asset\") {\n   emit([doc.period, doc.correlationAssetId], 1);\n  }\n}",
      "reduce": "_count"
    }
  },
 "language": "javascript"
}

a GET request to query the view

 https://$USER:$PASSWORD@$HOST/$DATABASE/_design/howdoi/_view/filter-by?inclusive_end=true&start_key=[%22201705%22]&end_key=[%22201705%22%2C{}]&reduce=true&group_level=2

should return the desired result if you specify start_key=["201705"] and end_key=["201705",{}].

Example response if there are two documents within that period, both containing the same correlationAssetId:

 {
  "rows": [
   {
    "key": [
      "201705",
      "aws-6082634880291"
    ],
    "value": 2
  }
 ]
}

The number of rows in the result set should identify the distinct number of correlationAssetIds for the specified PERIOD.

Example result for two correlationAssetIds:

{
  "rows": [
    {
      "key": [
        "201701",
        "aws-6082634880291"
      ],
      "value": 1
    },
    {
     "key": [
       "201701",
       "aws-6082634880292"
     ],
     "value": 1
   }
  ]
 }

P.S. Your example document didn't define the asset property and your view definition would therefore not have returned the document. My response above assumes that that property is defined in the documents.



来源:https://stackoverflow.com/questions/44083490/how-to-create-equivalent-view-in-cloudant-for-distinct-and-cout-query-in-mysql

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