How to search part of a sentece in elasticsearch - node.js

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*'
}
}
]
}
}
}
});

Related

How to calculate based on the result of an aggregation?

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"
}
}
}
}
}

searching with elasticsearch js with multiple fields

Hi guys I have this code :
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
}
}
}
});
this code is searching by 1 query which is title: 'something' , but I want to change it to search with multiple keys, for example:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
match: {
title: 'something',
desc: 'some Qualifications'
}
}
}
});
but this code doesn't work and I can't find anything that will work like that, can anyone help?
You need to combine all the match queries using a bool/must query, like this:
let test = await client.search({
index: 'test',
type: 'doc',
body: {
query: {
bool: {
must: [
{
match: {
title: 'something',
}
},
{
match: {
desc: 'some Qualifications',
}
}
]
}
}
}
});

Get RANDOM ids with es query with node.js

could anyone help me? Im new in elasticSearch and node.js.
REQUEST
app.get('/', function (req, res, next){
try {
client.search({
index: 'dbcatalogo',
type: 'cars',
size: 10,
body: {
query: {
function_score:{
functions:[{
random_score:{
seed: 1
}
}]
},
match_all: {}
},
sort: {
'AnoModelo': 'desc'
}
}
}).then(function (json) {
res.json(json.hits);
},
function (err) {res.json(error.HandleError(err));});
}
catch (err) { res.json(error.HandleError(err)); }});
RESPONSE
[parse_exception] failed to parse search source. expected field name but got [START_OBJECT]
You are almost there the match_all needs to be within the query object of function_score as shows in function score below .
Example:
client.search({
index: 'dbcatalogo',
type: 'cars',
size: 10,
body: {
query: {
function_score:{
functions:[{
random_score:{
seed: 1
}
}],
query : {
match_all: {}
}
}
},
sort: {
'AnoModelo': 'desc'
}
}
}).then(function (json) {
res.json(json.hits);
}
Also if you are sorting on a field other than score the random_score does not make much sense.

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!

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