many to many relationship in sqlalchemy - python-3.x

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 .

Related

How to findOneAndUpdate MongoDB object inside array from multiple arrays inside object

I am new to mongodD. Although i have wrote correct logic to push object inside cardsData bankCardsArray, but i am not able to make logic to edit a card.
**I have following Data in MongoDB, **
UserData = {
"_id": "63b43ab32fc8d3c100cafecc",
"name": "Praveen Lohar",
"email": "pr********#gmail.com",
"password": "$2b$12$3nwifHakrBu94BwLXAC4Nu16Kw0.xyW8vAIPTMSgY7cYttVklDIZq",
"loginIdsArray": [
{
"title": "Airtel App",
"logoIndex": 3,
"category": "Finance",
"app": "Airtel Thanks",
"username": "p******#gmail.com ",
"password": "xxxxxxx",
"isFavourite": false,
"_id":"63b440ee738a50fc333df3ca"
}
],
"cardsData": {
"bankCardsArray": [
{
"title": "SBI CC",
"logoIndex": 72,
"category": "Bank",
"cardHolder": "Prsscscs",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebec8b"
},
{
"title": "AXIS CC",
"logoIndex": 85,
"category": "Bank",
"cardHolder": "blsllslss",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebe5f"
}
],
"identityCardsArray": [
{
"title": "Aadhar Card",
"logoIndex": 98,
"category": "Identity",
"cardHolder": "Name_1",
"cardNumber": "54*******455454",
"issueDate": "2012",
"dob": "23/05",
"isFavourite": false,
"_id":"63b974e6bd0d03c116955f67"
}
],
"licenseCardsArray": [
{
"title": "Two Wheeler License",
"logoIndex": 0,
"category": "License",
"cardHolder": "Klaus Michealson",
"licenseNumber": "RJ/22/ADL-542/474/01",
"expiry": "2036",
"dob": "13/06",
"isFavourite": false,
"_id":"63b97535bd0d03c116955f69"
}
]
}
}
I want to find the user with _id
Then for that user i want to got to cardsData object
Then in cardsData object i want to got to bankCardsArray
Then in bankCardsArray , i want to update fields of a card with particular id
Const res = findOneAndUpdate(
{ 'cardsData.bankCardsArray._id':card_id },
{ $set{ 'cardsData.bankCardsArray.$.title': req.body.title });
Use "." operator to access nested fields.
Refer these mongodb documentation
query-array-of-documents
query-embedded-documents.
Hope this helps.

How can I mutate the json in the following way in javascript

I have been asked in an interview to mutate the array of objects in such a way that the data appears in the following manner
[
{
"companyName": "ABC",
"members": [
{
"id": 13121212,
"firstName": "Ray",
"lastName": "Fernandis",
"points": 1800,
"position": 1
},
{
"id": 13131313,
"firstName": "Carrie",
"lastName": "Yoda",
"points": 1200,
"position": 2
}
]
}]
and the sample data was given below.
[
{
"communityName": "ABC",
"lastUpdateTimestamp": {
"date": {
"year": 2020,
"month": 10,
"day": 7
},
"time": {
"hour": 18,
"minute": 6,
"second": 5,
"nano": 536529000
}
},
"data": {
"listChannelsData": [
{
"channelId": 1234,
"channelName": "BCD",
"members": [
{
"id": 13121212,
"firstName": "Ray",
"lastName": "Fernandis",
"points": 1800,
"position": 1
}
]
}
]
}
},
{
"communityName": "DEF",
"lastUpdateTimestamp": {
"date": {
"year": 2020,
"month": 10,
"day": 7
},
"time": {
"hour": 18,
"minute": 6,
"second": 21,
"nano": 47894000
}
},
"data": {
"listChannelsData": [
{
"channelId": 3421,
"channelName": "GHI",
"members": [
{
"id": 13121212,
"firstName": "Nicholas",
"lastName": "Xin",
"points": 800,
"position": 2
},
{
"id": 13131313,
"firstName": "Carrie",
"lastName": "Yoda",
"points": 1000,
"position": 1
}
]
}
]
}
}
]
The agenda for me was to print the derived json from sample json and I could only figure out this much code which was a courtesy of stackoverflow
function dictionary(data) {
var map = {};
data.forEach(item => {
if (!Array.isArray(map[item.companyName])) {
map[item.companyName] = [item.data.listChannelsData];
} else {
map[item.communityName].push(item.data.listChannelsData);
}
});
return map;
}
console.log(dictionary(data));
But now when I try to pick up the data for the member using another foreach loop, I'm not able to access the data for members. Can anyone help me with the part where I can successfully access the member array and print the company name along side it
Try this code
var newArray = []
data.map((item, index) => {
newArray[index] = {companyName : item.communityName}
newArray[index].members = item.data.listChannelsData[0].members
})
data is the given data.

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

how to create a query with geolocation in mongoose (use for search by near places)

I'm quite new in mongodb and mongoose. I don't know if my query is working but when I add some geojson to my code it returns null.
My only target is can filter my data using state,country and state and also search nearby places. It would be really great help if someone can help me. Thanks
var query = {
$and : [
{city : new RegExp('^'+req.body.city+'$', "i") },
{state : req.body.state},
{country : req.body.country},
{
loc : {
$nearSphere : {
$geometry : {
type : "Point",
coordinates : [-117.16108380000003,32.715738]
},
$maxDistance : 100
}
}
}
Business.find(query).populate('deal_id').sort({business_type : -1,deal_id : -1})
.exec(function(err,businesses){
res.json(businesses)
return
})
I don't know if im doing it right, here's my sample data:
[
{
"_id": "5a0b1f489929442c36fd5c83",
"business_row": 29160,
"created_at": "2017-11-14T16:52:10.130Z",
"owner_name": "David Lui",
"company_website": "",
"phone_number": "604-273-3288",
"contact_name": "David Lui",
"zip_postal": "V6X 3Z9",
"state": "British Columbia",
"country": "Canada",
"city": "Richmond",
"address": "3779 Sexsmith Rd # 2172 Richmond British Columbia",
"company_name": "Aem Seafood",
"__v": 1,
"slug": "Aem-Seafood&Richmond",
"loc": {
"coordinates": [
"-123.129488",
"49.185359"
],
"type": "Point"
},
"deal_id": [],
"is_favorite": false,
"is_draft": false,
"has_featured": false,
"owner_id": [
"5a0adcf9f7205f0004535def"
],
"files": [],
"operations": [],
"sub_category": [],
"category_options": [
{
"value": "5a0b186b9f3a4a2710075654",
"sub_cat": {
"value": "59f6d13d00086a6e645c50a4",
"label": "Meat And Fish Markets"
}
}
],
"category_id": [
"5a0b186b9f3a4a2710075654"
],
"business_type_name": "Free",
"business_type": "0",
"user_id": [
"5a0adcf9f7205f0004535def"
]
}
]
turns out i don't need to query the city,state and country for it and use $geoWithIn

Synonyms, storing weights in document for relevance scoring in Elastic Search

The story: Given the example documents below and by extending them, is it possible to get the following ranking:
A search on "Cereals" results in the following ranking
Cornflakes
Rice Krispies
A search on "Rice" results in the following ranking
Basmati
Rice Krispies
The documents against the search is performed:
[{
name: "Cornflakes"
},
{
name: "Basmati"
},
{
name: "Rice Krispies"
}]
Of course, some of them does not even held the search term, so an option is to add an array of synonyms with a text value and weight with would help in computing the ranking:
[{
name: "Cornflakes",
synonyms: [
{t: 'Cereals', weight: 100},
{t: 'Sugar', weight: 100}]
},
{
name: "Basmati",
synonyms: [
{t: 'Cereals', weight: 1},
{t: 'Rice', weight: 1000}]
},
{
name: "Rice Krispies",
synonyms: [
{t: 'Cereals', weight: 10},
{t: 'Rice', weight: 1}]
}]
Is it the right approach?
What is the Elastic Search query for taking into account weighted synonyms?
I think "tags" would be a more appropriate name for the field than "synonyms".
You could use a nested type to store tags and use function score to combine the value of the tags.weight field (of the best matching tag if any) with the match score on the name field.
One such implementation could look as follows:
put test
put test/tag_doc/_mapping
{
"properties" : {
"tags" : {
"type" : "nested" ,
"properties": {
"t" : {"type" : "string"},
"weight" : {"type" : "double"}
}
}
}
}
put test/tag_doc/_bulk
{ "index" : { "_index" : "test", "_type" : "tag_doc", "_id":1} }
{"name": "Cornflakes","tags": [{"t": "Cereals", "weight":100},{"t": "Sugar", "weight": 100}]}
{ "index" : { "_index" : "test", "_type" : "tag_doc","_id":2} }
{ "name": "Basmati","tags": [{"t": "Cereals", "weight": 1},{"t": "Rice", "weight": 1000}]}
{ "index" : { "_index" : "test", "_type" : "tag_doc","_id":3} }
{ "name": "Rice Krispies", "tags": [{"t": "Cereals", "weight": 10},{"t": "Rice", "weight": 1}]}
post test/_search
{
"query": {
"dis_max": {
"queries": [
{
"match": {
"name": {
"query": "cereals",
"boost": 100
}
}
},
{
"nested": {
"path": "tags",
"query": {
"function_score": {
"functions": [
{
"field_value_factor": {
"field": "tags.weight"
}
}
],
"query": {
"match": {
"tags.t": "cereals"
}
},
"boost_mode": "replace",
"score_mode": "max"
}
},
"score_mode": "max"
}
}
]
}
}
}
Result :
"hits": {
"total": 3,
"max_score": 100,
"hits": [
{
"_index": "test",
"_type": "tag_doc",
"_id": "1",
"_score": 100,
"_source": {
"name": "Cornflakes",
"tags": [
{
"t": "Cereals",
"weight": 100
},
{
"t": "Sugar",
"weight": 100
}
]
}
},
{
"_index": "test",
"_type": "tag_doc",
"_id": "3",
"_score": 10,
"_source": {
"name": "Rice Krispies",
"tags": [
{
"t": "Cereals",
"weight": 10
},
{
"t": "Rice",
"weight": 1
}
]
}
},
{
"_index": "test",
"_type": "tag_doc",
"_id": "2",
"_score": 1,
"_source": {
"name": "Basmati",
"tags": [
{
"t": "Cereals",
"weight": 1
},
{
"t": "Rice",
"weight": 1000
}
]
}
}
]
}

Resources