How do I apply conditional formatting in .map() in nodejs? - node.js

I have the below data
[
{
"ID": "1",
"SIZE": 2.21,
"Metal": "Steel",
"Class": "Non magnetic",
"Density":3.9,
},
{
"ID": "2",
"SIZE": 1.25,
"Metal": "Iron",
"Class": "magnetic",
"Density":4.2,
},
{
"ID": "3",
"SIZE": 15.5,
"Metal": "Water",
"Class": "non magnetic",
"Density": 1.3,
},
{
"ID": "4",
"SIZE": 9.5,
"Metal": "Steel",
"Class": "non magnetic",
"Density": 1.2,
}
{
"ID": "5",
"SIZE": 3.2,
"Metal": "Water",
"Class": "non magnetic",
"Density": 1.0,
}
]
Goal is to create a new map and filter the data. If name is steel or iron, we need to get the size from the previous object . Likewise if metal is water, then we need to the skip the currect object and check in the next value in the next object. If the subsequent values are water too, then we need to return "Invalid". I tried the below piece of code but it is not returning the desired output
data.map((temp, i) =>{
if (temp.METAL.toUpperCase() != 'WATER')
{
res.push({
ID: temp.ID,
SIZE: temp.SIZE,
Priortosize: data[i + 1] ? data[i + 1].SIZE: "Invalid",
Metal: temp.METAL
Class: temp.CLASS,
Density: temp.DENSITY
})
}
})
It returns empty value if the last metal is water. Can you please help?

First, Javascript is a case-sensitive language.
data.Metal != data.METAL
Use data.Metal, just as it is in the data object.
I also saw that you forgot some commas in your example, both in the data object and in the push of your code.
data = [
{
"ID": "1",
"SIZE": 2.21,
"Metal": "Steel",
"Class": "Non magnetic",
"Density":3.9,
},
{
"ID": "2",
"SIZE": 1.25,
"Metal": "Iron",
"Class": "magnetic",
"Density":4.2,
},
{
"ID": "3",
"SIZE": 15.5,
"Metal": "Water",
"Class": "non magnetic",
"Density": 1.3,
},
{
"ID": "4",
"SIZE": 9.5,
"Metal": "Steel",
"Class": "non magnetic",
"Density": 1.2,
},
{
"ID": "5",
"SIZE": 3.2,
"Metal": "Water",
"Class": "non magnetic",
"Density": 1.0,
}
]
res = []
data.map((temp, i) =>{
if (temp.Metal.toUpperCase() != 'WATER')
{
res.push({
ID: temp.ID,
SIZE: temp.SIZE,
Priortosize: data[i + 1] ? data[i + 1].SIZE: "Invalid",
Metal: temp.Metal,
Class: temp.Class,
Density: temp.Density
})
}
})
console.log(JSON.stringify(res, null, 0))

Related

many to many relationship in sqlalchemy

