How to create a query for multiple ranges? - reactjs

I'm experiencing issues with how to create a multi range query.
So I'm using a library that creates a query using a setQuery function, which accepts an object. Scroll down to setQuery
Now currently my function creates a single range query and works fine. I followed the ES Docs so it matches what I have currently written, which is...
const queryObject = {
query: {
range: {
[searchType]: {
gte: from,
lte: to,
boost: 2.0,
},
},
},
value: queryItem,
};
But I can't seem to find any documentation for multiple ranges that has a similar shape.
Any recommendations on how to handle this?
Thanks!

Did it!
So let's say I have an array of ranges
const sampleRanges = [{from: 1990, to: 1992}, {from: 1993, to: 1995}, {from: 1996, to: 2002}]
I created a function to map over those values soo...
const generateRangeQuery = () => {
return sampleRanges.map(value => ({
range: {
[searchType]: {
gte: value.from,
lte: value.to,
boost: 2.0,
},
},
}));
};
And the query for multi ranges should then look like:
const query = {
query: {
bool: {
should: generateRangeQuery(),
minimum_should_match: 1,
boost: 1.0,
},
},
};
and this works for me!

Related

How to filter multiple json items in a json array from onChange event

I have a react-select component that I am taking multiple values from. I am then trying to find all matches in a JSON array. I been trying for a while cant figure out the best way. I want to filter and print the matches. Below is the data. i want to get all conditions that match the selected symptoms.
export const symptomsCondition = [
{
condition: "Acetaminophen And Nsaid Toxicity",
symptions: ["Disorganized Speech", "Insomnia"],
},
{
condition: "Acne",
symptions: ["Swelling (Axilla)", "Bleeding Easily", "Difficult To Wake Up", "Increased Thirst"],
},
{
condition: "Adrenal Disorders (Addison’S Disease And Cushing’S Syndrome",
symptions: ["Weakness (Leg)", "Tremor", "Premature Ejaculation"],
},
{
condition: "Age Related Cognitive Decline",
symptions: ["Swelling (Jaw)", "Furry Tongue", "Headache (Worst Ever)", "Mucus In Eyes"],
},
{
condition: "Alcohol: Reducing The Risks",
symptions: [
"Pulling Out Eyebrows",
"Bleeding (Toes)",
"Craving To Eat Ice",
"Weakness (Shoulder)",
"Pounding Heart",
],
},
{
condition: "Allergies",
symptions: ["Thick Saliva", "Unable To Grip (Hands)", "Irregular Heartbeat"],
},
const [yoursymptoms, setYourSymptoms] = useState(null);
useEffect(() => {
symptomsCondition.symptoms.find((yoursymptoms) =>
console.log(yoursymptoms);
)
}, [yoursymptoms]);
onChange={setYourSymptoms}
You have to use filter on your array with the required criterias. Something like:
const allConditions = symptomsConditions.filter(c => c.symptions.includes(yoursymptoms))
And if you want only conditions, you can chain this with
.map(c => c.conditon)

Custom label on d3plus-react Treemap

I have to customize the label of a d3plus-react series, the customization will be pretty close to the original one with the label and the percentage but instead of taking the name from the id as the original does I will take it from another field of the object (name).
The object has this structure:
id: string
name: string
value: number
parent: string
and that's my Treemap config:
const methods = {
data: propsData,
groupBy: ['parent', 'id'],
size: 'value',
tooltipConfig: {
title: (d) => `${d.parent} - <span>${d.name}</span>`,
},
legend: true,
shapeConfig: {
label: (d) => {
console.log(d);
return [d.name];
},
},
};
The problem is that I don't know how to modify the label of the tile without touching the shared percentage, I've searched through the docs but I haven't found nothing relevant.
Does anyone know if there are some official methods for doing this or I'll have to do it myself?
Desired result
I've found out that you have access also to the percentage, the code will be as following
const methods = {
data: propsData,
groupBy: ['parent', 'id'],
size: 'value',
tooltipConfig: {
title: (d) => `${d.parent} - <span>${d.name}</span>`,
},
legend: true,
shapeConfig: {
label: (d) => {
return [d.customProperty, d.percentage];
},
},
}
Instead of the name I've used a custom property previously added to the data object so the series have the desired name

Mongodb $in failure from added quotes when passing Array of values from a User Search

I've spent a very long time trying to find an answer, I've checked every proposed answer provided while making this question, so if this has been answered, sorry for wasting your time. I've been programming for 5 years, and have built a Jquery, PHP, Mysql application. Now I'm redoing it all in Vanilla Javascript and MongoDB using a node backend.
The Params are sent from the user and compiled at the server to formulate different search criteria.
The regArray takes the Params.Criteria and makes an array with each name as a RegExp. For a multiple fuzzy search, using Mongodb's aggregate $in. The failure happens because outer quotes are added when passing the output /John/gim, /Jack/gim, /James/gim to [] or any other way I've tried.
The commented out test part works.
What I need: [/John/gim, /Jack/gim, /James/gim] (Hardcoded Array) This return 2 Documents
What I get: ['/John/gim, /Jack/gim, /James/gim'] (Dynamically Coded) This Fails
If anyone can help me get the required result I would be incredibly thankful.
Here is my code, easy to test - no db needed.
const Params = {
Field: 'FirstName',
Criteria: 'John Jack James',
Seek: { On : false, Case: true},
Tag: { On: false, By: true },
Or: false, Not: true,
ByDate: { Range: false, Year: false, Month: false, Day: false },
}
let regArray = Params.Criteria.split(' ').map((knit) => new RegExp(knit, 'igm')).join(', ')
console.log('regArray: ', regArray);
let findaMatch = ({ $match : { [Params.Field] : { $in : [regArray] } }})
// let test = [/John/gim, /Jack/gim, /James/gim]
// let findaMatch = ({ $match : { [Params.Field] : { $in : test } }})
console.log('findaMatch: ', findaMatch);
Whatever you are trying to do with [Params.Field] needs to be redone. There is nothing in MQL (MongoDB query language) that accepts arrays as keys like that.
Found my answer by removing .join()
let Result = 'John Jack James'.trim().split(' ')
var range = []
for (var i = 0; i < Result.length; i ++ ) {
range.push( new RegExp(Result[i], 'igm') )
}
or
let regArray = Params.Criteria.split(' ').map((knit) => {
return new RegExp(knit, 'igm')
})
Now I get [/John/igm, /Jack/igm, /James/igm]
And NOT ["/John/igm, /Jack/igm, /James/igm"]
Now it's an Array of Regexp values, instead of a useless string.

Flatten object type with array property in typescript react for output to react-data-grid

Apologies in advance if this has already been answered, but I am struggling to find an answer to it...
I have an array which contains a 2 d array property.
What I want returned is a type which contains has the inner array as a flat object.
So for example my array could be
{
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
**data: {
"114": "137.623",
"115": "51.090",
}**
}
What I would like is my output to be
{
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
"114": "137.623",
"115": "51.090",
,
}
Now here is my code to generate the array.
The Type:
type TableItem =
{
name: string,
event: string,
session: string,
frameType: string,
stint: number,
chassis: string,
driver: string,
data: (string | number)[][]
};
const getTableItem = (index: number) =>
{
const d = data[index];
//Transformentry just makes the id 3 digits
const dataItems = Object.assign({}, ...Object.entries(d.data).map(transformEntry));
const tableItem: TableItem = {
name: d.name,
event: d.event,
piolt: d.pilot,
session: d.session,
frameType: d.frameType,
stint: d.stint,
plane: d.plane,
data: dataItems
};
return tableItem;
};
const rows = (data.map((d, index) => { return getTableItem(index); }));
Now what I want is the rows variable(const) to contain the flattened array. I have tried flat/flatmap and reduce but can't get them to work.
If anyone can point me in the right direction with this it would be massively appreciated. Basically the rows const will then be passed to the react-data-grid component.
Thanks in advance
Steve
The data property is not an array, it is another object which may be why things like flatMap did not work for you.
If you're happy to retain the data property but also flatten the properties therein into the top level object you could just flatten it with the spread operator ...:
const input = {
name: "Widget",
event: "Xmas",
pilot: "Dave",
session: "drinking",
frameType: "flight",
stint: 2016,
plane: "737",
data: {
"114": "137.623",
"115": "51.090",
}
};
const result = {...input,...input.data};
console.log(result);
If you must get rid of the data property you could just add delete result.data; to the above.

How to pull data from deeply nested array in mongodb?

Hi I have deeply nested array in my mongoose schema. I want to pull record from that deeply nested array. Can anyone please help in writing the moongoose query. I tried this
var condition = {
_id: user,
$and: [
{
'cardInfo.cards': {
$elemMatch: {
_id: cardId,
isActive: '0'
}
}
},
{
'cardInfo.cards': {
$elemMatch: {
_id: { $exists: true }
}
}
}
]
};
var dataToUpdate = {
$pull: {'cardInfo.cards': { _id: cardId }}
};
var options = {
lean: true
}
for schema please look at MyAnotherQuestion and please try to answer that question as well. Above query is not working but in mongodb it is working fine if I use ObjectId for cardId
Ok I have been able to resolve the issue. What I did is just added an another parameter in options variable like:
var options = { strict: false, lean: true}
strict: false is the parameter which made my query to work and my mongoose query is same i.e
Customer.update(condition, dataToUpdate , options, anycallback)
and yes it is working for me.

Resources