Extract json key/value pairs with postgresql/snowflake, where value is not null/blank - postgresql

I have a field called "filter" with json array like:
[
{
"after":"2021-10-14T00:00:00",
"column":"createddate",
"from":null,
"gt":null,
"gte":null,
"id":"928d57b0",
"lt":null,
"lte":null,
"not":null,
"prior":null,
"to":null,
"value":null
},
{
"after":null,
"column":"last_coach_date",
"from":"",
"gt":null,
"gte":null,
"id":"01704cdd",
"lt":null,
"lte":null,
"not":null,
"prior":null,
"to":"",
"value":null
}
]
I'm trying to extract key/value pairs where value is not null/blank and create another field for it.
Maybe to something like this or one long string:
{ "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0"}, {"column": "last_coach_date","id": "01704cdd"} AS filter_value

Using FLATTEN and OBJECT_AGG:
CREATE OR REPLACE TABLE t(col VARIANT)
AS
SELECT PARSE_JSON('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null }]'
);
Query:
SELECT s.index, OBJECT_AGG(s2.key, s2.value) AS output
FROM t
,LATERAL FLATTEN(input => col) s
,LATERAL FLATTEN(input => s.value) s2
WHERE NOT IS_NULL_VALUE(s2.value) AND s2.value::TEXT != ''
GROUP BY s.INDEX;
Output:

For Postgres:
select (select jsonb_object_agg(key, value)
from jsonb_array_elements(t.filter) as x(item)
cross join jsonb_each_text(x.item) as e(key,value)
where e.value <> '')
from the_table t;

