Update numeric and float fields in elasticsearch client - node.js

I am bit new to elasticsearch client.
I have not done any type of predefined mapping to any field, because I might add some new field to the documents in future.
My data looks like this:-
{
"segmentId": "4700-b70e-881",
"segmentName": "test",
"data": "This is a test data",
"dataId": "70897e86-9d69-4700-b70e-881a7f74e9f9",
"augmented": false,
"createdBy": {
"email": "2010abinas#gmail.com",
"primaryKey": "902d2b57-54e6",
"secondaryKey": "adcc-f20423822c93"
},
"status": "active",
"createdAt": 1617422043554,
"updatedAt": 1617422043554
}
I wanted to update 3 fields by using updateByQuery.
I was trying below approach.
await esClient.updateByQuery({
index: "data",
type: "doc",
refresh: true,
body:{
query:{
match: {
dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
}
},
script:{
lang:"painless",
source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=${Date.now()};ctx._source.segmentId=null`
}
}
})
I am getting compilation error because of updatedAt and segmentId, When I pass as string it works, like:-
source:`ctx._source.data='This is updated test data';ctx._source.updatedAt='${Date.now()}';ctx._source.segmentId='null'`

I found a way to solve the above issue,
await esClient.updateByQuery({
index: "data",
type: "doc",
refresh: true,
body:{
query:{
match: {
dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
}
},
script:{
lang:"painless",
source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=params.date;ctx._source.segmentId=params.segmentId`,
params:{
date: Date.now(),
segmentId: null
}
}
}
});

Related

Order result resolved via resolver in graphql + apollo server + nodejs

I am trying to order an array returned by resolver in GraphQL.
I can only think of way of ordering data using DB Query, but how can we order data that GraphQL resolves using its resolver functions?
Below is my Query resolver:
getAllNotifications: (
_parent,
_args: { authorId: string },
context: Context
) => {
return context.prisma.blog.findMany({
where: {
authorId: _args.authorId,
},
orderBy: {
created_at: "desc",
},
});
},
And my query:
query Query($authorId: String) {
getAllNotifications(authorId: $authorId) {
title
comment {
id
created_at
}
}
}
And result:
{
"data": {
"getAllNotifications": [
{
"title": "First Ride! ",
"comment": [ <--- I am trying to order this comment array using created_at date
{
"id": "cl8afqaqx001209jtxx7mt5h6",
"created_at": "2022-09-20T16:53:07.689Z"
},
{
"id": "cl8agiq71001509l27or7oxyd",
"created_at": "2022-09-20T17:15:14.077Z"
},
{
"id": "cl8ahmvrm003109l8dp684bn6",
"created_at": "2022-09-20T17:46:27.538Z"
},
{
"id": "cl99kj24p002609iajdbpycg0",
"created_at": "2022-10-15T06:59:24.169Z"
}
]
}
]
}
}
I didn't found anything in Graphql docs regarding ordering data returned by resolver
GraphQL doesn't have functions for selection and ordering, those are jobs that resolvers must do.
Add a resolver for comment that sorts the comment array. Your existing sort just sorts based on the created_at date of the post.

Updating an array of objects iteratively in mongodb nodejs