need a little help. I have two table with many to many relation between them . Now i am not using any of those sqlalchemy orm relationship because of certain constraints in the project.
class ChargeStation(Base):
__tablename__="charge_station"
__table_args__={'extend_existing': True}
station_id=Column(String(255),primary_key=True,index=True)
station_name=Column(String(255))
address=Column(String(255),nullable=True)
class TariffChart(Base):
__tablename__="tariff_chart"
__table_args__={'extend_existing': True}
tariff_id=Column(String(30),primary_key=True,index=True)
tariff_name=Column(String(30))
rate=Column(Float(25),nullable=True)
class StationTariff(Base):
__tablename__="station_tariff"
__table_args__={'extend_existing': True}
id=Column(UUID(as_uuid=True),primary_key=True,default=uuid4)
station_id=Column(String, ForeignKey("charge_station.charge_station_id",ondelete="CASCADE"),nullable=True)
tariff_id=Column(String, ForeignKey("tariff_chart.tariff_id",ondelete="CASCADE"),nullable=True)
datetime=Column(DateTime(), default=datetime.now())
I want to fetch all rate cards assigned to every stations through a get call . For that i am using the below query.
charge_stations=db.query(station.station_id,
station.station_name,
station.address,tariff).\
join(station_tariff,station.station_id==station_tariff.station_id).\
join(tariff,station_tariff.tariff_id==tariff.tariff_id).all()
Now i am getting the response as this
[
{
"station_id": "1",
"station_name": "s1",
"address": "abc",
"tariff_chart": {
"tariff_id": "t1",
"rate": 30,
"tariff_name": "tar1"
}
},
{
"station_id": "1",
"station_name": "s1",
"address": "abc",
"tariff_chart": {
"tariff_id": "t2",
"rate": 30.6,
"tariff_name": "tar2"
}
},
{
"station_id": "23",
"station_name": "Groot",
"address": "xyz ",
"tariff_chart": {
"tariff_id": "t1",
"rate": 30,
"tariff_name": "tar1"
}
}
]
But i want all the tariff chart related to particular station clubbed together in a list of dictionaries like this
[
{
"station_id": "1",
"station_name": "s1",
"address": "abc",
"tariff_chart":[ {
"tariff_id": "t1",
"rate": 30,
"tariff_name": "tar1"
},
{
"tariff_id": "t2",
"rate": 30.6,
"tariff_name": "tar2"
}]
},
{
"station_id": "23",
"station_name": "Groot",
"address": "xyz ",
"tariff_chart": {
"tariff_id": "t1",
"rate": 30,
"tariff_name": "tar1"
}
}
]
Can you guys please suggest how to achieve that .

Terraform AWS Dashboard - Widgets from nested list

