I have a posgresql database, table has a column which is an array: Sequelize.ARRAY(Sequelize.BIGINT).
What is the right way to append a new item to the array?
I am new to posgresql, sequelize and nodejs. May be it is a trivial question.
From reading around I think I know how to use Promise.all to read all rows, append, and update back.
The question, isn't there any useful shortcut.
PostreSQL documentation mentions a function array_append(anyarray, anyelement).
Sequelize documentation offers a function fn, which Creates an object representing a database function, but only seems to be working in where and order parts
Any way to combine those for an append-like update?
Array Datatype has many methods like append, concat etc. which you can see here. I will give an example with array_append function.
Room is a sequelize model and job_ids is a column in this model with datatype as Array of integer. sequelize is an instant of Sequelize class.
Room.update(
{'job_ids': sequelize.fn('array_append', sequelize.col('job_ids'), new_jobId)},
{'where': {'id': roomId}}
);
Assuming default value of this column is an empty array else it may throw an error.
Related
I want to query the url in a field value like this:
["{\"Success\":null,\"Fail\":null,\"Url\":\"http://www.baidu.com\",\"Method\":\"Post\",\"Data\":\"\",\"ContentType\":\"application/json\",\"Timeout\":120000,\"DelayFromMinutes\":15,\"Cron\":\"33 10 3/6 * * ?\",\"JobName\":\"Test#asyncOrder\",\"QueueName\":\"recurring\",\"AgentClass\":null,\"SendSuccess\":false,\"SendFail\":true,\"Mail\":\"xxxxxx#qq.com\",\"EnableRetry\":true,\"RetryDelaysInSeconds\":null,\"RetryTimes\":0,\"BasicUserName\":null,\"BasicPassword\":null,\"Headers\":{},\"CallbackEL\":null,\"TimeZone\":null,\"DingTalk\":null}","\"Test#asyncOrder\"","\"recurring\"","true",null]
What should I do?
I think I need some further clarification on this.
Are you trying to pass the entire json object into the query as an array of key-value pairs?
If so, do you want that pass to be all one string--commas, colons and everything?
OR are you passing the value for each key into its own parameter in the query?
In any event, I would likely want to utilize STRING_ESCAPE:
... WHERE Thing = STRING_ESCAPE(#Thing, 'json') ...
I'm using postgresql database which allows having an array datatype, in addition django provides PostgreSQL specific model fields for that.
My question is how can I filter objects based on the last element of the array?
class Example(models.Model):
tags = ArrayField(models.CharField(...))
example = Example.objects.create(tags=['tag1', 'tag2', 'tag3']
example_tag3 = Example.objects.filter(tags__2='tag3')
I want to filter but don't know what is the size of the tags. Is there any dynamic filtering something like:
example_tag3 = Example.objects.filter(tags__last='tag3')
I don't think there is a way to do that without "killing the performance" other than using raw SQL (see this). But you should avoid doing things like this, from the doc:
Tip: Arrays are not sets; searching for specific array elements can be
a sign of database misdesign. Consider using a separate table with a
row for each item that would be an array element. This will be easier
to search, and is likely to scale better for a large number of
elements.
Adding to the above answer and comment, if changing the table structure isn't an option, you may filter your query based on the first element in an array by using field__0:
example_tag3 = Example.objects.filter(tags__0='tag1')
However, I don't see a way to access the last element directly in the documentation.
I have a requirement where the records will be sorted based on created date first and if created dates are same, we will sort on another field called as ratings.
In my Spring mongo project I am doing the following thing:
Query query = new Query();
query.with(new Sort(Direction.DESC, "crDate")).with(new Sort(Direction.DESC, "ratings"));
For some reasons its only sorting on the first field ie crDate. And if both dates are same, sort by ratings never work.
When i try to check the value of sort object it shows me this:
{"crDate":-1,"ratings":-1}
Another finding is, mongo takes in the following syntax for compound sorts:
db.abc.find({..some criteria..}).sort([["crDate",-1],["ratings",-1]]);
Is this a bug in spring mongodb implementation or I missed something?
Looking at the Spring API Documentation it shows you can specify multiple strings to the sort object you are creating in a list. From you snippet above I would suggest you need to only apply the one sort object that takes the two fields, something like
query.with(new Sort(Direction.DESC, Arrays.asList("crDate", "ratings")));
There was another constructor that took the List of Order objects. Strange but I tried it with that now and it seems to be working.
I am now using a single with clause and passing in a List of Order
I am trying a case where we changed a field name in our entity. we have something like this for example
class Person {
String name; //The original declaration was "String fullName"
}
According to objectify you have to use annonation #AutoLoad(""). This is ok and it works as Google Datastore doesn't delete the data Actually but it makes a new field so this annotation is like a mapping between the old and the new field. No problem when you are reading the whole table.
The problem arises when you apply a filter on your query (Suppose you made 5 objects with old name and 5 with new name). The result of your query depends on whether you used the old variable name or the new one (returns back only 5 but never the 10). It won't fetch both of them and map them. Any Suggestions for this problem? I hope i explained it in a clear way.
Thanks in advance
The simplest straight forward solution. fetch all data with the annonation "AutoLoad()". Then store them again. In this way they will be saved as the new field. The old one doesn't exist anymore or at least it doesn't contain any data anymore. It is like migrating the data from the old name to the new name. Anyone has better suggestions ?
If you've changed the name of your field, you need to load and re-put all your data (using the mapreduce API would be one option here). There's no magic way around this - the data you've stored exists with two different names on disk.
You can use #OldName
http://www.mail-archive.com/google-appengine-java#googlegroups.com/msg05586.html
1) Finding by instance object
Assuming I have the instance object called #topic. I want to retrieve the answers for this given topic. I was thinking I should be able to pass in :topics=>#topic, but i had to do the very ugly query below.
#answers = Answers.where(:topic_ids => {"$in" => [#topic.id]})
2) Getting the string representation of the id. I have a custom function (shown below). But shouldn't this be a very common requirement?
def sid
return id.to_s
end
If your associations are set up correctly, you should be able to do:
#topic.answers
It sounds like the above is what you are looking for. Make sure you have set up your associations correctly. Mongoid is very forgiving when defining associations, so it can seem that they are set up right when there is in fact a problem like mismatched names in references_many and referenced_in.
If there's a good reason why the above doesn't work and you have to use a query, you can use this simple query:
#answers = Answer.where(:topic_ids => #topic.id)
This will match any Answer record whose topic_ids include the supplied ID. The syntax is the same for array fields as for single-value fields like Answer.where(:title => 'Foo'). MongoDB will interpret the query differently depending on whether the field is an array (check if supplied value is in the array) or a single value (check if the supplied value is a match).
Here's a little more info on how MongoDB handles array queries:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray