How to update a specific field in all the documents of a bucket using Couchbase UI - couchbase

I have a bucket in couchbase which has many documents for example
{
"id":"1",
"isAvailable": false
},
{
"id":"2",
"isAvailable": false
},
{
"id":"3",
"isAvailable": true
},
{
"id":"4"
}
Now I want to iterate through all the document in this bucket and check if this document has isAvailable: false.
If yes then I need to update that document's isAvailable: true.
All this I want to do is from the couchbase UI

I think an UPDATE statement would work for you.
Something like:
UPDATE mybucket SET isAvailable = true
"check if this document has isAvailable: false" I don't think you don't need to check if isAvailable is false, since you're just setting all of the isAvailable to true.
If you want to just verify that isAvailable is actually in the document (no matter what its value is), you can do something like this:
UPDATE mybucket
SET isAvailable = true
WHERE isAvailable IS NOT MISSING

Index Selection is based on WHERE clause and mutation of the document is controlled by WHERE clause. If no WHERE clause all the documents are mutated. Mutations full document update and expensive. Do mutation when needed by supply the where clause (If you repeat the statement due to CAS error will not update all of them again)
CREATE INDEX ix1 ON mybucket(isAvailable);
UPDATE mybucket AS b
SET b.isAvailable = true
WHERE b.isAvailable = false;

Related

Postgresql: How to get value in JSON where key LIKE?

I have a column in my table containing a JSON statuses_json:
{
"demoStatus" : "true",
"productionStatus": "false"
}
I would like to retrieve a value where the key is LIKE some string.
For example, if I pass in "demo", I want to retrieve the value for the key demoStatus.
Right now I am able to retrieve values when passing the exact key:
`statuses_json->>'productionStatus' = 'false' `;
Extract the keys and run a query on it:
select *
from json_object_keys('{
"demoStatus" : "true",
"productionStatus": "false"
}') k where k like '%demo%';
I don't have a new enough version of postgresql but jsonb_path_query looks interesting, too. Then used statuses_json->>(...) to extract the corresponding value(s).
select statuses_json from your_table
where statuses_json->>(
select prop
from json_object_keys(statuses_json) as prop
where prop like 'demo%'
) = 'false';

Check if a value exists in a json file with python

I've the following json file (banneds.json):
{
"players": [
{
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/07/07aa315f664efa92456569429230bc2c254c3ff8_full.jpg",
"created": 1595050663,
"created_by": "<#128152620136267776>",
"nick": "teste",
"steam64": 76561198046619692
},
{
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/21/21fa5c468597e9c890212b2e3bdb0fac781c040c_full.jpg",
"created": 1595056420,
"created_by": "<#128152620136267776>",
"nick": "ingridão",
"steam64": 76561199058918551
}
]
}
And I want to insert new values if the new value (inserted by user) is not already in the json, however when I try to search if the value is already there I receive a false value, an example of what I'm doing ( not the original code, only an example ):
import json
check = 76561198046619692
with open('banneds.json', 'r') as file:
data = json.load(file)
if check in data:
print(True)
else:
print(False)
I'm always receiving the "False" result, but the value is there, someone can give me a light of what I'm doing wrong please? I tried the entire night to find a solution, but no one works :(
Thanks for the help!
You are checking data as a dictionary object. When checking using if check in data it checks if data object have a key matching the value of the check variable (data.keys() to list all keys).
One easy way would be to use if check in data["players"].__str__() which will convert value to a string and search for the match.
If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values. Another solution would be to make list of "steam64" values for faster and easier checking.
You can use any() to check if value of steam64 key is there.
For example:
import json
def check_value(data, val):
return any(player['steam64']==val for player in data['players'])
with open('banneds.json', 'r') as f_in:
data = json.load(f_in)
print(check_value(data, 76561198046619692))
Prints:
True

Update multiple elements of a list using Couchbase N1QL

context
I have somewhere in my couchbase documents, a node looking like this :
"metadata": {
"configurations": {
"AU": {
"enabled": false,
"order": 2147483647
},
"BE": {
"enabled": false,
"order": 2147483647
},
"BG": {
"enabled": false,
"order": 2147483647
} ...
}
}
and it goes along with a list country unicodes and their "enabled" state
what I want to achieve
update this document to mark is as disabled ("enabled" = false) for all countries
to do this I hoped this syntax would work (let's say I'm trying to update document with id 03c53a2d-6208-4a35-b9ec-f61e74d81dab)
UPDATE `data` t
SET country.enabled = false
FOR country IN t.metadata.configurations END
where meta(t).id = "03c53a2d-6208-4a35-b9ec-f61e74d81dab";
but it seems like it doesn't change anything on my document
any hints ? :)
thanks guys,
As the filed name is dynamic you can generate field names using OBJECT_NAMES() and use that during update of field.
UPDATE data t USE KEYS "03c53a2d-6208-4a35-b9ec-f61e74d81dab"
SET t.metadata.configurations.[v].enabled = false FOR v IN OBJECT_NAMES(t.metadata.configurations) END ;
In above example OBJECT_NAMES(t.metadata.configurations) generates ["AU", "BE","BG"]
When field of JSON is referenced .[v] it evaluates v and value become field.
So During looping construct t.metadata.configurations.[v].enabled becomes
t.metadata.configurations.`AU`.enabled,
t.metadata.configurations.`BE`.enabled,
t.metadata.configurations.`BG`.enabled
Depends on value of v.
This query should work:
update data
use keys "03c53a2d-6208-4a35-b9ec-f61e74d81dab"
set country.enabled = true for country within metadata.configurations when
country.enabled is defined end
The WITHIN allows "country" to be found at any level of the metadata.configurations structure, and we use the "WHEN country.enabled IS DEFINED" to make sure we are looking at the correct type of "country" structure.

