I am using elasticsearch (managed instance from searchly) with the elasticsearch-js npm client library. I want to search multiple fields in my index from a term. There seems to be loads of documentation on this, e.g.
GET /_search
{
"query": {
"bool": {
"should": [
{ "match": { "title": "War and Peace" }},
{ "match": { "author": "Leo Tolstoy" }}
]
}
}
}
where I could just set the same value for author and title. However, this is a get request and is structured differently to the nodejs library, where I am doing this:
this._client.search({
index: 'sample',
body: {
query: {
match: {
name: 'toFind'
}
}
}
}).then(function (resp) {
var hits = resp.hits.hits;
}, function (err) {
console.trace(err.message);
});
I can't have multiple match: fields otherwise tsc complains about strict mode, and if I try something like:
query: {
match: {
name: 'toFind',
description: 'toFind'
}
}
then I get an error:
"type": "query_parsing_exception",
"reason": "[match] query parsed in simplified form, with direct field name, but included more options than just the field name, possibly use its \u0027options\u0027 form, with \u0027query\u0027 element?",
Since you want to match same string on multiple fields you need multi match query. Try something like this
this._client.search({
index: 'sample',
body: {
query: {
multi_match: {
query: 'toFind',
fields: ['name','description']
}
}
}
}).then(function (resp) {
var hits = resp.hits.hits;
}, function (err) {
console.trace(err.message);
});
Related
I've been dealing with a project. My goal is to get result from search engine in all circumstances for example, although i enter a keyword which is not include the keys inside data or is a empty string, I still need to get some result.How can i reach my goal?
you can see the query below :
query: {
regexp: {
title: "something to not found .*",
},
Try use "prefix" or "query_string"
You also can use title.keyword for exact value
1 -
{
"query": {
"prefix": {
"title": {
"value": "<data>"
}
}
}
}
2 -
{
"query": {
"query_string": {
"default_field": "title",
"query": "<data>*^0"
}
}
}
How can I select multiple fields when using the documents.get ?
Right now I am getting the documenmt like this:
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
fields: 'body/content'
});
which returns this:
"data": {
"body": {
"content": [...]
}
}
However, I need to also get the inlineObject and the only way so far I have been able to do so, is by removing the fields proeprty completely
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
});
Then I get this:
"data": {
"title": "Some document title",
"body": {
"content": [...]
},
"headers": {
},
"footers": {
},
"documentStyle": {
},
"namedStyles": {
},
"lists": {
},
"revisionId": "some-long-id",
"suggestionsViewMode": "SUGGESTIONS_INLINE",
"inlineObjects": {
},
"documentId": "some-long-id"
}
But I am really only interested in data.body.content and data.inlineObjects
When selecting everything the response is many thousands of lines of json larger, which I don't want.
I have tried fields: ['body/content', 'inlineObjects'] but that only returns body.content and not the inlineObjects - also the documentation doesn't mention this syntax anywhere, it was just to experiment.
I think it doesn't return any inlineObjects when you don't have any inlineObjects in the document. To confirm if the actual format is working and the statement above is true, try using other fields where a value is confirmed to be returned such as revisionId or title.
Test:
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
fields: 'body/content,inlineObjects'
});
Output:
I'm learning FQL and trying to do a mass update, but I can't figure out what I'm doing wrong, nor can I really figure out what the error is really pointing to.
Here is my code:
const updateResult = await serverClient.query(
q.Map(
guests,
q.Lambda(
"guest",
q.Update(q.Var("guest").id, {
data: {
emailSent: q.Var("guest").emailSent,
emailStatus: q.Var("guest").emailStatus,
emailRejectReason: q.Var("guest").emailRejectReason,
},
})
)
)
);
Here is the what the guests object is via console.log:
[ { email: 'myemail+bart72320#gmail.com',
emailStatus: 'sent',
emailRejectReason: null,
emailSent: true,
id: Ref(Collection("Guests"), "271884343706649107") } ]
Here is that same object with JSON.stringify:
[
{
"email": "myemail+bart72320#gmail.com",
"emailStatus": "sent",
"emailRejectReason": null,
"emailSent": true,
"id": {
"#ref": {
"id": "271884343706649107",
"collection": {
"#ref": {
"id": "Guests",
"collection": {
"#ref": {
"id": "collections"
}
}
}
}
}
}
}
]
Here is part of the error that is returned:
{ [BadRequest: invalid expression]
name: 'BadRequest',
message: 'invalid expression',
description:
'No form/function found, or invalid argument keys: { params }.',
requestResult:
RequestResult {
method: 'POST',
path: '',
query: null,
requestRaw:
'{"map":{"lambda":"guest","expr":{"params":{"object":{"data":{"object":{}}}}}},"collection":[{"object":{"email":"myemail+bart72320#gmail.com","emailStatus":"sent","emailRejectReason":null,"emailSent":true,"id":{"#ref":{"id":"271884343706649107","collection":{"#ref":{"id":"Guests","collection":{"#ref":{"id":"collections"}}}}}}}}]}',
requestContent: Expr { raw: [Object] },
responseRaw:
'{"errors":[{"position":["map","expr"],"code":"invalid expression","description":"No form/function found, or invalid argument keys: { params }."}]}',
I've gotten updates to work and lambdas to work, but not this one and maybe I'm just bad at reading very nested, functional looking error messages. What is a form and is it the same as a function, or am I missing keys: params? I don't know what to make of this.
Please help me understand what I'm doing wrong and if this error message is actually helpful and how to interpret it or if it's just a confusing catchall?
Thanks!
You are mixing Javascript syntax with FQL expressions.
Var("guest")
is a FQL expression, but
Var("guest").id
is a Javascript syntax. The equivalent of dot operator in FQL is
Select("id", Var("guest"))
Remember that FQL is not executed on Javascript, but is executed on server side.
I have a node object that looks like this:
{
"_id":"58b336e105ac8eec70aef159",
"name":"my node",
"ip":"192.168.1.1",
"__v":0,
"configuration":{
"links":[
{
"linkName":"athena_fw_listen_tcp_5555",
"_id":"58b336e105ac8eec70aef15d",
"local":true
},
{
"linkName":"athena_fw_listen_udp_5554",
"_id":"58b336e105ac8eec70aef15c",
"local":true
}
]
}
}
I am sending a delete request to my express server that looks like this:
DELETE http://localhost:9000/api/nodes/58b336e105ac8eec70aef159/links/58b336e105ac8eec70aef15d
I followed instructions in $pull mongodb documentation and I also tried this
But it does not seem to work, as I keep receiving: 500 (Internal Server Error)
This is how the code on my express side looks like:
exports.destroyLink = function(req, res) {
Node.findById(req.params.id, function(err, node) {
if (err) { return handleError(res, err); }
if (!node) { return res.status(404).send('Not Found'); }
console.log("Node", JSON.stringify(node))
console.log("Params", req.params)
node
.update({ '_id': req.params.id }, { $pull: { 'configuration': { 'links': { '_id': req.params.linkId } } } }, false, true)
.then(err => {
if (err) { return handleError(res, err); }
return res.status(204).send('No Content');
});
})
};
The express router contains this:
router.delete('/:id/links/:linkId', controller.destroyLink);
So I am expecting id and linkId as params, I use id (_id: req.params.id) to target a specific node and linkId (_id: req.params.linkId) to target a specific link, but it doesn't work!
Need help resolving the issue, I don't know what I am missing here!
Hi all and thank you for your help. I finally got it to work!!!
After almost 3 hours of troubleshooting :'( :'( this is the solution that used:
exports.destroyLink = function(req, res) {
Node.findByIdAndUpdate(
req.params.id, { $pull: { "configuration.links": { _id: req.params.linkId } } }, { safe: true, upsert: true },
function(err, node) {
if (err) { return handleError(res, err); }
return res.status(200).json(node.configuration.links);
});
};
Instead of findById then update the node, I did both using findByIdAndUpdate. It' working perfectly now!!!
I still don't find an explanation for the other version though. But anyways glad it's working this way.
I had a similar issue getting a query like yours working. I think your query is not finding the id you're looking for. If you want to find an object in mongo by '_id' it needs to be passed in as an ObjectId. Try modifying things so it looks like this:
const mongo = require('mongodb');
var oId = new mongo.ObjectID(req.params.id);
update({ '_id': oId }, { $pull: { 'configuration': { 'links': { '_id': req.params.linkId } } } }, false, true)
I never got this working using the mongodb $pull operator. An alternative is to find the document then update the array using the mongoose pull method. The pull method can take an id string as its single argument and knows how to handle it. For this example using promises the code would look something like:
exports.destroyLink = function(req, res) {
Node.findById(req.params.id)
.then(node => {
node.configuration.links.pull(req.params.linkId)
return node.save()
.then(node => res.send(node.configuration.links))
}
The mongoose docs for pull
I got the .update mongoose function to work by changing to this:
{ $pull: { 'configuration': { 'links': { '_id': ''+req.params.linkId+'' } } } }
Once you concatenate that, it'll pull it from the array.
For my problem, this worked
await FormSchema.updateOne({formName: name}, {$pull: {fields: {fieldName: fieldName}}}).exec();
and here is what my schema looks like
{
"fields": [
{
"contentType": "Text",
"fieldName": "First Name",
"textType": "short",
"isUnique": false
},
{
"contentType": "Boolean",
"fieldName": "Contact Me"
}
],
"_id": "61f71efd14cafb5a50ba365f",
"formName": "Contact",
"__v": 4
}
I'm trying to write a Joi validation for a JSON object coming into a Hapi handler. So far the code looks like this:
server.route({
method: 'POST',
path: '/converge',
handler: function (request, reply) {
consociator.consociate(request.payload)
.then (function (result) {
reply (200, result);
});
},
config: {
validate: {
payload: {
value: Joi.object().required().keys({ knownid: Joi.object() })
}
}
}
});
You can see the Joi object validation so far in the config: validate: code section above. The JSON coming in looks like this.
"key": '06e5140d-fa4e-4758-8d9d-e707bd19880d-testA',
"value": {
"ids_lot_args": {
"this_id": "stuff",
"otherThign": "more data"
},
"peripheral_data": 'Sample peripheral data of any sort'
}
In this JSON above the key and value at the root of the object are required, and the section called ids_lot_args is required. The section that starts with peripheral_data could be there or not, or could be any other JSON payload. It doesn't matter, only key and value at the root level and ids_lot_args inside the value are required.
So far, I'm stumbling through trying to get the Joi validation to work.
Any ideas on how this should be setup? The code repo for Joi is located at https://github.com/hapijs/joi if one wants to check it out. I've been trying the allow all functions on objects to no avail so far.
You just need to call the unknown() function on the value object:
var schema = Joi.object({
key: Joi.string().required(),
value: Joi.object({
ids_lot_args: Joi.object().required()
}).unknown().required()
});
You can use the "allowUnknown" parameter:
validate : {
options : {
allowUnknown: true
},
headers : {
...
},
params : {
...
},
payload : {
...
}
}
}
Try using Joi.any()
server.route({
method: 'POST',
path: '/converge',
handler: function (request, reply) {
consociator.consociate(request.payload)
.then (function (result) {
reply (200, result);
});
},
config: {
validate: {
payload: {
key: Joi.string().required(),
value: Joi.object({
ids_lot_args: Joi.object().required(),
peripheral_data: Joi.any()
})
}
}
}});