NodeJS–Add Array of String in PostgreSQL Query - node.js

I am trying to write a postgres query (executed in nodejs using a pool created using the node-postgres package) that will insert a new row in a table. One of the columns in this table is of type text[]. My code is as follows:
pool.query('INSERT INTO paragraphs (lines) VALUES (ARRAY[$1]::TEXT[]) RETURNING id', [my_array], (err, results) => {
if (err) {
reject(err)
return;
}
resolve(results.rows[0].id)
})
paragraphs is the name of my table and lines is the name of the column of type text[]. my_array is a list of strings. My problem is that what is inserted is not an array of strings, but rather a single string formatted like an array. e.x.:
{"[\"First line\", \"Second line\", \"Third Line\"]"}
I want it to be:
{"First line", "Second line", "Third Line"}
I have also tried taking out the ARRAY and TEXT parts (so the sql looks like INSERT INTO paragraphs (lines) VALUES ($1) RETURNING id in the above query), but then I receive the errors:
malformed array literal: "["New First line", "Second line", "Third Line"]"
DETAIL: "[" must introduce explicitly-specified array dimensions.
What is the correct way to insert lists of strings into PostgreSQL tables in nodejs through a query executed by a pool?

According to: https://node-postgres.com/features/queries#parameterized-query
Parameters passed as the second argument to query() will be converted to raw data types using the following rules:
...
Array
Converted to a string that describes a Postgres array. Each array item is recursively converted using the rules described here.
So:
VALUES ($1) or VALUES ($1::TEXT[])should suffice.

Related

If i store index number fetched from db in variable & using in select from list by index, m getting err as expected string, int found-Robot Framework

enter image description here
select from list by index ${locator_var} ${inp_msge_type}
--getting error as expected string, int found
select from list by index ${locator_var} 7
-----not getting any error
${inp_msge_type}----contains 7 from DB query the result is stored in this variable, to avoid hard coding we need to do this
Is there any way to write
Do not add links to screenshots of code, or error messages, and format the code pieces accordingly - use the ` (tick) symbol to surround them.
The rant now behind us, your issue is that the keyword Select From List By Index expects the type of the index argument to be a string.
When you called it
Select From List By Index ${locator_var} 7
, that "7" is actually a string (though it looks like a number), because this is what the framework defaults to on any typed text. And so it works.
When you get the value from the DB, it is of the type that the DB stores it with; and probably the table schema says it is int. So now you pass an int to the keyword - and it fails.
The fix is simple - just cast (convert) the variable to a string type:
${inp_msge_type}= Convert To String ${inp_msge_type}
, and now you can call the keyword as you did before.

get list of collections having all words exists in field which added in given string in mongoDB

I want to search list of collections from mongoDB have all the keywords of given string.
For e.g.
I have a collection
{
"id":1
"text":"go for shopping",
"description":"you can visit this branch as well"
}
{
"id":2
"text":"check exiting discount",
"description":"We have various discount options"
}
Now, If I will pass string like "I want to go for shopping" w.r.t. text field in find query of mongoDB. Then I should get first collection as output because text field value "go for shopping" exists in the input string passed in find query.
This can be achieved through $text operator in MongoDB. But you have to createIndex on the "text" field in your database.(or whichever filed you want to be matched, I would suggest you rename it in your db to avoid confusion)
db.yourCollectionName.createIndex({"text":"text"})
The first field here is the "text" field in your database, and the second one is the mongo operator.
Then you can pass any query like,
db.yourCollectionName.find({$text: {$search: "I want to go for shopping"}})
The "$text" here is the mongo operator.
This would return all documents which have any of the keywords above.
Maybe you can read more around this and improvise and modify.
Ref: MongoDb $text
You can do so through regular expression. MongoDb provides the provision of matching strings through regex patterns.
In your case you could do something like:
db.yourCollectionName.find({text:{$regex:"go for shopping" }})
This will return you all the documents having the phrase "go for shopping" in the text field.
Ref: MongoDb Regex

Elasticsearch: How to get the length of a string field(before analysis)?

My index has a string field containing a variable length random id. Obviously it shouldn't be analysed.
But I don't know much about elasticsearch especially when I created the index.
Today I tried a lot to filter documents based on the length of id, finally I got this groovy script:
doc['myfield'].values.size()
or
doc['myfield'].value.size()
both returns mysterious numbers, I think that's because of the field got analysed.
If it's really the case, is there any way to get the original length or fix the problem, without rebuild the whole index?
Use _source instead of doc. That's using the source of the document, meaning the initial indexed text:
_source['myfield'].value.size()
If possible, try to re-index the documents to:
use doc[field] on a not-analyzed version of that field
even better, find out the size of the field before you index the document and consider adding its size as a regular field in the document itself
Elasticsearch stores a string as tokenized in the data structure ( Field data cache )where we have script access to.
So assuming that your field is not not_analyzed , doc['field'].values will look like this
"In america" => [ "in" , "america" ]
Hence what you get from doc['field'].values is a array and not a string.
Now the story doesn't change even if you have a single token or have the field as not_analyzed.
"america" => [ "america" ]
Now to see the size of the first token , you can use the following request
{
"script_fields": {
"test1": {
"script": "doc['field'].values[0].size()"
}
}
}

Multi-value fields only store last value

I'm relatively new to ELK and grok. I'm trying to parse a log file that may contain 1 or more repetitions of the same value. For example the log file could contain:
value1;value2;value3;
value1;
value1;value2;value3;value4;........value900;
For this example, I'm using the following grok pattern:
((?[a-z0-9]*)[;])+
This appears to work properly, and parse each value. The problem is that the "tag" field only contains the last value (ie value900). All of the previous values seem to be overwritten.
Is there a way to gather all of the values and store them into an array instead of only getting the last value?
Simply use mutate:
mutate {
split => ["tag",";"]
}
This will split the value that's in the tag field into an array. So just match the whole string in your grok ((?<tag>[a-z0-9;]+) and then split it from there.

How to create a search query for partial string matches in Mongoose?

I'm new to Mongoose.js and I'm wondering how to create a simple Mongoose query that returns values containing the characters in the order that they were submitted.
This will be for an autocomplete form which needs to return cities with names that contain characters input into the search field. Should I start with a .where query?
You could find by regexp, which should allow you to search in a flexible (although not extremely fast) way. The code would be something similar to;
var input = 'ln'; // the input from your auto-complete box
cities.find({name: new RegExp(input, "i")}, function(err, docs) {
...
});
Of course, you could preprocess the string to make it match from the start (prepend by ^), from the end (append by $) etc. Just note that matching against arbitrary parts of long strings may be slow.

Resources