Cursor-based Pagination in Facebook's Graph API

according to graphApi's documentation :
Cursor-based Pagination
Cursor-based pagination is the most efficient method of paging and should always be used where possible. A
cursor refers to a random string of characters which marks a specific
item in a list of data. Unless this item is deleted, the cursor will
always point to the same part of the list, but is be invalidated if an
item is removed. Therefore, your app shouldn't store any older cursors
or assume that they will still be valid.
When reading an edge that supports cursor pagination, you will see the
following JSON response:
{
"data": [
... Endpoint data is here
],
"paging": {
"cursors": {
"after": "MTAxNTExOTQ1MjAwNzI5NDE=",
"before": "NDMyNzQyODI3OTQw"
},
"previous": "https://graph.facebook.com/me/albums?limit=25&before=NDMyNzQyODI3OTQw"
"next": "https://graph.facebook.com/me/albums?limit=25&after=MTAxNTExOTQ1MjAwNzI5NDE="
}
}
but i have no idea what's going on up here, anyone can point me on how we do Cursor-based Pagination here? i've done similar thing by passing the Max_id but in here its not the case
this is how i'm making my first call
accessKey = "\(appID)|\(appSecret)"
let connection = GraphRequestConnection()
let request = GraphRequest.init(graphPath:"/myPageName/posts", parameters: [ "access_token" : accessKey, "fields" : "message,full_picture,created_time,story,type,permalink_url" , "limit": "10"], accessToken: nil, httpMethod: .GET, apiVersion: "2.8")
connection.add(request) { httpResponse, result in
switch result {
case .success(let response):
//FETCHED DATA HERE///
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()
(Posted on behalf of the OP).
Passing offset in parameter did the job.
For this lets first understand Cursor paging with an example :
Let’s assume we want to paginate from the most recent user to the oldest user.When client request for the first time , suppose we select the first page through query:
SELECT * FROM users
WHERE team_id = %team_id
ORDER BY id DESC
LIMIT %limit
Where limit is equal to limit plus one, to fetch one more result than the count specified by the client. The extra result isn’t returned in the result set, but we use the ID of the value as the next_cursor.
The response from the server would be:
{
"users": [...],
"next_cursor": "1234", # the user id of the extra result
}
The client would then provide next_cursor as cursor in the second request.
SELECT * FROM users
WHERE team_id = %team_id
AND id <= %cursor
ORDER BY id DESC
LIMIT %limit
Coming back to Facebook Implementation : As the name suggests the next cursor will fetch you the next set of results and the previous cursor will fetch you the previous set of results.
If you still have problem understanding Cursors and why they are used you can check out this article. The above example is quoted from the same.

Iterating through couchbase keys without a view

In couchbase, I was wondering if there was a way - WITHOUT using a view - to iterate through database keys. The admin interface appears to do this, but maybe its doing something special. What I'd like to is make a call like this to retrieve an array of keys:
$result = $cb->get("KEY_ALBERT", "KEY_FRED");
having the result be an array [KEY_ALEX, KEY_BOB, KEY_DOGBERT]
Again, I don't want to use a view unless there's no alternative. Doesn't look like its possible, but since the "view documents" in the admin appears to do this, I thought i'd double-check. I'm using the php interface if that matters.
Based on your comments, the only way is to create a simple view that emit only the id as par of the key:
function(doc, meta) {
emit( meta.id );
}
With this view you will be able to create query with the various options you need :
- pagination, range, ...
Note: you talk about the Administration Console, the console use an "internal view" that is similar to what I have written above (but not optimized)
I don't know about how couchbase admin works, but there are two options. First option is to store your docs as linked list, one doc have property (key) that points to another doc.
docs = [
{
id: "doc_C",
data: "somedata",
prev: "doc_B",
next: "doc_D"
},
{
id: "doc_D",
data: "somedata",
prev: "doc_C",
next: "doc_E"
}
]
The second approach is to use sequential id. You should have one doc that contain sequence and increment it on each add. It would be something like this:
docs = [
{
id: "doc_1",
data: "somedata"
},
{
id: "doc_2",
data: "somedata"
}
...
]
In this way you can do "range requests". To do this you form array of keys on server side:
[doc_1, doc_2 .... doc_N]and execute multiget query. Here is also a link to another example
The couchbase PHP sdk does support multiget requests. For a list of keys it will return an array of documents.
getMulti(array $ids, array $cas, int $flags) : array
http://www.couchbase.com/autodocs/couchbase-php-client-1.1.5/classes/Couchbase.html#method_getMulti