Arangodb groupby query multiple fields

岁酱吖の 提交于 2020-02-25 04:06:14

问题


I have a database of products in an arangodb collection in which a product has multiple sizes. The issue is that for each size, the same product is repeated. But each product has a common group number. Like this:

{"name": "product1", "description": "someDescription", size: 5,price: 12 groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 15, price: 26, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 25, price: 84, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 35, price: 106, groupNumber: 12}

{"name": "product2", "description": "someDescription", size: 5, price: 12, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 15, price: 22, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 25, price: 32, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 35, price: 43, groupNumber: 11}

I have to now display the list of products(in a web page) but each product should appear only once with sizes and prices in an array for each product like this:

product1 someDescription sizes: 5,15,25,35, prices: 12,26,84,106
product2 someDescription sizes: 5,15,25,35, prices: 12,22,32,43
...

How do I do it?


回答1:


Ignoring the groupNumber and grouping by name, the query looks like this:

FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN { 
    "name" : name, 
    "description": description,
    "prices" : groups[*].p.price,
    "sizes" : groups[*].p.size
  }

Given your (corrected) example data, the query returns:

[
  {
    "name": "product1",
    "description": "someDescription",
    "prices": [
      12,
      84,
      106,
      26
    ],
    "sizes": [
      5,
      25,
      35,
      15
    ]
  },
  {
    "name": "product2",
    "description": "someDescription",
    "prices": [
      43,
      32,
      22,
      12
    ],
    "sizes": [
      35,
      25,
      15,
      5
    ]
  }
]

The grouped values aren't sorted, but the positions of sizes and prices correspond, you can alleviate this fact to zip the values into a size-price map:

FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN { 
    "name" : name, 
    "description": description,
    "size_price_map" : ZIP(groups[*].p.size, groups[*].p.price)
  }

yielding:

[
  {
    "name": "product1",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 26,
      "25": 84,
      "35": 106
    }
  },
  {
    "name": "product2",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 22,
      "25": 32,
      "35": 43
    }
  }
]


来源:https://stackoverflow.com/questions/60240849/arangodb-groupby-query-multiple-fields

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