I am trying to update a couple of objects in the MongoDB in nodejs. Here's the problem I'm having: I have an array of objects kind of looks like this:
[{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2200 TL"
},
{
"_id": "40", // this object is recently added so it doesn't
// have an oid it needs to be inserted instead of updating.
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "4+1 Ev Taşıma",
"value": "7000 TL"
},
]
I'm trying to update every one of these objects using collection.updateMany with upsert: true
Here's the code I wrote:
mongodb.collection('prices').updateMany({}, {$set: post.prices}, {upsert: true}, (error, result) => {
if(error) throw error;
res.json(response);
})
Here's the error:
MongoError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not
{$set: [ { _id: "5ed611265828aa77c978afb4", advert_id: "5ec2e4a8bda562e21b8c5052", isCategory: false, name: "2+1
Ev Taşıma", value: "2000 TL", isVisible: false } ]}
The problem seems that I'm trying to pass prices array directly into the $set pipe. What's a field type and how can I translate my array into that.
Appreciate the help, had some difficult time searching through the documentation but couldn't find any related chapter. I can really appreciate it if you can also link the documentation's related part in your answer.
Database document:
{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2000 TL",
"isVisible": false
}
I see a problem here {$set: post.prices}
It should be {$set: {'prices':post.prices}} - You should provide a document to $set
Refer
db.col.find({
'_id.$oid': '5ed611265828aa77c978afb4'
},
{
$set: {
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false
},
{
upsert: true
}
}

Not able to query for nested relations using dgraph-orm

I am using dgraph-orm for fetching nested relational values but it works for single level but not multiple level.
I am getting the page details but unable to fetch the avatar of the page.
Here is my snippet:
let posts = await PagePost.has('page_id', {
filter: {
page_id: {
uid_in: [page_id]
}
},
include: {
page_id: {
as: 'page',
include: {
avatar: {
as: 'avatar'
}
}
},
owner_id: {
as: 'postedBy'
}
},
order: [], // accepts order like the above example
first: perPage, // accepts first
offset: offset, // accepts offset
});
I am not getting avatar for the attribute page_id:
{
"uid": "0x75b4",
"title": "",
"content": "haha",
"created_at": "2019-09-23T08:50:52.957Z",
"status": true,
"page": [
{
"uid": "0x75ac",
"name": "Saregamaapaaaa...",
"description": "This a is place where you can listen ti thrilling music.",
"created_at": "2019-09-23T06:46:50.756Z",
"status": true
}
],
"postedBy": [
{
"uid": "0x3",
"first_name": "Mohit",
"last_name": "Talwar",
"created_at": "2019-07-11T11:37:33.853Z",
"status": true
}
]
}
Is there a support for multilevel field querying in the orm??
There was some issue with ORM itself it was not able to recognize the correct model name for multilevel includes and generating the wrong queries.
Fixed the same in version 1.2.4, please run npm update dgraph-orm --save to update your DgraphORM.
Thanks for the issue.

Sequelize - get proper path while validating associations of a model

I'm using Sequelize as an ORM for my project. I have this structure:
const Event = sequelize.define('event', {
// fields defined
});
const Question = sequelize.define('question', {
description: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: '',
validate: {
notEmpty: { msg: 'Description should be set.' }
},
},
// other fields defined
});
Event.hasMany(Question);
Question.belongsTo(Event);
Then I create an instance of the Event model, with associate, like that:
const body = {
questions: [
{ description: '' } // is obviously invalid
],
// some other fields
}
const newEvent = await Event.create(body, {
include: [ Question ]
});
If I have validation errors for the Event instance itself, it returns SequelizeValidationError where I can see the path attribute for each ValidationErrorItem. However, when I have the validation error on a child model, the path attribute for this validation error is unclear:
{
"message": "Description should be set.",
"type": "Validation error",
"path": "description",
"value": "",
"origin": "FUNCTION",
"instance": {
"required": true,
"id": null,
"description": "",
"event_id": 60,
"updated_at": "2018-06-11T12:25:04.666Z",
"created_at": "2018-06-11T12:25:04.666Z"
},
"validatorKey": "notEmpty",
"validatorName": "notEmpty",
"validatorArgs": [
{
"msg": "Description should be set."
}
],
"__raw": {
"validatorName": "notEmpty",
"validatorArgs": [
{
"msg": "Description should be set."
}
]
}
The problem is, it's unclear what caused this error and which child is invalid. When I've used Mongoose as an ORM, if I'd do the same, the path attribute would be equal to something like questions.0.description, and that is way more clear, that way you can see which child is invalid.
So, my question is: is there a way to set up the path attribute while validating the child models?
Apparently it's not presented yet, I've filed an issue on Sequelize repo, here it is: https://github.com/sequelize/sequelize/issues/9524

Mongoose Mixed type field not getting populated

I have a json doc that has embedded document which is variable (but in json format). So I use Mixed Schema type.
When I save, everything works fine except the mixed type object doesn't get populated and won't save.
What am I doing wrong here ?
Updating --> What I mean is - everything works as expected except the data node (which is suppose to be of mixed type)
My Document Example:
{
"data": {
"user_name": "username",
"cart_items": [
{
"sku": "ABCD",
"msrp": 1250.25,
"discount": 10,
"final_price": 112.22
},
{
"sku": "PQRSDF",
"msrp": 12.25,
"discount": 10,
"final_price": 1.2
}
]
},
"template_id": "1",
"from": "x#gmail.com",
"send_status": 0,
"priority": 99,
"app_id": "app3",
"_id": "532a54aa1c76fba0874c48ea",
"bcc": [],
"cc": [],
"to": [
{
"name": "acv",
"email": "x#outlook.com"
},
{
"name": "pem",
"email": "y#gmail.com"
}
],
"call_details": {
"data_id": "01234",
"event_id": 25
}
}
code to insert:
Schema definition:
app_id : { type: String, trim: true },
priority: { type: Number},
send_status: { type: Number},
call_details : {
event_id : { type: Number},
data_id : { type: String, trim: true },
id : false
},
from : { type: String, trim: true },
to : [addressSchema],
cc : [addressSchema],
bcc : [addressSchema],
template_id : { type: String, trim: true },
data: { any: {} }
Code:
r.app_id = req.body.app_id;
r.priority= req.body.priority;
r.send_status= req.body.send_status;
r.call_details.event_id= req.body.call_details.event_id;
r.call_details.data_id= req.body.call_details.data_id;
r.from= req.body.from;
r.to = populate_address(req.body.to);
r.cc = populate_address(req.body.cc);
r.bcc = populate_address(req.body.bcc);
r.template_id= req.body.template_id;
r.data =req.body.data);
r.markModified('data');
r.save(function (err){
console.log("add");
res.send ("added");
});
As you currently define your schema, it will only save the any field within data.
Remove the any embedded field from the definition for data in your schema.
So instead of:
data: { any: {} }
Use:
data: {}
As mongoose does not handle the embedded document save automatically. You need to save the embedded document first and assign the object ID to the parent schema as reference.

Resources