Search code examples
couchbasesql++

How to get n1ql query response in a particular format?


when i execute below query

SELECT r.name AS organizationRoleName, r.organizationRoleId, a.city, a.zip,a.address1
FROM `contact` AS c
UNNEST c.organizationRoles AS r
UNNEST r.addressAssociations AS aa
jOIN `optima_contact` AS a
ON aa.addressId = TO_NUMBER(a.addressId) 
WHERE  c.type = "organization" AND a.type = "address" and a.city="Plaridel";

i get the response as below

[
   {
 "address1": "Ground Floor Waltermart Center-Plaridel, Cagayan Valley Road, Barrio Banga 1, Plaridel",
"city": "Plaridel",
"organizationRoleId": 903,
"organizationRoleName": "SUN - WALTERMART PLARIDEL",
"zip": "3004"
},
{
"address1": "Ground Floor Waltermart Center-Plaridel Cagayan Valley Road Barrio Banga 1 Plaridel",
"city": "Plaridel",
"organizationRoleId": 1001,
"organizationRoleName": "FRS1 Store",
"zip": "3004"
  }
]

Is there anyway to get the response in below format instead of above format?

[
{
"organizationRoleId": 903,
"organizationRoleName": "SUN - WALTERMART PLARIDEL",
"storeAddress": {
                "address1": "Ground Floor Waltermart Center-Plaridel, Cagayan Valley Road, Barrio Banga 1, Plaridel",
                "city": "Plaridel",
                "zipCode": "3004"
            }
},
{
"organizationRoleId": 1001,
"organizationRoleName": "FRS1 Store",
"storeAddress": {
                "address1": "Ground Floor Waltermart Center-Plaridel Cagayan Valley Road Barri Banga 
                             1 Plaridel",
                "city": "Plaridel",
                "zipCode": "3004"
            }
  }
  ]

What should be the way to get the above type of response?


Solution

  • You can construct Object using {city, zip, address1} and Alias AS storeAddress

    SELECT r.name AS organizationRoleName, r.organizationRoleId,
           {a.city, a.zip,a.address1} AS storeAddress
    FROM `contact` AS c
    UNNEST c.organizationRoles AS r
    UNNEST r.addressAssociations AS aa
    jOIN `optima_contact` AS a
    ON aa.addressId = TO_NUMBER(a.addressId) 
    WHERE  c.type = "organization" AND a.type = "address" and a.city="Plaridel";