Modify and delete document in Cloudant IBM Database - database

Is it possible to modify document or delete in Cloudant Database by query?

I assume the questioner is looking for equivalent functionality to SQL's:
UPDATE db SET x = 10 WHERE y > 100;
If that is the question then the answer is that Cloudant does not have such functionality, only an atomic update operation.
The equivalent of the UPDATE statement could be achieved by combining a call to the Cloudant Query API and making updates using the bulk API.
Another option is to use the couchtato iterator tool which allows bulk changes to be made to Cloudant databases.

To delete a document you have to know the document _id, if you do not know the _id then you have to look for the document in your db, retrieve it and then get the _id.
To retrieve a document you can use a selector. For example, let's say that you have a document that contains a "name" field, your selector would be something like
selector = {"name": {"$eq": "name that you want"}}
So for python code you would have something like
def retrieve_db_data(db_name, selector):
client = connect_to_db()
db = client[db_name]
results = db.get_query_result(selector)
data = results.all()
return data
In "data" you will have the _id
then you can use something like this to delete the data
def delete_document(db_name, doc_id):
client = connect_to_db()
client.connect()
db = client[db_name]
document = db[doc_id]
document.delete()

Related

Querying Firestore without Primary Key

I'd like my users to be able to update the slug on the URL, like so:
url.co/username/projectname
I could use the primary key but unfortunately Firestore does not allow any modifcation on assigned uid once set so I created a unique slug field.
Example of structure:
projects: {
P10syfRWpT32fsceMKEm6X332Yt2: {
slug: "majestic-slug",
...
},
K41syfeMKEmpT72fcseMlEm6X337: {
slug: "beautiful-slug",
...
},
}
A way to modify the slug would be to delete and copy the data on a new document, doing this becomes complicated as I have subcollections attached to the document.
I'm aware I can query by document key like so:
var doc = db.collection("projects");
var query = doc.where("slug", "==", "beautiful-slug").limit(1).get();
Here comes the questions.
Wouldn't this be highly impractical as if I have more than +1000 docs in my database, each time I will have to call a project (url.co/username/projectname) wouldn't it cost +1000 reads as it has to query through all the documents? If yes, what would be the correct way?
As stated in this answer on StackOverflow: https://stackoverflow.com/a/49725001/7846567, only the document returned by a query is counted as a read operation.
Now for your special case:
doc.where("slug", "==", "beautiful-slug").limit(1).get();
This will indeed result in a lot of read operations on the Firestore server until it finds the correct document. But by using limit(1) you will only receive a single document, this way only a single read operation is counted against your limits.
Using the where() function is the correct and recommended approach to your problem.

How to get result based on specific keywords using Google App Engine NO-SQL datastore query in java?

We use GoogleInfo table, in that table, we store scopes of application. e.g."https://www.googleapis.com/auth/drive.appdata,https://www.googleapis.com/auth/drive.file"
and I am trying to get a result based on some keyword like "drive" from scopes, based on that keyword I am trying to get a result. following is my code. Please suggest.
String keywords[] = {"admin","drive","gmail","userinfo"};
Query query = pm.newQuery("SELECT scopes FROM com.cloudcodes.gcontrol.dataaccesslayer.insights.google.drive.GoogleInfo where :p.contains(scopes)");
result = (List) query.execute(Arrays.asList(keywords));
List tempResult = new ArrayList();
tempResult.addAll(result);
return tempResult;
Seems that you are using JDO [1] and the PersistanceManager [2].
As far as I can see the query you are trying to execute might be wrong. Check how to perform queries with JDO [3].
Your query is:
String keywords[] = {"admin","drive","gmail","userinfo"};
Query query = pm.newQuery("SELECT scopes FROM com.cloudcodes.gcontrol.dataaccesslayer.insights.google.drive.GoogleInfo where :p.contains(scopes)");
result = (List) query.execute(Arrays.asList(keywords));
Looks like you want to do something like:
//Query for all persons with lastName equal to Smith or Jones
Query q = pm.newQuery(Person.class, ":p.contains(lastName)");
q.execute(Arrays.asList("Smith", "Jones"));
Person.class is the kind
Arrays.asList("Smith", "Jones")
This parameter ":p.contains(lastName)" that defines lastName is the property we want to check on.
You are setting the class as com.cloudcodes.gcontrol.dataaccesslayer.insights.google.drive.GoogleInfo, I suppose that this is the full Java name package where the class habits, and the class name is GoogleInfo. So you could try:
Query q = pm.newQuery(GoogleInfo.class, ":p.contains(scopes)");
q.execute(Arrays.asList("admin","drive","gmail","userinfo"));
You want to retrieve scopes. I assume that you want to use the REST API. So inside :p.contains(“scopes”) might go another property related to your keyWords that is in the Entity you want to retrieve, maybe an array property?
Here I share with you some docs that might be useful [4][5].
Hope this helps!
[1] https://cloud.google.com/appengine/docs/standard/java/datastore/jdo/overview-dn2
[2] http://massapi.com/method/javax/jdo/PersistenceManager.newQuery-4.html
[3] https://cloud.google.com/appengine/docs/standard/java/datastore/jdo/queries
[4] https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases
[5] https://cloud.google.com/datastore/docs/reference/gql_reference

How to search arrays for values in Google Cloud Datastore

Assuming we have an entity in Google Cloud Datastore - "Job" and it has some Access Control Tags:
["admin", "manager"]
and we have a user that has some Access Control Tags
["admin", "super_user"]
We would like to pull back all Jobs that this user has access to; e.g. in SQL something like
SELECT * from Job where tags INCLUDE "admin" OR tags INCLUDE "super_user"
OR queries are not supported, is there another way to achieve this?
Could you query the datastore model using ndb.OR? Something like in this example:
query = Article.query(ndb.AND(Article.tags == 'python',
ndb.OR(Article.tags.IN(['ruby', 'jruby']),
ndb.AND(Article.tags == 'php',
Article.tags != 'perl'))))
You can query to retrieve multiple values like the following:
If you have array of multiple datastore Id's like following:
[1,2,3,4]
You can query with gstore-node Package
var userData = await UserModel.get([1,2,3,4]);
Hope this will help you.
Thanks
For that you need to store the data in array format in google cloud datastore. in here we can't use OR condition. so you can use > and < for equlity and also you can use the add_filter for that

Can I query by document id with full text search on App Engine?

After creating a document with a explicit id like this:
Document(doc_id = 123)
Is it possible to find that document using the id, similar to get_by_id with the Datastore?
I've tried queries with id:123, _id:123, doc_id:123, and _doc_id:123.
Index.list_documents has the options start_doc_id and limit which can be used to get a single document by id.
documents = index.list_documents(start_doc_id = id, limit = 1)
I also found in Java that you can do index.get(ID), which might be useful for Java users.
Here's the Javadoc:
https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/search/Index#get(java.lang.String)

How To Use Entity Groups And Ancestors with DjangoForms

I would like to rewrite the example from the GAE djangoforms article to be show most up to date after submitting a form (e.g. when updating or adding a new entry) on Google App Engine using the High Replication Datastore.
The main recurring query in this article is:
query = db.GqlQuery("SELECT * FROM Item ORDER BY name")
which we will translate to:
query = Item.all().order('name') // datastore request
This query I would like to get the latest updated data from the high replication datastore after submitting the form (only in these occasions, I assume I can redirect to a specific urls after submission which just uses the query for the latest data and in all other cases I would not do this).
validating the form storing the results happens like:
data = ItemForm(data=self.request.POST)
if data.is_valid():
# Save the data, and redirect to the view page
entity = data.save(commit=False)
entity.added_by = users.get_current_user()
entity.put() // datastore request
and getting the latest entry from the datastore for populating a form (for editing) happens like:
id = int(self.request.get('id'))
item = Item.get(db.Key.from_path('Item', id)) // datastore request
data = ItemForm(data=self.request.POST, instance=item)
So how do I add entity groups/ancestor keys to these datastore queries to reflect the latest data after form submission. Please note, I don't want all queries to have the latest data, when populating a form (for editing) and after submitting a form.
Who can help me with practical code examples?
If it is in the same block, you have reference of the current intance.
Then once you put() it, you can get its id by:
if data.is_valid():
entity = data.save(commit=False)
entity.added_by = users.get_current_user()
entity.put()
id= entity.key().id() #this gives you inserted data id

Resources