How to calculate based on the result of an aggregation? - node.js

For example, I can get the result of the average counts of request to a specific url base on parent id with the code below:
client.search({
index: 'console-*',
body: {
query: {
bool: {
query_string: {
query: 'meta.http.url:"https://www.google.com"'
}
}
},
aggs: {
parent_id: {
terms: {
field: 'parent_id'
}
}
}
},
size: 0
}).then(res => {
console.log(res.hits.total/res.aggregations.total.value)
})
Now let's say I have a number of urls like:
https://www.google.com
https://www.bing.com
https://www.apple.com
And I can use:
client.search({
index: 'console-*',
body: {
sort: {
'#timestamp': {
order: 'asc'
}
},
query: {
bool: {
must: [{
range: {
'#timestamp': {
gte: 'now-5m',
lte: 'now'
}
}
}, {
query_string: { query: '_exists_:meta.http.url' }
}]
}
},
aggs: {
urls: {
terms: {
field: 'meta.http.url'
},
aggs: {
total: {
cardinality: {
field: 'parent_id'
}
}
}
}
}
},
size: 0
}).then(res => {
console.log(JSON.stringify(res))
console.log(res.aggregations.urls.buckets.map(o => {
const res = {};
res[o.key] = o.doc_count / o.total.value;
return res;
}))
})
Is it possible to get the result without doing any additional calculation in Node.js?

Yes, you can leverage pipeline aggregations, and more specifically, the bucket_script one.
The aggs section would look like this instead and in each bucket you'll get the result of the document count divided by the total value stored in the compute section:
aggs: {
urls: {
terms: {
field: 'meta.http.url'
},
aggs: {
total: {
cardinality: {
field: 'parent_id'
}
},
compute: {
bucket_script: {
buckets_path: {
count: "_count",
total: "total"
},
script: "params.count / params.total"
}
}
}
}
}

Related

How to search part of a sentece in elasticsearch

I'm using Elasticsearch js to make a search engine, like so:
let jobs = await client.search({
index: 'index',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: 'test'
}
}
]
}
}
}
});
if the title has 'test' in it , it will show, but when it has something like 'hello this is/test' it wont show up, how do I fix it?
You can surround the string with *:
let jobs = await client.search({
index: 'index',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: '*test*'
}
}
]
}
}
}
});

How to update mongodb with multiple dynamic keys?

Server receives three dynamic keys: map_id -> section_id -> subsection_id.
User model:
{
_id: userId,
skills: {
[map_id]: {
[section_id]: {
[subsection_id]: {
...subsectionData
}
}
},
...otherMapKeys
}
}
How to update subsection data?
This solution with mongoose Model.update works correctly:
const dynamicLink = `skills.${map_id}.${section_id}.${subsection_id}`;
userModel.update(
{ id: userId },
{ $set: { [dynamicLink]: subsection } },
{ upsert: true }
);

How to query property keys with conditions in LoopBack

How to query the key values of properties in LoopBack? In my case, the keys are array of objects.
The schema I generated is,
{
"bookingsLog": [
{
"checkIn": 1456079400000,
"checkOut": 1456165800000
},
{
"checkIn": 1456079400000,
"checkOut": 1456165800000
}
]
}
The remote method used to query is,
Resort.search = function(custom, cb) {}
Resort.remoteMethod('search', {
accepts: {
arg: 'custom',
type: 'object',
http: function(ctx) {
var _cIn = ctx.req.body.checkIn;
var _cOut = ctx.req.body.checkOut;
Resort.find({
where: {
and: [{ checkIn: { neq: _cIn } }, { checkOut: { neq: _cOut } },
{ checkIn: { neq: { between: [_cIn, _cOut] } } },
{ checkOut: { neq: { between: [_cIn, _cOut] } } }
]
}
}, function(err, resorts) {
console.log('Length is = ' + resorts.Length);
console.log('Res is = ' + JSON.stringify(resorts));
if(err){return ctx.res.send(err);}
if(resorts){return ctx.res.send(resorts);}
});
}
},
returns: {
arg: 'custom',
type: 'object'
}
});
Thanks in advance!

Sails-mongo. Find in array

I'm using sails.js and sails-mongo adapter. Suppose I have a model:
module.exports = {
attributes: {
shema: true
, attributes: {
description: {
type: 'TEXT'
, max: 200
}
, tags: {
type: 'ARRAY'
}
}
}
};
How can I carry out a search in an tags array?
Model.find({
'tags.title': {
contains: 'query'
}
})
.done(function (err, response) {
/**/
});
db.schools.find( { criteria },
{ atributes: { $elemMatch: { tags: value } } } )
there are a great example here: http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/
with waterline
Model.native(function(err, collection) {
// Execute any query that works with the mongo js driver
collection.find( { criteria },
{ atributes: { $elemMatch: { tags: value } } } )
});