So very similar to Lukasz solution, but OBJECT_AGG will filter out any NULL values, so if you cast to ::text the nulls become real nulls, and are filtered out, so the WHERE clause is not required:
WITH data_table AS(
SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT f.index as batch_id,
OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
FROM data_table t,
TABLE(FLATTEN(input=>t.json)) as f,
TABLE(FLATTEN(input=>f.value)) as p
GROUP BY 1
ORDER BY 1
;
gives:
BATCH_ID
OBJ
0
{ "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0" }
1
{ "column": "last_coach_date", "id": "01704cdd" }
It's not clear from the question if you want 2 rows, or a single value, the latter can be had by adding another layer of aggregation via ARRAY_AGG:
WITH data_table AS(
SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT array_agg(obj) as single_answer
FROM (
SELECT f.index as batch_id,
OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
FROM data_table t,
TABLE(FLATTEN(input=>t.json)) as f,
TABLE(FLATTEN(input=>f.value)) as p
GROUP BY 1
)
;
gives:
SINGLE_ANSWER
[ { "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0" }, { "column": "last_coach_date", "id": "01704cdd" } ]

Related

MondoDB $locate

I have two collections, a policy collection, and a person collection
The Policy looks something like this:
[{
"_id": {
"$oid": "61169375e2145bbfd73dedbe"
},
"PolicyNumber": {
"Identifier": "A56B096A",
"Sequence": 1
},
"Persons": {
"61169362982ac4e8ae2ad768": null,
"60de07a8dc031e91ac5f35c0": null
},
}]
The Person:
[{
"_id": {
"$oid": "5f0c6d087937e0000145e5c3"
},
"UniqueCode": "PER0004",
"PassportExpiryDate": null,
"Age": 35,
"Gender": "M",
"Nationality": null,
"LanguageCode": null,
"Name": "NAME",
"Surname": "SURNAME",
"Initials": null,
"ContactDetails": {
"Addresses": {
"physicalAddress": {
"AddressType": null,
"UnitNumber": null,
"UnitName": null,
"PoBox": null,
"StreetNumber": null,
"StreetName": null,
"Suburb": null,
"Town": null,
"PostalCode": "7100",
"Country": null,
"Coordinates": null,
"InitialCenter": null
}
},
"EmailAddresses": {
"emailAddress": "EMAIL#EMAIL.COM"
},
"TelephoneNumbers": {
"cellphone": "0000000000"
},
"PreferredCommunicationMethod": "SMS"
},
"BankingDetails": [],
"Statistics": null,
"Imported": false,
"ImportReference": null
}]
I have tried various options with $locate, $let, $convert, etc to enable me to join the two collections on 'Persons' using the Policy collections as the entry point.
I know this is probably fundamentals, but I'm n SQL guy who got dumped with a MongoDB conversion.
Any assistance will be appreciated

Query complex JSON in Postgres

I have a json column named "Payload" with a complex json structure as below-
{
"Number": "",
"Status": "",
"Parties": [
{
"BeCode": "SHANGMAG",
"PartyCode": "CNSHANGMAGVDR",
},
{
"BeCode": "FREEMAN",
"PartyCode": "CNFREEMANVDR",
}
],
"ContactName": "test",
"Type": "",
"Legs": [
{
"Name": "",
"ELocation": {
"City": "Enns",
"State": null,
"Country": "Austria",
},
"Socation": {
"City": "Buenos Aires",
"State": null,
"Country": "Argentina",
},
"Transport": 1
},
{
"Name": "84nbt",
"ELocation": {
"City": "Linz",
"State": null,
"Country": "Austria",
},
"SLocation": {
"City": "Enns",
"State": null,
"Country": "Austria",
},
"Transport": 2
}
]
"Bookings": [
{
"BookingNo": "",
"Status": "",
"Id": ""
}
]
}
Now I need to query all the rows where SLocation is equal to ELocation.
I was able to get the "Legs" part row vise using following query -
select payload->'Legs'
from public.shipping_instruction
However, If I dig deep into the json to get the SLocation and ELocation, the query doesnt exceute.
I am looking for something like the one below-
select payload->'Legs'
from public.shipping_instruction where
payload->'Legs'->'ELocation'->'City' =
payload->'Legs'->'SLocation'->'City'
But then here the Legs have multiple SLocation and ELocation how do I handle it?
select "Number",
x."Status" as Status,
"BeCode",
"PartyCode",
"ContactName",
"Type",
"Name",
"Transport",
e_city,
e_state,
e_country,
s_city,
s_state,
s_country,
"BookingNo",
b."Status" as BookingStatus,
"Id"
from jsonb_to_record('{
"Number": "",
"Status": "",
"Parties": [
{
"BeCode": "SHANGMAG",
"PartyCode": "CNSHANGMAGVDR"
},
{
"BeCode": "FREEMAN",
"PartyCode": "CNFREEMANVDR"
}
],
"ContactName": "test",
"Type": "",
"Legs": [
{
"Name": "",
"ELocation": {
"City": "Enns",
"State": null,
"Country": "Austria"
},
"SLocation": {
"City": "Buenos Aires",
"State": null,
"Country": "Argentina"
},
"Transport": 1
},
{
"Name": "84nbtMatch",
"ELocation": {
"City": "Linz",
"State": null,
"Country": "Austria"
},
"SLocation": {
"City": "Linz",
"State": null,
"Country": "Austria"
},
"Transport": 2
},
{
"Name": "84nbt",
"ELocation": {
"City": "Linz",
"State": null,
"Country": "Austria"
},
"SLocation": {
"City": "Enns",
"State": null,
"Country": "Austria"
},
"Transport": 3
}
],
"Bookings": [
{
"BookingNo": "bn",
"Status": "bs",
"Id": "bid"
}
]
}'::jsonb) as x("Number" text,
"Status" text,
"Parties" jsonb,
"ContactName" text,
"Type" text,
"Legs" jsonb,
"Bookings" jsonb),
lateral jsonb_to_recordset(x."Parties") as p("BeCode" text, "PartyCode" text),
lateral jsonb_to_recordset(x."Legs") as l("Name" text, "Transport" int, "ELocation" jsonb, "SLocation" jsonb),
lateral (select l."ELocation" ->> 'City' as e_city,
l."ELocation" ->> 'State' as e_state,
l."ELocation" ->> 'Country' as e_country,
l."SLocation" ->> 'City' as s_city,
l."SLocation" ->> 'State' as s_state,
l."SLocation" ->> 'Country' as s_country
) loc,
lateral jsonb_to_recordset(x."Bookings") as b("BookingNo" text, "Status" text, "Id" text)
where coalesce(e_city, '') = coalesce(s_city, '')
and coalesce(e_state, '') = coalesce(s_state, '')
and coalesce(e_country, '') = coalesce(s_country, '');

AWS ECS Fargate Logging: Facing issue with Firelens side-car container approach to push log files present inside application container to Cloudwatch

I want to push log files which are present in a specific folder inside a container to Cloudwatch. For this, I tried Firelens logdriver but had no luck.
As mentioned here : https://github.com/aws-samples/amazon-ecs-firelens-examples/tree/mainline/examples/fluent-bit/config-file-type-file
I created a custom docker image for fluentbit and deployed it as a side car container in task definition:
FROM public.ecr.aws/aws-observability/aws-for-fluent-bit:stable
COPY fluentbit.conf /extra.conf
fluentbit.conf (I tried exec for debugging purpose, aim is to use tail):
[INPUT]
Name exec
Tag exec_ls
Command ls /opt/apache-tomcat-8.5.72/my-app/logs
Interval_Sec 3
Interval_NSec 0
Buf_Size 8mb
[OUTPUT]
Name cloudwatch
Match *
region ap-south-1
log_group_name fluent-bit-adapter-logs
log_stream_prefix from-fluent-bit-
auto_create_group true
log_key log
This is my ECS Fargate task definition :
{
"ipcMode": null,
"executionRoleArn": "<role>",
"containerDefinitions": [
{
"dnsSearchDomains": null,
"environmentFiles": null,
"logConfiguration": {
"logDriver": "awsfirelens",
"secretOptions": null,
"options": {
"log_group_name": "/aws/ecs/containerinsights/$(ecs_cluster)/application",
"auto_create_group": "true",
"log_key": "log",
"log_stream_prefix": "log_stream_name",
"region": "ap-south-1",
"Name": "cloudwatch"
}
},
"entryPoint": null,
"portMappings": [
{
"hostPort": 8080,
"protocol": "tcp",
"containerPort": 8080
}
],
"command": null,
"linuxParameters": null,
"cpu": 0,
"environment": [],
"resourceRequirements": null,
"ulimits": null,
"dnsServers": null,
"mountPoints": [],
"workingDirectory": null,
"secrets": null,
"dockerSecurityOptions": null,
"memory": null,
"memoryReservation": null,
"volumesFrom": [],
"stopTimeout": null,
"image": "<image-url>",
"startTimeout": null,
"firelensConfiguration": null,
"dependsOn": null,
"disableNetworking": null,
"interactive": null,
"healthCheck": null,
"essential": true,
"links": null,
"hostname": null,
"extraHosts": null,
"pseudoTerminal": null,
"user": null,
"readonlyRootFilesystem": null,
"dockerLabels": null,
"systemControls": null,
"privileged": null,
"name": "my-app"
},
{
"dnsSearchDomains": null,
"environmentFiles": null,
"logConfiguration": {
"logDriver": "awslogs",
"secretOptions": null,
"options": {
"awslogs-group": "/ecs/log_router",
"awslogs-region": "ap-south-1",
"awslogs-create-group": "true",
"awslogs-stream-prefix": "firelens"
}
},
"entryPoint": null,
"portMappings": [],
"command": null,
"linuxParameters": null,
"cpu": 0,
"environment": [],
"resourceRequirements": null,
"ulimits": null,
"dnsServers": null,
"mountPoints": [],
"workingDirectory": null,
"secrets": null,
"dockerSecurityOptions": null,
"memory": null,
"memoryReservation": 50,
"volumesFrom": [],
"stopTimeout": null,
"image": "<image-url>",
"startTimeout": null,
"firelensConfiguration": {
"type": "fluentbit",
"options": {
"config-file-type": "file",
"config-file-value": "/extra.conf"
}
},
"dependsOn": null,
"disableNetworking": null,
"interactive": null,
"healthCheck": null,
"essential": true,
"links": null,
"hostname": null,
"extraHosts": null,
"pseudoTerminal": null,
"user": "0",
"readonlyRootFilesystem": null,
"dockerLabels": null,
"systemControls": null,
"privileged": null,
"name": "log_router"
}
],
"placementConstraints": [],
"memory": "8192",
"taskRoleArn": "<role>",
"compatibilities": [
"EC2",
"FARGATE"
],
"taskDefinitionArn": "<my-app arn>",
"family": "equbemi",
"requiresAttributes": [
{
"targetId": null,
"targetType": null,
"value": null,
"name": "ecs.capability.execution-role-awslogs"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.ecr-auth"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "ecs.capability.firelens.options.config.file"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.21"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.logging-driver.awsfirelens"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.task-iam-role"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "ecs.capability.execution-role-ecr-pull"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "ecs.capability.task-eni"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
},
{
"targetId": null,
"targetType": null,
"value": null,
"name": "ecs.capability.firelens.fluentbit"
}
],
"pidMode": null,
"requiresCompatibilities": [
"FARGATE"
],
"networkMode": "awsvpc",
"cpu": "4096",
"revision": 19,
"status": "ACTIVE",
"inferenceAccelerators": null,
"proxyConfiguration": null,
"volumes": []
}
For my application container, I've given logconfiguration as firelens and deployed a side-car container as mentioned in documentation. I tried the tail command in firelens config but didn't work. So just to troubleshoot, I tried exec and found out in firelens container logs that it is giving "File not found" exception. I assume it is trying to find the path in its own container(the side-car one) and not in the application container. I'm not sure how to make the firelens container access the application container. Am I missing anything here?
*
Here, the problem is that the fluent-bit container does not have access to the application container file system. You need to configure a volume so that the log path will be shared between both of these containers.
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html
Add a volume at the parent level and add this volume as a mount point in both of the container definitions:
{
...
"volumes": [
{
"fsxWindowsFileServerVolumeConfiguration": null,
"efsVolumeConfiguration": null,
"name": "log_path",
"host": {
"sourcePath": null
},
"dockerVolumeConfiguration": null
}
],
...
"containerDefinitions": [
{
...
"mountPoints": [
{
"readOnly": null,
"containerPath": "/var/log",
"sourceVolume": "log_path"
}
],
...
},
{
...
"mountPoints": [
{
"readOnly": null,
"containerPath": "/var/log",
"sourceVolume": "log_path"
}
],
...
}
]
...
}

how to return just one object from an array that is inside a collection with the mongo_dart

I currently have this collection below, and I need a way to return only one item from an internal array (an item from the "pontosGastronomicos" array), only the object, I don't have much experience with mongodb. I'm developing an application and AngularDart and the backend in Angel, application is already working, I just need an optimized way to do this.
// 1
{
"_id": ObjectId("6025b13eab1951094272d007"),
"id": "03a091e2-fa67-4132-9237-f5b9ed3dbb39",
"dataCadastro": "2021-02-11 19:35:41.998",
"link": null,
"icon": "icon-pizza-1",
"ativo": true,
"order": NumberInt("0"),
...
"pontosGastronomicos": [
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
]
}
I need to make a request that brings me just a "pontosGastronomicos" by id, i currently do this via terminal:
db.pontosGastronomicos.find(
{"pontosGastronomicos.id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31"},
{_id: 0, pontosGastronomicos: {$elemMatch: {id: "208a3f93-9fcb-4db7-ac44-bb11b86a2d31"}}});
the result is this:
{
"pontosGastronomicos": [
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
]
}
how to return just one object from an array that is inside a collection with the mongo_dart
I would like the result to be like this
{
"id": "208a3f93-9fcb-4db7-ac44-bb11b86a2d31",
"infos": [
{
"id": "925ed160-9276-4046-87a2-d1f37547f7cb",
"title": "BAR DA BOCA",
"lang": "pt",
"content": "Ótima experiência com o melhor chope de Rio das Ostras"
},
{
"id": "abc2ef60-4807-4b16-8d3e-95223abe0524",
"title": "BAR DA BOCA",
"lang": "en",
"content": "Great experience with the best draft beer in Rio das Ostras"
}
],
"midias": [
{
"id": "d54435d2-2fe3-4ea1-aa04-0ccdfade4c9f",
"title": "experimente-praias-1",
"description": "experimente-praias-1.jpg",
"dataCadastro": "2021-02-10 14:23:23.224",
"fisicalFilename": "acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"originalFilename": "experimente-praias-1.jpg",
"link": "http://localhost:4002/storage/turismo/midias/acd13d50-15af-45fd-98f9-0903d1bb3ea5.jpg",
"mimeType": "image/jpeg",
"tipo": null
}
],
"ativo": true,
"dataCadastro": "2021-02-11 19:51:26.702",
"order": NumberInt("0"),
"link": null,
"email": "bardaboca#yahoo.com.br",
"logradouro": "Rua Teresópolis",
"bairro": "Boca da Barra",
"numero": "69",
"telefone1": "2227641671 ",
"telefone2": "22998578550",
"horarioFuncionamento": "10h as 20h",
"latitude": null,
"longitude": null,
"categoria": null,
"logo": null,
"whatsapp": null,
"tipoDeCozinha": null,
"capacidade": null,
"site": null,
"facebook": null,
"youtube": null,
"instagram": null,
"observacao": null,
}
I get the answer on github, for others who have this difficulty follow the answer:
final cursor = db.collection(collection).modernAggregateCursor([
{
r'$replaceRoot': {
'newRoot': {
r'$arrayElemAt': [
{
r'$filter': {
'input': r'$pontosGastronomicos',
'as': 'pontosGastronomicos',
'cond': {
/* resolve to a boolean value and determine if an element should be included in the output array. */
r'$eq': [r'$$pontosGastronomicos.id', '208a3f93-9fcb-4db7-ac44-bb11b86a2d31']
}
}
},
0 /* the element at the specified array index */
]
}
}
}
]);
result = await cursor.nextObject();
await cursor.close();
/*result = await db.collection(collection).modernFindOne(filter: {
'pontosGastronomicos': {
r'$elemMatch': {'id': '208a3f93-9fcb-4db7-ac44-bb11b86a2d31'}
}
}, projection: {
'_id': 0,
'pontosGastronomicos': {
r'$elemMatch': {'id': '208a3f93-9fcb-4db7-ac44-bb11b86a2d31'}
}
});*/
print(result);

How to use SoftLayer REST API to create an Auto Scale Group

I'm using this URL to get an existing Auto Scale Group that I want to clone with modifications. It seems to have all the informmation about Service Port, Policies, Resource Triggers, Watches, Actions that I need to have.
https://api.softlayer.com/rest/v3/SoftLayer_Scale_Group/1120061/getObject.json?objectMask=mask[policies[resourceUseTriggers[watches],actions],loadBalancers]
The resulting response is contained in "RESPONSE 1" below.
I then modify the response to "remove the IDs" and then modify it to use as a template to create a new Auto Scale Group and the new request JSON is shown in "REQUEST 1" below.
When I submit "REQUEST 1" to SoftLayer using a POST to
https://api.softlayer.com/rest/v3/SoftLayer_Scale_Group/createObject.json
I get the standard error - "The remote server returned an error: (500) Internal Server Error."
So what am I doing incorrectly here?
== REQUEST 1 ==
{ "parameters": [
{
"virtualGuestMemberTemplate": {
"accountId": 940999,
"domain": "partpic.com",
"hostname": "CaffeServer-test-001",
"maxMemory": 1024,
"postInstallScriptUri": "https://webdev.partpic.com/ppsvc/CaffeStartup.aspx?model=Sample.tar.gz",
"startCpus": 1,
"blockDeviceTemplateGroup": {
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"name": "dal06"
},
"hourlyBillingFlag": true
},
"loadBalancers": [{
"healthCheckId": 609283,
"id": 101503,
"port": 32400,
"virtualServerId": 275643
}],
"policies": [{
"name": "ScaleDown",
"resourceUseTriggers": [{
"typeId": 3,
"watches": [{
"algorithm": "EWMA",
"metric": "host.cpu.percent",
"operator": "<",
"period": 1500,
"value": "20"
}]
}],
"actions": [{
"typeId": 1,
"amount": 80,
"scaleType": "PERCENT"
}]
},
{
"name": "ScaleUp",
"resourceUseTriggers": [{
"typeId": 3,
"watches": [{
"algorithm": "EWMA",
"metric": "host.cpu.percent",
"operator": ">",
"period": 600,
"value": "80"
}]
}],
"actions": [{
"typeId": 1,
"amount": 150,
"scaleType": "PERCENT"
}]
}],
"status": {
"id": 1,
"keyName": "ACTIVE",
"name": "Active"
},
"virtualGuestAssets": [],
"virtualGuestMembers": [],
"accountId": 940999,
"cooldown": 60,
"name": "scale_test-001",
"regionalGroupId": 22,
"terminationPolicyId": 1
}
]}
== RESPONSE 1 ==
{
"accountId": 940999,
"balancedTerminationFlag": false,
"cooldown": 60,
"createDate": "2016-08-08T13:19:51-05:00",
"desiredMemberCount": null,
"id": 1120061,
"lastActionDate": "2016-08-12T14:22:51-05:00",
"maximumMemberCount": 0,
"minimumMemberCount": 0,
"modifyDate": "2016-08-12T14:22:57-05:00",
"name": "scale_CaffeServerSample",
"regionalGroupId": 22,
"suspendedFlag": false,
"terminationPolicyId": 1,
"virtualGuestMemberTemplate": {
"accountId": 940999,
"createDate": null,
"dedicatedAccountHostOnlyFlag": null,
"domain": "partpic.com",
"hostname": "CaffeServerSample",
"id": null,
"lastPowerStateId": null,
"lastVerifiedDate": null,
"maxCpu": null,
"maxMemory": 1024,
"metricPollDate": null,
"modifyDate": null,
"postInstallScriptUri": "https:\/\/webdev.partpic.com\/ppsvc\/CaffeStartup.aspx?model=Sample.tar.gz",
"provisionDate": null,
"startCpus": 1,
"statusId": null,
"blockDeviceTemplateGroup": {
"accountId": null,
"createDate": null,
"id": null,
"parentId": null,
"publicFlag": null,
"statusId": null,
"transactionId": null,
"userRecordId": null,
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"id": null,
"name": "dal06",
"statusId": null
},
"hourlyBillingFlag": true,
"localDiskFlag": false,
"privateNetworkOnlyFlag": false
},
"loadBalancers": [{
"createDate": "2016-08-12T14:06:07-05:00",
"deleteFlag": null,
"healthCheckId": 609283,
"id": 101503,
"modifyDate": "2016-08-12T14:19:33-05:00",
"port": 32400,
"scaleGroupId": 1120061,
"virtualServerId": 274353,
"scaleGroup": {
"accountId": 940999,
"balancedTerminationFlag": false,
"cooldown": 60,
"createDate": "2016-08-08T13:19:51-05:00",
"desiredMemberCount": null,
"id": 1120061,
"lastActionDate": "2016-08-12T14:22:51-05:00",
"maximumMemberCount": 0,
"minimumMemberCount": 0,
"modifyDate": "2016-08-12T14:22:57-05:00",
"name": "scale_CaffeServerSample",
"regionalGroupId": 22,
"suspendedFlag": false,
"terminationPolicyId": 1,
"virtualGuestMemberTemplate": {
"accountId": 940999,
"createDate": null,
"dedicatedAccountHostOnlyFlag": null,
"domain": "partpic.com",
"hostname": "CaffeServerSample",
"id": null,
"lastPowerStateId": null,
"lastVerifiedDate": null,
"maxCpu": null,
"maxMemory": 1024,
"metricPollDate": null,
"modifyDate": null,
"postInstallScriptUri": "https:\/\/webdev.partpic.com\/ppsvc\/CaffeStartup.aspx?model=Sample.tar.gz",
"provisionDate": null,
"startCpus": 1,
"statusId": null,
"blockDeviceTemplateGroup": {
"accountId": null,
"createDate": null,
"id": null,
"parentId": null,
"publicFlag": null,
"statusId": null,
"transactionId": null,
"userRecordId": null,
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"id": null,
"name": "dal06",
"statusId": null
},
"hourlyBillingFlag": true,
"localDiskFlag": false,
"privateNetworkOnlyFlag": false
},
"loadBalancers": null,
"policies": [{
"cooldown": null,
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 174557,
"modifyDate": null,
"name": "ScaleDown",
"scaleGroupId": 1120061,
"actions": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 166457,
"modifyDate": null,
"scalePolicyId": 174557,
"typeId": 1,
"scalePolicy": null,
"amount": 80,
"scaleType": "PERCENT"
}],
"resourceUseTriggers": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 173005,
"modifyDate": null,
"scalePolicyId": 174557,
"typeId": 3,
"scalePolicy": null,
"watches": [{
"algorithm": "EWMA",
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 143505,
"metric": "host.cpu.percent",
"modifyDate": null,
"operator": "<",
"period": 1500,
"scalePolicyTriggerId": 173005,
"value": "20",
"scalePolicyTrigger": null
}]
}],
"scaleGroup": null
},
{
"cooldown": null,
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 174555,
"modifyDate": null,
"name": "ScaleUp",
"scaleGroupId": 1120061,
"actions": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 166455,
"modifyDate": null,
"scalePolicyId": 174555,
"typeId": 1,
"scalePolicy": null,
"amount": 150,
"scaleType": "PERCENT"
}],
"resourceUseTriggers": [{
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 173003,
"modifyDate": null,
"scalePolicyId": 174555,
"typeId": 3,
"scalePolicy": null,
"watches": [{
"algorithm": "EWMA",
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 143503,
"metric": "host.cpu.percent",
"modifyDate": null,
"operator": ">",
"period": 600,
"scalePolicyTriggerId": 173003,
"value": "80",
"scalePolicyTrigger": null
}]
}],
"scaleGroup": null
}],
"status": {
"id": 1,
"keyName": "ACTIVE",
"name": "Active"
},
"virtualGuestAssets": [],
"virtualGuestMembers": []
}
}],
"policies": [{
"cooldown": null,
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 174557,
"modifyDate": null,
"name": "ScaleDown",
"scaleGroupId": 1120061,
"actions": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 166457,
"modifyDate": null,
"scalePolicyId": 174557,
"typeId": 1,
"scalePolicy": null,
"amount": 80,
"scaleType": "PERCENT"
}],
"resourceUseTriggers": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 173005,
"modifyDate": null,
"scalePolicyId": 174557,
"typeId": 3,
"scalePolicy": null,
"watches": [{
"algorithm": "EWMA",
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 143505,
"metric": "host.cpu.percent",
"modifyDate": null,
"operator": "<",
"period": 1500,
"scalePolicyTriggerId": 173005,
"value": "20",
"scalePolicyTrigger": null
}]
}],
"scaleGroup": {
"accountId": 940999,
"balancedTerminationFlag": false,
"cooldown": 60,
"createDate": "2016-08-08T13:19:51-05:00",
"desiredMemberCount": null,
"id": 1120061,
"lastActionDate": "2016-08-12T14:22:51-05:00",
"maximumMemberCount": 0,
"minimumMemberCount": 0,
"modifyDate": "2016-08-12T14:22:57-05:00",
"name": "scale_CaffeServerSample",
"regionalGroupId": 22,
"suspendedFlag": false,
"terminationPolicyId": 1,
"virtualGuestMemberTemplate": {
"accountId": 940999,
"createDate": null,
"dedicatedAccountHostOnlyFlag": null,
"domain": "partpic.com",
"hostname": "CaffeServerSample",
"id": null,
"lastPowerStateId": null,
"lastVerifiedDate": null,
"maxCpu": null,
"maxMemory": 1024,
"metricPollDate": null,
"modifyDate": null,
"postInstallScriptUri": "https:\/\/webdev.partpic.com\/ppsvc\/CaffeStartup.aspx?model=Sample.tar.gz",
"provisionDate": null,
"startCpus": 1,
"statusId": null,
"blockDeviceTemplateGroup": {
"accountId": null,
"createDate": null,
"id": null,
"parentId": null,
"publicFlag": null,
"statusId": null,
"transactionId": null,
"userRecordId": null,
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"id": null,
"name": "dal06",
"statusId": null
},
"hourlyBillingFlag": true,
"localDiskFlag": false,
"privateNetworkOnlyFlag": false
},
"loadBalancers": [{
"createDate": "2016-08-12T14:06:07-05:00",
"deleteFlag": null,
"healthCheckId": 609283,
"id": 101503,
"modifyDate": "2016-08-12T14:19:33-05:00",
"port": 32400,
"scaleGroupId": 1120061,
"virtualServerId": 274353,
"scaleGroup": null
}],
"policies": null,
"status": {
"id": 1,
"keyName": "ACTIVE",
"name": "Active"
},
"virtualGuestAssets": [],
"virtualGuestMembers": []
}
},
{
"cooldown": null,
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 174555,
"modifyDate": null,
"name": "ScaleUp",
"scaleGroupId": 1120061,
"actions": [{
"createDate": "2016-08-12T14:23:01-05:00",
"deleteFlag": null,
"id": 166455,
"modifyDate": null,
"scalePolicyId": 174555,
"typeId": 1,
"scalePolicy": null,
"amount": 150,
"scaleType": "PERCENT"
}],
"resourceUseTriggers": [{
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 173003,
"modifyDate": null,
"scalePolicyId": 174555,
"typeId": 3,
"scalePolicy": null,
"watches": [{
"algorithm": "EWMA",
"createDate": "2016-08-12T14:22:51-05:00",
"deleteFlag": null,
"id": 143503,
"metric": "host.cpu.percent",
"modifyDate": null,
"operator": ">",
"period": 600,
"scalePolicyTriggerId": 173003,
"value": "80",
"scalePolicyTrigger": null
}]
}],
"scaleGroup": {
"accountId": 940999,
"balancedTerminationFlag": false,
"cooldown": 60,
"createDate": "2016-08-08T13:19:51-05:00",
"desiredMemberCount": null,
"id": 1120061,
"lastActionDate": "2016-08-12T14:22:51-05:00",
"maximumMemberCount": 0,
"minimumMemberCount": 0,
"modifyDate": "2016-08-12T14:22:57-05:00",
"name": "scale_CaffeServerSample",
"regionalGroupId": 22,
"suspendedFlag": false,
"terminationPolicyId": 1,
"virtualGuestMemberTemplate": {
"accountId": 940999,
"createDate": null,
"dedicatedAccountHostOnlyFlag": null,
"domain": "partpic.com",
"hostname": "CaffeServerSample",
"id": null,
"lastPowerStateId": null,
"lastVerifiedDate": null,
"maxCpu": null,
"maxMemory": 1024,
"metricPollDate": null,
"modifyDate": null,
"postInstallScriptUri": "https:\/\/webdev.partpic.com\/ppsvc\/CaffeStartup.aspx?model=Sample.tar.gz",
"provisionDate": null,
"startCpus": 1,
"statusId": null,
"blockDeviceTemplateGroup": {
"accountId": null,
"createDate": null,
"id": null,
"parentId": null,
"publicFlag": null,
"statusId": null,
"transactionId": null,
"userRecordId": null,
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"id": null,
"name": "dal06",
"statusId": null
},
"hourlyBillingFlag": true,
"localDiskFlag": false,
"privateNetworkOnlyFlag": false
},
"loadBalancers": [{
"createDate": "2016-08-12T14:06:07-05:00",
"deleteFlag": null,
"healthCheckId": 609283,
"id": 101503,
"modifyDate": "2016-08-12T14:19:33-05:00",
"port": 32400,
"scaleGroupId": 1120061,
"virtualServerId": 274353,
"scaleGroup": null
}],
"policies": null,
"status": {
"id": 1,
"keyName": "ACTIVE",
"name": "Active"
},
"virtualGuestAssets": [],
"virtualGuestMembers": []
}
}],
"status": {
"id": 1,
"keyName": "ACTIVE",
"name": "Active"
},
"virtualGuestAssets": [],
"virtualGuestMembers": []
}
I do not think that create a new autoscale group is so easy like copy paste and delete some ids.
try this request:
{
"parameters": [
{
"balancedTerminationFlag": false,
"maximumMemberCount": 0,
"minimumMemberCount": 0,
"cooldown": 60,
"name": "scale_test-0012a",
"regionalGroupId": 22,
"suspendedFlag": false,
"terminationPolicyId": 1,
"virtualGuestMemberTemplate": {
"domain": "partpic.com",
"hostname": "CaffeServer-test-001",
"maxMemory": 1024,
"postInstallScriptUri": "https://webdev.partpic.com/ppsvc/CaffeStartup.aspx?model=Sample.tar.gz",
"startCpus": 1,
"blockDeviceTemplateGroup": {
"globalIdentifier": "fb2fd46d-713a-4d9b-8de1-d47030adc728"
},
"datacenter": {
"name": "dal06"
},
"hourlyBillingFlag": true,
"localDiskFlag": false,
"privateNetworkOnlyFlag": false
},
"loadBalancers": [{
"deleteFlag" : false,
"port": 32400,
"virtualServerId": 275643,
"healthCheck": {
"type": {
"keyname": "DEFAULT"
}
}
}],
"policies": [{
"name": "ScaleDown",
"resourceUseTriggers": [{
"watches": [{
"algorithm": "EWMA",
"metric": "host.cpu.percent",
"operator": "<",
"period": 1500,
"value": "20"
}]
}],
"scaleActions": [{
"amount": 80,
"scaleType": "PERCENT"
}]
}, {
"name": "ScaleUp",
"resourceUseTriggers": [{
"typeId": 3,
"watches": [{
"algorithm": "EWMA",
"metric": "host.cpu.percent",
"operator": ">",
"period": 600,
"value": "80"
}]
}],
"scaleActions": [{
"amount": 150,
"scaleType": "PERCENT"
}]
}]
}
]
}