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.
Related
I'm trying to use the $set, $addToSet and $inc at the same time for my report of sales and
tbh I'm not even sure if I did the right approach since it's not working.
once I send the request, the console gives me the error 404 but when I check the req.body the data was correct. so I was wondering if the problem is my query on mongoose because this was the first time I use multiple operations on mongoose query
export const report_of_sales = async (req, res) => {
const { id } = req.params;
console.log(req.body);
try {
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'Invalid ID' });
let i;
for (i = 0; i < req.body.sales_report.length; i++) {
await OwnerModels.findByIdAndUpdate(id, {
$inc: {
total_clients: req.body.total_clients,
total_product_sold: req.body.sales_report[i].qty,
sales_revenue: req.body.sales_report[i].amount
},
$set: {
"months.$[s].month_digit": req.body.months[i].month_digit,
"months.$[s].targetsales": req.body.months[i].targetsales,
"months.$[s].sales": req.body.months[i].sales,
},
$addToSet: {
sales_report: {
$each: [{
identifier: req.body.sales_report[i].identifier,
product_name: req.body.sales_report[i].product_name,
generic_name: req.body.sales_report[i].generic_name,
description: req.body.sales_report[i].description,
qty: req.body.sales_report[i].qty,
amount: req.body.sales_report[i].amount,
profit: req.body.sales_report[i].profit
}]
}
}
}, {
arrayFilters: [
{
"s.month_digit": req.body.months[i].month_digit
}
],
returnDocument: 'after',
safe: true,
}, { new: true, upsert: true })
}
} catch (error) {
res.status(404).json(error);
}
}
Well, you are looking at the body, but you are actually using query parameter named id. This is probably undefined, which leads to ObjectId.isValid(id) returning false.
You should decide on whether to pass this data as a query param or in the request body and adjust your code accordingly.
Right now I am able to fetch the data and show in the table in front side, but I need
help to implement the code for skip, limit, searching, sorting and pagination so everything will be a functional.
I looked over the internet but didn't find good source to implement, I hope this might
help others in future. Anyone’s help will be appreciated.
**javascript code**
$(document).ready(function() {
let table = $('#exportable_table').DataTable({
"processing": true,
"searching": true,
"serverSide": true,
"ajax": {
url:"/employee/data-table/get-data",
error:(error)=>{
console.log(error);
}
},
'columns': [
{ data: '_id' },
{ data: 'employee_name' },
{ data: 'gender' },
{ data: 'email' },
{ data: 'mobile_number' },
{ data: 'salary' },
{ data: 'created_at' },
{ data: 'updated_at' },
{ data: '', "defaultContent": "<button class='btn btn-primary' onclick='edititem();'>Edit</button>" },
{ data: '', "defaultContent": "<button class='btn btn-danger' onclick='deleteitem();'>Delete</button>"}
],
});
});
**backend side logic**
employeeDataTableData: async (req, res) => {
let employeeData = await EmployeeService.getEmployee();
var response = {
"draw": parseInt(req.query.draw),
"iTotalRecords": employeeData.length,
"iTotalDisplayRecords": 2,
"data": employeeData
}
res.status(200).send(response);
}
**logic to fetch data from database**
exports.getEmployee = async () => {
try {
let employeeData = await EmployeeModel.find().lean();
if (!employeeData) return false;
return employeeData;
} catch (error) {
console.log("Error : ", error);
}
};
How can I update a field with new properties that is initially set to be an empty object?
For example, I have the following schema:
import mongoose from 'mongoose';
var RunSchema = mongoose.Schema(
{
runId: { type: String },
reports: {
cookieSummary: {
name: String,
path: String
}
}
}
)
export default mongoose.model('Run', RunSchema);
And I'm trying to update the following document:
{
"_id": {
"$oid": "5a0565c2537e0b5d9d08ee6b"
},
"__v": 0,
"reports": {},
"runId": "8r4LNN3fRqd3qNgdW"
}
But when I run this code, it returns undefined:
Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
{
$set: {'reports.cookieSummary': { 'name': 'test' }},
}, (err, doc) => { console.log(doc) })
The object notation works after adding type to fields, like this: name: { type: String }
Try to use dot notation, as you're setting just one field:
Run.findOneAndUpdate(
{ runId: '8r4LNN3fRqd3qNgdW' },
{ $set: {'reports.cookieSummary.name': 'test' } },
(err, doc) => { console.log(doc) })
According to the docs, the command you're using should work but you write it wrongly. Try like this:
Run.findOneAndUpdate(
{ runId: '8r4LNN3fRqd3qNgdW' },
{ $set: { 'reports.cookieSummary': {'name': 'test'} } },
(err, doc) => { console.log(doc) })
if it does not work, maybe mongo expect that the object matches its schema when you use the command like this. But I don't think so.
Let me know.
Your query for update a document is good only the mistake is at the end of curly braces of $set. You entered un-necessary comma at the end that is actually creating problem in this case. So I suggest you to remove it and run this :
Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
{
$set: {'reports.cookieSummary': { 'name': 'test' }}
}, (err, doc) => { console.log(doc) });
and then see. Rest of your query is fine.
Hope It will work for you.
Thanks.
Try using below code, it will update the document and return the updated document.
var Q = require('q');
var deferred = Q.defer();
Run.findOneAndUpdate({ runId: '8r4LNN3fRqd3qNgdW' }, { $set: { 'reports.cookieSummary.name': 'test' } }, { new: true },
(err, doc) => {
console.log(doc);
deferred.resolve(doc);
});
return deferred.promise;
I made a small change. Test this solution.
Run.findOneAndUpdate({runId: '8r4LNN3fRqd3qNgdW'},
{
$set: {"reports": {'cookieSummary':{'name': 'test'}}},
}, (err, doc) => { console.log(doc) })
Am new to elastic search and struggling to delete an entry from my collection.
I need a query similar to this one
DELETE FROM message WHERE id='1323'" and created_user = "user#gmail.com".
Following are my elastic search query, when i execute this, its only deleting the particular id field, its not taking the second argument created_user. Please help me to solve this issue. Thanks
var created = "9ed8afe738aa63c28b66994cef1f83c6"
db.delete({
index: 'outboxpro',
type: 'message',
id: req.body.post_id,
created_user: created
}, function (error, resp) {
if (error) {
return next(error);
}
var data = {};
console.log('delete response',resp);
if (resp.hits.successful < 1) {
data = {status: false, message: 'NO POST FOUND TO DELETE', code: 400};
res.send(data);
} else {
return next({status: true, message: 'POST DELETED', data: error, code: 500});
}
});
//// EDIT
I have tried deleteByQuery, following are my code
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body:{
"query": {
"filtered": {
"query": {
"match": {
"_id": {
"query": "Kal4AXi5R9G-IMx4GIKYMw"
}
}
},
"filter": {
"and": [
{
"term": {
"created_user": created
}
}
]
}
}
}
}
}, function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});
You can delete documents matching your query, using delete by query in elasticsearch.. Refer
http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/api-reference-1-0.html#api-deletebyquery-1-0
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body: {
"query": {
"filtered": {
"query": {
"match": {
"_id": "Kal4AXi5R9G-IMx4GIKYMw"
}
},
"filter": {
"term": {
"created_user": "created"
}
}
}
}
},
function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});
The delete API will do exactly what you want, just in a slightly round-about way.
What you'll have to do first is search for the documents you want to delete, so construct a search query that find all documents with the id of '1323' and a created_user of 'user#gmail.com'. From the returned documents you'll be able to retreive the document ID which you then need to pass through to the delete API.
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete.html
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 } } } )
});