Sequelize find based on association and nested [Op.and] - javascript

I'm writing here because I'm completely lost. I would like to do a findall based on association and nested [Op.and], but I can't do it. Let me explain.
I have two tables (car and properties) with an association between these two tables (one car, can have several properties). The data looks like this :
{
"car": "BMW M5",
"properties": [
{
"name": "make",
"value": "bmw"
},
{
"name": "color",
"value": "blue"
}
]
},
{
"car": "AUDI A3",
"properties": [
{
"name": "make",
"value": "audi"
},
{
"name": "color",
"value": "black"
}
]
},
What I'm trying to do is a "findAll" of all cars of make BMW and with blue color. Logically, I would see something like this :
( properties.name = make & properties.value = audi ) & ( properties.name = color & properties.value = blue )
From this logic, I therefore tried to create the sequelize command below, but without success :
const cars = await models.Car.findAll({
include: [{
model: models.Properties,
required: false,
}],
where: {
[Sequelize.Op.and]:[
{[Sequelize.Op.and]: [{"$properties.name$": "make"}, {"$properties.value$": "bmw"}]},
{[Sequelize.Op.and]: [{"$properties.name$": "color"}, {"$properties.value$": "blue"}]},
]
});
Apparently when I do this it only takes the last [Op.and] ([Sequelize.Op.and]: [{"$properties.name$": "color"}, {"$properties.value$": "blue"}]), the others don't seem to be taken into consideration.
Maybe I'm wrong, but I tried several possibilities, but I don't know how to do it. Any help would be very appreciated, thank you in advance to everyone.

It seems you over-complicated the where condition:
const cars = await models.Car.findAll({
include: [{
model: models.Properties,
required: false,
}],
where: {
[Sequelize.Op.and]:[
{
"$properties.name$": "make",
"$properties.value$": "bmw"
},
{
"$properties.name$": "color",
"$properties.value$": "blue"
},
]
}
});
If you have different props in the same group of conditions then you can just use an object to combine them with AND operator.

Related

Match by multiple objects in array in Mongoose

My data looks like this
{
"_id": "62f77d806f24c09f0acae163",
"name": "Test product",
"attributes": [
{
"attribute_name": "Shape",
"attribute_value": "Square"
},
{
"attribute_name": "Color",
"attribute_value": "Red"
}
]
}
I am using the aggregate method to filter results where I want to find products where "attribute_name" is "shape" and the "attribute_value" is "Square" AND "attribute_name" is "Color" and the "attribute_value" is "Red"
Basically I am building a filter feature in my application and basis the data passed to the API I want to get the products.
I have tried this:
let lookup = {
$match: {
$and: [
{
'attributes.attribute_label': 'Shape',
'attributes.attribute_value': {
$in: ['Square']
},
},
{
'attributes.attribute_label': 'Color',
'attributes.attribute_value': {
$in: ['Red']
},
}
],
}
};
let products = await productsModel.aggregate(lookup);
At first it seemed like it worked, but then I noticed it doesn't work properly, it matches
'attributes.attribute_value': {
$in: ['Red']
},
so if it finds "Red" in "attribute_label" which can be anything other than "Color" it will still return the results.
Any help is appreciated
I want to be able to get results based on the values for each attribute name
For e.g data passed might be this
Shape=Square,Color=Red,Green
I want to get the products which matches this, where the object with attribute_label of Color contains the attribute_value of Red or Green.
Is it a typo? Once you are using "attributes.attribute_label" and once "attributes.attribute_name".
This should work with attributes.attrubite_name (not label!)
[
{
'$match': {
'$and': [
{
'attributes.attribute_name': 'Shape'
}, {
'attributes.attribute_value': {
'$in': [
'Square'
]
}
}, {
'attributes.attribute_name': 'Color'
}, {
'attributes.attribute_value': {
'$in': [
'Red'
]
}
}
]
}
}
]

Parsing Exception error when using Terms in ElasticSearch

I'm getting an error on this elastic search for terms. The error message is
"[parsing_exception] [terms] unknown token [START_ARRAY] after [activeIds], with { line=1 & col=63 }"
Active Ids is an array of unique ids. It sort of looks like
const activeIds = [ '157621a1-d892-4f4b-80ca-14feddb837a0',
'd04c5c93-a22c-48c3-a3b0-c79a61bdd923',
'296d40d9-f316-4560-bbc9-001d6f46858b',
'2f8c6c37-588d-4d24-9e69-34b6dd7366c2',
'ba0508dd-0e76-4be8-8b6e-9e938ab4abed',
'ab076ed9-1dd5-4987-8842-15f1b995bc0d',
'ea6b0cff-a64f-4ce3-844e-b36d9f161e6f' ]
let items = await es.search({
"index": table,
"body": {
"from": 0, "size": 25,
"query": {
"terms" : {
"growerId" : {
activeIds
}
},
"bool": {
"must_not": [
{ "match":
{
"active": false
}
},
],
"must": [
{ "query_string" :
{
"query": searchQuery,
"fields": ["item_name"]
}
}
],
}
}
}
})
Appreciate the help!
Edit: Answering this question- "What's the expected result? Can you elaborate and share some sample data? – Nishant Saini 15 hours ago"
I'll try to elaborate a bit.
1) Overall I'm trying to retrieve items that belong to active users. There are 2 tables: user and items. So I'm initially running an ES that returns all the users that contain { active: true } from the user table
2) Running that ES returns an array of ids which I'm calling activeIds. The array looks like what I've already displayed in my example. So this works so far (let me know if you want to see the code for that, but if I'm getting an expected result then I don't think we need that now)
3) Now I want to search through the items table, and retrieve only the items that contain one of the active ids. So an item should look like:
4) expected result is retrieve an array of objects that match the growerId with one of the activeIds. So if I do a search query for "flowers", a single expected result should look like:
[ { _index: 'items-dev',
_type: 'items-dev_type',
_id: 'itemId=fc68dadf-21c8-43c2-98d2-cf574f71f06d',
_score: 11.397207,
_source:
{ itemId: 'fc68dadf-21c8-43c2-98d2-cf574f71f06d',
'#SequenceNumber': '522268700000000025760905838',
item_name: 'Flowers',
grower_name: 'Uhs',
image: '630b5d6e-566f-4d55-9d31-6421eb2cff87.jpg',
dev: true,
growerId: 'd04c5c93-a22c-48c3-a3b0-c79a61bdd923',
sold_out: true,
'#timestamp': '2018-12-20T16:09:38.742599',
quantity_type: 'Pounds',
active: true,
pending_inventory: 4,
initial_quantity: 5,
price: 10,
item_description: 'Field of flowers' } },
So here the growerId matches activeIds[1]
But if I do a search for "invisible", which is created by a an inactive user, I get:
[ { _index: 'items-dev',
_type: 'items-dev_type',
_id: 'itemId=15200473-93e1-477c-a1a7-0b67831f5351',
_score: 1,
_source:
{ itemId: '15200473-93e1-477c-a1a7-0b67831f5351',
'#SequenceNumber': '518241400000000004028805117',
item_name: 'Invisible too',
grower_name: 'Field of Greens',
image: '7f37d364-e768-451d-997f-8bb759343300.jpg',
dev: true,
growerId: 'f25040f4-3b8c-4306-9eb5-8b6c9ac58634',
sold_out: false,
'#timestamp': '2018-12-19T20:47:16.128934',
quantity_type: 'Pounds',
pending_inventory: 5,
initial_quantity: 5,
price: 122,
item_description: 'Add' } },
Now that growerId does not match any of the ids in activeIds.
5) Using the code you helped with, it's returning 0 items.
Let me know if you need more detail. I've been working on this for a bit too long :\
Terms query accept array of terms so the terms query should be defined as below:
"terms": {
"growerId": activeIds
}
You might face other errors as well after making the above correction. So below is full query which might help you:
{
"from": 0,
"size": 25,
"query": {
"bool": {
"must_not": [
{
"match": {
"active": false
}
}
],
"must": [
{
"query_string": {
"query": searchQuery,
"fields": [
"item_name"
]
}
},
{
"terms": {
"growerId": activeIds
}
}
]
}
}
}

How to make dojo treeGrid categorized by two columns?

I have a simple dojo treeGrid that is categorized just by first column. But how to make it categorized/collapsible by second as well? Note the treeGrid has totals shown in each category. Also, is there a way to move totals to the category level but not to the bottom?
var layout = [
{ cells: [
[ {field: "year", name: "Year"},
{field: "childItems",
children: [ { field: "unid", name: "unid", hidden: true},
{ field: "geography", name: "Geography"},
{ field: "country", name: "Coungtry"},
{ field: "status", name: "Status"},
{ field: "credit", name: "Credit"},
{ field: "debit", name: "Debit"}
],
aggregate: "sum"
}
]] } ]
var jsonStore = new dojo.data.ItemFileWriteStore({ url: <...............>});
var grid = new dojox.grid.TreeGrid({
structure: layout,
store: jsonStore,
query: {type: 'year'},
queryOptions: {deep: true},
rowSelector: true,
openAtLevels: [false],
autoWidth: true,
autoHeight: true
},
dojo.byId("treeGrid"));
grid.startup();
dojo.connect(window, "onresize", grid, "resize");
sample JSON store:
{
"identifier": "id",
"label": "name",
"items": [
{
"id": "2018",
"type": "year",
"year": "2018",
"childItems": [
{
"id": "id0",
"geography": "Asia Pacific",
"country": "Australia",
"programname": "Program 1",
"totalPlanned": 0,
"totalForecasted": 0
},
{
.....
}
]
},
{
.....
}
]
}
You can find completely working example over here:
Now, let me try to explain it:
Data
First of all to support multiple levels in the grid you must have your data in the same format. For tree with n levels, you need to have n-1 level grouping in your data itself.
For example, JSON object below have 2 levels of grouping (year, geography) to support tree with 3 levels (root, parent, and child).
{
"identifier":"id",
"label":"name",
"items":[
{
"id":"2018",
"type":"year",
"year":"2018",
"geography":[
{
"id":"id1",
"geography":"Asia Pacific",
"childItems":[
{
"id":"ci1",
"country":"Australia",
"programname":"Program 1",
"credit":100,
"debit":50
}
]
}
]
}
]
}
Layout
To render a tree with n-levels you have to make sure layout of the tree is properly configured with same nesting as your data. To support data structure from JSON object above you need to set layout to:
[
{
cells:
[
[
{ field:"year", name:"Year" },
{
field:"geography",
children:
[
{ field:"geography", name:"Geography" },
{
field:"childItems",
children:[
{ field:"unid", name:"unid", hidden:true },
{ field:"country", name:"Country" },
{ field:"programname", name:"Program" },
{ field:"credit", name:"Credit" },
{ field:"debit", name:"Debit" }
],
aggregate:"sum",
},
]
}
]
]
}
]
You can see that, for each child level(s) you have to add a group (as I would like to call it) field and set first field within that group to your actual group field.
I hope this example will clear your doubt.
PS: In the jsfiddle version I have used formatters just to hide aggregate values for string fields.

Dynamically add an object property to existing object

So I have a json object such as:
"highChart":{
"xAxis":{
"categories":[
"SYN 13 ",
"Settlement",
"Service Interaction",
"FNOL",
"Repair Process",
"Rental Experience",
"Appraisal",
"SYN 14 "
],
"title":{
"text":""
},
"labels":{
"enabled":true,
"maxStaggerLines":1
},
"tickWidth":1
}}
Lets define this as $scope.chartConfig = highChart
Now I want to add another property to chartConfig like this:
"highChart":{
"options":{
"chart":{
"height":null,
"type":"waterfall"
}},
"xAxis":{
"categories":[
"SYN 13 ",
"Settlement",
"Service Interaction",
"FNOL",
"Repair Process",
"Rental Experience",
"Appraisal",
"SYN 14 "
],
"title":{
"text":""
},
"labels":{
"enabled":true,
"maxStaggerLines":1
},
"tickWidth":1
}}
So after initializing $scope.chartConfig = highChart I want to add the options property along with the chart property as shown above. How do I do that?
just like this...
$scope.chartConfig.options = {
"chart":{
"height":null,
"type":"waterfall"
}
};
Not 100% clear what you are asking but you can use angular.extend() to merge objects
var options = {
"chart": {
"height": null,
"type": "waterfall"
}
}
angular.extend($scope.chartConfig, options);
$scope.chartConfig now contains the new properties. If options had some properties that were the same as original but different values...the originaal would be updated with those values

Declaration 2d array containing multiple objects for graph plugin?

I using igDoughnutChart for my web-page, I want a graph which shows the following hierarchy
source of attack (inside)
login abuse
dos
spyware
worm
outside attackers
spying
social attacks
The current object array looks like (also demo)
var data = [
{ "attacksource": 43, "attacktype": 60, "AT":"DoS","Label": "iNISDE" },
{ "attacksource": 29, "attacktype": 40, "AT":"login abuse","Label": "outside" }
];
I want to change this to do following:- (also shown above)
Where I have a parent and child values in 2d array so above code is to transform as
var data =
[
[{"attacksource": 43,"Label":"Inside"}],
[
{"attacktype": 13,"Label":"dos"},
{"attacktype": 13,"Label":"virus"}...
]
];
I'm not sure If I have initialized / assigned 2d using objects correctly.I appreciate If someone can look at the code, and let me know if I'm doing this right.
UPDATE
The jsbin example is just something to illustrate my requirements for the new code. For e.g "Label":"virus" is currently hardcoded, in real code (which I cannot do on jsbin) is I will get the values from DB.
VISUAL EXAMPLE
I don't think the chart you are trying to use support what you want to do. That being said there is somewhat of a hack to make it work:
$(function () {
var data = [
{ "label": "Inside", "attacks": 8 },
{ "label": "Outside", "attacks": 6 },
// Inside
{ "label": "Dos", vector: "Inside", "dummyValue": 6 },
{ "label": "siem", detect: "Dos", "detectValue": 3 },
{ "label": "user", detect: "Dos", "detectValue": 3 },
{ "label": "Worm", vector: "Inside", "dummyValue": 2 },
{ "label": "siem", detect: "Worm", "detectValue": 1 },
{ "label": "user", detect: "Worm", "detectValue": 1 },
// Outside
{ "label": "Spying", vector: "Outside", "dummyValue": 3 },
{ "label": "siem", detect: "Spying", "detectValue": 1.5 },
{ "label": "user", detect: "Spying", "detectValue": 1.5 },
{ "label": "Social", vector: "Outside", "dummyValue": 3},
{ "label": "siem", detect: "Social", "detectValue": 1.5 },
{ "label": "user", detect: "Social", "detectValue": 1.5 },
];
$("#chart").igDoughnutChart({
width: "100%",
height: "550px",
innerExtent: 6,
series:
[
{
name: "Attack Type",
labelMemberPath: "label",
valueMemberPath: "attacks",
dataSource: data,
labelsPosition: "center"
},
{
name: "Attack Vector",
labelMemberPath: "label",
valueMemberPath: "dummyValue",
dataSource: data,
labelsPosition: "center"
},
{
name: "detect Vector",
labelMemberPath: "label",
valueMemberPath: "detectValue",
dataSource: data,
labelsPosition: "center"
}
]
});
});
The order of the data and series arrays matter (not completely, just partially). Here is a jsFiddle that demonstrates this. Disclaimer: I'm not saying this will always work, as it makes the big assumption that igniteUI will always parse and display the data in the same way.
Also I'm not familiar with the library but I would bet there is a way to customize the colors of each section of the chart. If so you could just make the color a function that returns a color based on the vector property.
Some alternatives:
Highcharts
D3 - this would be my preferred approach. Browse the gallery, there a few examples that apply here.

Categories