Terraform beginner here. I am trying to create some widgets from a nested list. Group will be a "label" widget indicating the group followed by the metric widgets for the canaries related to the group. So the dashboard should look as follows:
Group 1
widget1, widget2 etc.
Group 2
widget3, widget4 etc.
Variable value:
dashboard = [
{
name = "Group-1",
canaries = ["canary1", "canary2", "canary3"]
},
{
name = "Group-2",
canaries = ["canary4", "canary5"]
}
]
Attempt at building json:
locals {
body = [for group in var.dashboard :
#Create text widget for Group name
{
"height": 1,
"width": 24,
"y": 4,
"x": 0,
"type": "text",
"properties": {
"markdown": "\n# > [${group.name}]\n"
}
}
#Attempt to create underlying widgets for group
[for canary in group.canaries :
{
{
"height": 3,
"width": 6,
"y": 5,
"x": 0,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "${canary}", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
}
}
] #TF Doesn't like the inclusion of nested loop here or my syntax is incorrect.
]
}
Resource creation:
resource "aws_cloudwatch_dashboard" "canary_dashboard" {
dashboard_name = "Canary-Dashboard"
dashboard_body = jsonencode({
"widgets": concat(local.body)
})
}
In my creation of body, Terraform complains about Missing close bracket on index, but I have triple checked that I am not missing a bracket or curly brace. How do I dynamically create the dashboard widgets from nested lists?
Edit
Including desired json output below as suggested by Jordan. In the end, there will be n number of groups, each having n number of canaries belonging to said group.
{
"widgets": [
{
"height": 1,
"width": 24,
"y": 4,
"x": 0,
"type": "text",
"properties": {
"markdown": "\n# Group1\n"
}
},
{
"height": 3,
"width": 6,
"y": 5,
"x": 6,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "Group1-Canary", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
},
{
"height": 1,
"width": 24,
"y": 4,
"x": 0,
"type": "text",
"properties": {
"markdown": "\n# Group2\n"
}
},
{
"height": 3,
"width": 6,
"y": 5,
"x": 6,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "Group2-Canary", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
},
]
}
You're trying to do something with list comprehension that Terraform doesn't allow (see where I've marked "HERE"):
locals {
body = [for group in var.dashboard :
#Create text widget for Group name
{
"height": 1,
"width": 24,
"y": 4,
"x": 0,
"type": "text",
"properties": {
"markdown": "\n# > [${group.name}]\n"
}
} <===== HERE
#Attempt to create underlying widgets for group
[for canary in group.canaries :
{
{
"height": 3,
"width": 6,
"y": 5,
"x": 0,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "${canary}", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
}
}
] #TF Doesn't like the inclusion of nested loop here or my syntax is incorrect.
]
}
If TF allowed you to do what you're trying to do, you'd end up with something like:
body = [
{
"height": 1,
"width": 24,
"y": 4,
"x": 0,
"type": "text",
"properties": {
"markdown": "\n# > [${group.name}]\n"
}
},
[
{
{
"height": 3,
"width": 6,
"y": 5,
"x": 0,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "${canary}", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
}
},
{
{
"height": 3,
"width": 6,
"y": 5,
"x": 0,
"type": "metric",
"properties": {
"metrics": [
[ "CloudWatchSynthetics", "Failed", "CanaryName", "${canary}", { "label": "Canary failures count", "region": "us-west-2" } ]
],
"title": "Failed canary runs",
"period": 60,
"region": "us-west-2",
"stat": "Sum",
"view": "singleValue",
"setPeriodToTimeRange": true
}
}
}
]
]
And I doubt that's what you're trying to do. If you can provide a sample of what you'd like the JSON to look like, we can show you how to achieve it.

Elasticsearch on fashion commerce

I have the following dataset indexed in elasticsearch
[
{
"id": "1",
"name": "Red T-shirt",
"size": "S",
"styleId": "R-1"
},
{
"id": "2",
"name": "Red T-shirt",
"size": "M",
"styleId": "R-1"
},
{
"id": "3",
"name": "Red T-shirt",
"size": "L",
"styleId": "R-1"
},
{
"id": "4",
"name": "White T-shirt",
"size": "S",
"styleId": "W-1"
},
{
"id": "5",
"name": "White T-shirt",
"size": "XL",
"styleId": "W-1"
}
]
In search result I want products grouped by styleId. Is it possible like bellow sample result? In most of the commerce websites like Amazon, Myntra, Flipkart I have seen they are doing the same what I am trying. I have tried many elasticsearch concepts like "collapse" but without success. Using kibana, and elasticsearch version 7.4. Any suggestions will be highly appreciated.
[
{
"id": "1",
"name": "Red T-shirt",
"size": "S",
"styleId": "R-1",
"sizes": [
{
"id": "2",
"name": "Red T-shirt",
"size": "M",
"styleId": "R-1"
},
{
"id": "3",
"name": "Red T-shirt",
"size": "L",
"styleId": "R-1"
}
]
},
{
"id": "4",
"name": "White T-shirt",
"size": "S",
"styleId": "W-1",
"sizes": [
{
"id": "5",
"name": "White T-shirt",
"size": "XL",
"styleId": "W-1"
}
]
},
]
You can use collapse with cardinality aggregation.
Cardinality will give group level count
{
"_source": "false",
"collapse": {
"field": "styleId.keyword",
"inner_hits": {
"name": "group-details",
"size": 5
}
},
"from": 0,
"size": 5,
"aggs": {
"type_count": {
"cardinality": {
"field": "styleId.keyword"
}
}
}
}

MongoDB Aggregate with sum of array object values

I have a collection with the following data:
{ "id": 1,
"name": "abc",
"age" : "12"
"quizzes": [
{
"id": "1",
"time": "10"
},
{
"id": "2",
"time": "20"
}
]
},
{ "id": 2,
"name": "efg",
"age" : "20"
"quizzes": [
{
"id": "3",
"time": "11"
},
{
"id": "4",
"time": "25"
}
]
},
...
I would like to perform the MongoDB Aggregation for a sum of quizzes for each document.and set it to totalTimes field
And this is the result that I would like to get after the querying:
{ "id": 1,
"name": "abc",
"age" : "12",
"totalTimes": "30"
"quizzes": [
{
"id": "1",
"time": "10"
},
{
"id": "2",
"time": "20"
}
]
},
{ "id": 2,
"name": "efg",
"age" : "20",
"totalTimes": "36"
"quizzes": [
{
"id": "3",
"time": "11"
},
{
"id": "4",
"time": "25"
}
]
},
...
How can I query to get the sum of quizzes time?
Quite simple using $reduce
db.collection.aggregate([
{
$addFields: {
totalTimes: {
$reduce: {
input: "$quizzes",
initialValue: 0,
in: {
$sum: [
{
$toInt: "$$this.time"
},
"$$value"
]
}
}
}
}
}
])
Mongo Playground

Modifying elasticsearch score based on nested field value

I want to modify scoring in ElasticSearch (v2+) based on the weight of a field in a nested object within an array.
For instance, using this data:
PUT index/test/0
{
"name": "red bell pepper",
"words": [
{"text": "pepper", "weight": 20},
{"text": "bell","weight": 10},
{"text": "red","weight": 5}
]
}
PUT index/test/1
{
"name": "hot red pepper",
"words": [
{"text": "pepper", "weight": 15},
{"text": "hot","weight": 11},
{"text": "red","weight": 5}
]
}
I want a query like {"words.text": "red pepper"} which would rank "red bell pepper" above "hot red pepper".
The way I am thinking about this problem is "first match the 'text' field, then modify scoring based on the 'weight' field". Unfortunately I don't know how to achieve this, if it's even possible, or if I have the right approach for something like this.
If proposing alternative approach, please try and keep a generalized idea where there are tons of different similar cases (eg: simply modifying the "red bell pepper" document score to be higher isn't really a suitable alternative).
The approach you have in mind is feasible. It can be achieved via function score in a nested query .
An example implementation is shown below :
PUT test
PUT test/test/_mapping
{
"properties": {
"name": {
"type": "string"
},
"words": {
"type": "nested",
"properties": {
"text": {
"type": "string"
},
"weight": {
"type": "long"
}
}
}
}
}
PUT test/test/0
{
"name": "red bell pepper",
"words": [
{"text": "pepper", "weight": 20},
{"text": "bell","weight": 10},
{"text": "red","weight": 5}
]
}
PUT test/test/1
{
"name": "hot red pepper",
"words": [
{"text": "pepper", "weight": 15},
{"text": "hot","weight": 11},
{"text": "red","weight": 5}
]
}
post test/_search
{
"query": {
"bool": {
"disable_coord": true,
"must": [
{
"match": {
"name": "red pepper"
}
}
],
"should": [
{
"nested": {
"path": "words",
"query": {
"function_score": {
"functions": [
{
"field_value_factor": {
"field" : "words.weight",
"missing": 0
}
}
],
"query": {
"match": {
"words.text": "red pepper"
}
},
"score_mode": "sum",
"boost_mode": "replace"
}
},
"score_mode": "total"
}
}
]
}
}
}
Result :
"hits": [
{
"_index": "test",
"_type": "test",
"_id": "0",
"_score": 26.030865,
"_source": {
"name": "red bell pepper",
"words": [
{
"text": "pepper",
"weight": 20
},
{
"text": "bell",
"weight": 10
},
{
"text": "red",
"weight": 5
}
]
}
},
{
"_index": "test",
"_type": "test",
"_id": "1",
"_score": 21.030865,
"_source": {
"name": "hot red pepper",
"words": [
{
"text": "pepper",
"weight": 15
},
{
"text": "hot",
"weight": 11
},
{
"text": "red",
"weight": 5
}
]
}
}
]
}
The query in a nutshell would score a document that satisfies the must clause as follows : sum up the weights of the matched nested documents with the score of the must clause.

Resources