Not Getting Search value in Sencha Touch using searchfield

I want to display predictive text in search field, value for predictive text which comes from server. Here is my code so far:
View:
Ext.define('MyApp.view.AutoSearch', {
extend: 'Ext.dataview.List',
alias : 'widget.mainPanel',
config: {
store : 'AutoSearchStore',
itemTpl: '<div class="myWord">'+
'<div>Word is --<b>{name}</b>--- after search!!!</div>' +
'</div>',
emptyText: '<div class="myWord">No Matching Words</div>',
items: [
{
xtype: 'toolbar',
docked: 'top',
items: [
{
xtype: 'searchfield',
placeHolder: 'Search...',
itemId: 'searchBox'
}
]
}
]
}
});
Store:
Ext.define('MyApp.store.AutoSearchStore',{
extend: 'Ext.data.Store',
config:
{
model: 'MyApp.model.AutoSearchModel',
autoLoad:true,
id:'Contacts',
proxy:
{
type: 'ajax',
url: 'http://alucio.com.np/trunk/dev/sillydic/admin/api/word/categories/SDSILLYTOKEN/650773253e7f157a93c53d47a866204dedc7c363',
reader:
{
rootProperty:''
}
}
}
});
Model:
Ext.define('MyApp.model.AutoSearchModel', {
extend: 'Ext.data.Model',
requires: ['MyApp.model.AutoSearchModelMenu'],
config: {
fields: [
{name:'data', mapping: 'data'},
{name: 'name'},
],
},
});
and
Ext.define('MyApp.model.AutoSearchModelMenu', {
extend: 'Ext.data.Model',
config: {
fields: [
'name',
],
belongsTo: "MyApp.model.AutoSearchModel"
}
});
Controller:
Ext.define('MyApp.controller.SearchAutoComplete', {
extend : 'Ext.app.Controller',
config: {
profile: Ext.os.deviceType.toLowerCase(),
stores : ['MyApp.store.AutoSearchStore'],
models : ['MyApp.model.AutoSearchModel'],
refs: {
myContainer: 'mainPanel'
},
control: {
'mainPanel': {
activate: 'onActivate'
},
'mainPanel searchfield[itemId=searchBox]' : {
clearicontap : 'onClearSearch',
keyup: 'onSearchKeyUp'
}
}
},
onActivate: function() {
console.log('Main container is active--Search');
},
onSearchKeyUp: function(searchField) {
queryString = searchField.getValue();
console.log(this,'Please search by: ' + queryString);
var store = Ext.getStore('AutoSearchStore');
store.clearFilter();
if(queryString){
var thisRegEx = new RegExp(queryString, "i");
store.filterBy(function(record) {
if (thisRegEx.test(record.get('name'))) {
return true;
};
return false;
});
}
},
onClearSearch: function() {
console.log('Clear icon is tapped');
var store = Ext.getStore('AutoSearchStore');
store.clearFilter();
},
init: function() {
console.log('Controller initialized for SearchAutoComplete');
}
});
Json Data Looks Like:
"data":[
{
"name":"paint",
"author":"admin",
"word_id":"1",
"category":"Business",
"is_favourite":"yesStar"
},
{
"name":"abacus",
"author":"admin",
"word_id":"2",
"category":"Education",
"is_favourite":"yesStar"
},
{
"name":"abate",
"author":"admin",
"word_id":"3",
"category":"Education",
"is_favourite":"noStar"
},
{
"name":"testing adsf",
"author":"admin",
"word_id":"7",
"category":"Education",
"is_favourite":"noStar"
},
{
"name":"sprite",
"author":"admin",
"word_id":"6",
"category":"Business",
"is_favourite":"noStar"
},
{
"name":"newword",
"author":"admin",
"word_id":"8",
"category":"Architecture",
"is_favourite":"noStar"
}
]
})
If I type "A", then it displays No Matching Words, but I have words from "A" on json coming from server. How to solve this problem?
Any idea!
Code Sources Link
I don't know why you are using two models but just one thing you need to specify in AutoSearchStore :
reader:
{
rootProperty:'data'
}
instead of
reader:
{
rootProperty:''
}
to get the expected results in the list.
Hope this will be helpful :)

Resources