I'm trying to update an array inside a specific json document on a Couchbase Bucket.
Basically what I want to do is to insert a new object to the array.
When I try below query on the data Base itself, the query is working perfectly,
UPDATE BUCKETNAME SET appl[3]= {
'appl_ads_id': 'testtttt',
'appl_bnd_lvl_cd': 30,
'appl_desire_skill_tx': [
"couchbase",
"nodejs"
],
'appl_email_tx': "TESTING123#gmail.com",
'appl_full_nm': "TEST TESTING",
'appl_id': "4444",
'appl_ldr_apprvd': true,
'appl_locat_tx': "ALABAMA",
'appl_role_nm': "Engineer III",
'appl_status': "PENDING"}
where opp_id= 1 and opp_nm= "Couchbase Management Project" RETURNING *;
but when i try and write that query into my javascript code Im getting below error:
QueryErrorContext {
first_error_code: 3000,
first_error_message: 'syntax error - at '',
statement:
'UPDATE `BUCKETNAME` SET appl[3]= {'appl_ads_id': 'albm111', 'appl_bnd_lvl_cd': 30, 'appl_desire_skill_tx': ['couchbase', 'nodejs'],'appl_email_tx': 'zzzzzzz','appl_full_nm': 'z Z','appl_id': '222222','appl_ldr_apprvd': false, 'appl_locat_tx': 'ALABAMA','appl_role_nm': 'Engineer III','appl_status': 'Test'} where opp_id= $ID and opp_nm= $NAME RETURNING *;',
client_context_id: '54f4f683f306b4a5',
parameters: '',
http_response_code: 400,
http_response_body: '' } }
Please find below how I wrote the N1ql query on my nodejs code:
async function queryResults() {
const query = "UPDATE BUCKETNAME SET appl[3]= {'appl_ads_id': 'mfern685', 'appl_bnd_lvl_cd': 30, 'appl_desire_skill_tx': ['couchbase', 'nodejs'],'appl_email_tx': 'zzzzzzz','appl_full_nm': 'z Z','appl_id': '222222','appl_ldr_apprvd': false, 'appl_locat_tx': 'Sunrise','appl_role_nm': 'Engineer III','appl_status': 'Test'} where opp_id= $ID and opp_nm= $NAME RETURNING *;"
const options = { parameters: { ID: 1, NAME: 'Couchbase Management Project' } }
try {
let results = await cluster.query(query,options);
results.rows.forEach((row) => {
console.log('Query row: ', row)
})
return results
} catch (error) {
console.error('Query failed: ', error)
}
}
The second part of your query should use standard SQL syntax:
update my_bucket set myArray[3] = {teste: 'something'}, appl_email_tx = 'TESTING123#gmail.com';
Related
I have aerospike 6.0.0 installed on server and being used as cache. Also I am using Node.js client 5.2.0 to connect to the database.The aerospike nodes are configured to use TLS. The config of the namespace I am using is:
namespace application_cache {
memory-size 5G
replication-factor 2
default-ttl 1h
nsup-period 1h
high-water-memory-pct 80
stop-writes-pct 90
storage-engine memory
}
The config I am passing while connecting to the Db is:
"config": {
"captureStackTraces":true,
"connTimeoutMs": 10000,
"maxConnsPerNode": 1000,
"maxCommandsInQueue" : 300,
"maxCommandsInProcess" : 100,
"user": "test",
"password": "test",
"policies": {
"read": {
"maxRetries": 3,
"totalTimeout": 0,
"socketTimeout": 0
},
"write": {
"maxRetries": 3,
"totalTimeout": 0,
"socketTimeout": 0
},
"info": {
"timeout": 10000
}
},
"tls": {
"enable": true,
"cafile": "./certs/ca.crt",
"keyfile": "./certs/server.key",
"certfile": "./certs/server.crt"
},
"hosts": [
{
"addr": "-----.com",
"port": 4333,
"tlsname": "----"
},
{
"addr": "---.com",
"port": 4333,
"tlsname": "-----"
},
{
"addr": "----.com",
"port": 4333,
"tlsname": "-----"
}
]
}
This is the function I am using to write to a set in this namespace:
async function updateApp(appKey, bins) {
let result = {};
try {
const writePolicy = new Aerospike.WritePolicy({
maxRetries: 3,
socketTimeout: 0,
totalTimeout: 0,
exists: Aerospike.policy.exists.CREATE_OR_UPDATE,
key: Aerospike.policy.key.SEND
});
const key = new Aerospike.Key(namespace, set, appKey);
let meta = {
ttl: 3600
};
let bins = {};
result = await asc.put(key, bins, meta, writePolicy);
} catch (err) {
console.error("Aerospike Error:", JSON.stringify({params: {namespace, set, appKey}, err: {code: err.code, message: err.message}}));
return err;
}
return result;
}
It works most of the time but once in a while I get this error:
Aerospike Error: {"params":{"namespace":"application_cache","set":"apps","packageName":"com.test.application"},"err":{"code":-6,"message":"TLS write failed: -2 34D53CA5C4E0734F 10.57.49.180:4333"}}
Every record in this set has about 12-15 bins and the size of the record varies between 300Kb to 1.5Mb. The bigger the size of the record the higher chance of this error showing up. Has anyone faced this issue before and what could be causing this?
I answered this on the community forum but figured I'd add it here as well.
Looking at the server error codes a code: 6 is AS_ERR_BIN_EXISTS. Your write policy is setup with exists: Aerospike.policy.exists.CREATE_OR_UPDATE but the options for exists are:
Name
Description
IGNORE
Write the record, regardless of existence. (I.e. create or update.)
CREATE
Create a record, ONLY if it doesn't exist.
UPDATE
Update a record, ONLY if it exists.
REPLACE
Completely replace a record, ONLY if it exists.
CREATE_OR_REPLACE
Completely replace a record if it exists, otherwise create it.
My guess is that it's somehow defaulting to a CREATE only causing it to throw that error. Try updating your write policy to use exists: Aerospike.policy.exists.IGNORE and see if you still get that error.
I have created a function triggered by Azure Cosmos DB by following https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-function which is working.
Upon seeing logs, I am unable to identify if this trigger is for INSERT or UPDATE. I know that in AWS, when you add lambda as the dynamo trigger, you could identify that easily. You can even see what was original record vs updated one (for update)
Question:
How to identify INSERT vs UPDATE vs DELETE action?
I am new to Azure, so it is possible that I am missing something in my function code.
Function Code:
module.exports = async function (context, documents) {
context.log('1');
if (!!documents && documents.length > 0) {
context.log('Document Id: ', documents[0].id); <-- SHOWS ID OF THE RECORD
context.log('Document[0]', documents[0]); <-- ENTIRE RECORD
context.log('Documents', documents); <-- ALL RECORDS
}
}
context object from above:
{
invocationId: '3ee0136e-d005-4517-a11e-c43ec9ca7c67',
traceContext: {
traceparent: '00-4938136b13476845524c7ae5059d84f3-badfbc56b5ef0067-00',
tracestate: '',
attributes: {
OperationName: 'CosmosTrigger1'
}
},
executionContext: {
invocationId: '3ee0136e-d005-4517-a11e-c43ec9ca7c67',
functionName: 'CosmosTrigger1',
functionDirectory: 'C:\\home\\site\\wwwroot\\CosmosTrigger1',
retryContext: null
},
bindings: {
documents: [
[
Object
]
]
},
log: [
Function(anonymous)
]{
error: [
Function: error
],
warn: [
Function: warn
],
info: [
Function: info
],
verbose: [
Function: verbose
]
},
bindingData: {
invocationId: '3ee0136e-d005-4517-a11e-c43ec9ca7c67'
},
bindingDefinitions: [
{
name: 'documents',
type: 'cosmosDBTrigger',
direction: 'in'
}
],
done: [
Function(anonymous)
]
}
Function Log:
Unfortunately, you can't distinguish between the two types (insert & update). The trigger consumes the Change Feed, and you can't filter it for a specific type of operation.
Today, you see all inserts and updates in the change feed. You can't
filter the change feed for a specific type of operation.
Trying to set multiple values in CascadeChoiceParameter's for referencedParameters. What the format should be? Docs documentation said that it should be 'string', but in case of setting referencedParameters: 'param1,param2' it goes to fallback script.
here is the class:
[$class: 'CascadeChoiceParameter',
name: 'SOME_PARAM',
description: 'some description',
randomName: '',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["item_1"]'
],
script: [
classpath: [],
sandbox: true,
script: """
if(PARAM_2.equals("some_value") && PARAM_3.equals("some_value")) {
return ["item_1", "item_2", "item_3"]
} else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard")) {
return ["item_1", "item_2", "item_4"]
} else {
return ["item_1"]
}
""".stripIndent()
]
],
choiceType: 'PT_SINGLE_SELECT',
referencedParameters: 'PARAM_2,PARAM_3',
filterable: false,
filterLength: 1
],
The fallback script is used if/when there is any kind of exception/error when attempting to execute the main script. In your case, there is a compilation error in the else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard")) line. All the open parenthesis haven't been closed - there are 6 open parenthesis and only 5 close parenthesis. Anyway, I haven't tested a CascadeChoiceParameter version of the pipeline. I have tested using activeChoiceReactiveParam. Below is a working job DSL:
String choicesScript = """
if(PARAM_2.equals("some_value") && PARAM_3.equals("some_value")) {
return ["item_1", "item_2", "item_3"]
} else if((PARAM_2.equals("E2E_Tests") || (PARAM_2.equals("Real_API")) && PARAM_3.equals("knox_guard"))) {
return ["item_1", "item_2", "item_4"]
} else {
return ["item_5"]
}
""".stripIndent()
String pipeline = '''
pipeline {
agent any
stages {
stage('Show parameter values') {
steps {
echo "PARAM_2: ${params.PARAM_2}, PARAM_3: ${params.PARAM_3}, SOME_PARAM: ${params.SOME_PARAM}"
}
}
}
}
'''.stripIndent()
pipelineJob('reactive-params') {
parameters {
activeChoiceParam('PARAM_2') {
description('First test parameter')
choiceType('SINGLE_SELECT')
groovyScript {
script('return ["some_value", "E2E_Tests", "Real_API"]')
}
}
activeChoiceParam('PARAM_3') {
description('Second test parameter')
choiceType('SINGLE_SELECT')
groovyScript {
script('return ["some_value", "knox_guard"]')
}
}
activeChoiceReactiveParam('SOME_PARAM') {
description('some description')
choiceType('SINGLE_SELECT')
referencedParameter('PARAM_2')
referencedParameter('PARAM_3')
groovyScript {
script(choicesScript)
fallbackScript('return ["item_1"]')
}
}
}
definition {
cps {
script(pipeline)
}
}
}
I tried replacing the value for the key "Information" from the below JSON Object using the code
"itsmdata.incidentParamsJSON.IncidentContainerJson.replace("Information",option);"
but getting error as object is not defined (Attachment)
{
"ServiceName": "IM_LogOrUpdateIncident",
"objCommonParameters": {
"_ProxyDetails": {
"ProxyID": 0,
"ReturnType": "JSON",
"OrgID": 1,
"TokenID": null
},
"incidentParamsJSON": {
"IncidentContainerJson": "{\"SelectedAssets\":null,\"Ticket\":{\"Caller_EmailID\":null,\"Closure_Code_Name\":null,\"Description_Name\":\"Account Unlock\",\"Instance\":null},\"TicketInformation\":{\"Information\":\"account locked out\"},\"CustomFields\":null}"
},
"RequestType": "RemoteCall"
}
}
If you try to update properties of itsmdata you can try this
let str = itsmdata.objCommonParameters.incidentParamsJSON.IncidentContainerJson;
itsmdata.objCommonParameters.incidentParamsJSON.IncidentContainerJson = str.replace(/Information/gi, option);
I'm using node.js as my Server and have an account on Azure where my storage table resides. I'm retrieving all records for a specific partition by using the following :
var query= new azure.TableQuery().where('PartitionKey eq ?',username);
tableSvc.queryEntities(localTableName,query, null, function(error, result, response) {
}
When this call comes back, I want to access the values for the rest of the fields of table. But when I do that using result.entries, it kinda looks weird. Alternatively I think I can access the results via response.body.value.userID.
Here is how the structure of "result.entries" vs "response" object looks like:
result.entries :
[ { PartitionKey: { '$': 'Edm.String', _: '048tfbne' },
RowKey: { '$': 'Edm.String', _: '145610564488450166' },
Timestamp:
{ '$': 'Edm.DateTime',
_: Mon Feb 22 2016 01:47:26 GMT+0000 (UTC) },
username: { _: '048tfbne' },
userID: { _: '145610564488450166' },
deleteAfter: { _: 'not set yet' },
'.metadata': { etag: 'W/"datetime\'2016-02-22T01%3A47%3A26.4394133Z\'"' } } ]
response :
{ isSuccessful: true,
statusCode: 200,
body:
{ 'odata.metadata': 'https://photoshareuserdata.table.core.windows.net/$metadata#userIdentifier',
value:
[ { 'odata.etag': 'W/"datetime\'2016-02-22T01%3A47%3A26.4394133Z\'"',
PartitionKey: '048tfbne',
RowKey: '145610564488450166',
Timestamp: '2016-02-22T01:47:26.4394133Z',
username: '048tfbne',
userID: '145610564488450166',
deleteAfter: 'not set yet' } ] },
I thought results.entries would be a better way to access the records, but I am sort of weirded out by the nested objects and Edm.String here.
Which is a better way to access the records ?
Table Node Sample shows how to access entities in a table as result of a query. See method "runPageQuery".
Actually, according the official Section: Query a set of entities, there is a paragraph as following:
If successful, result.entries will contain an array of entities that match the query. If the query was unable to return all entities, result.continuationToken will be non-null and can be used as the third parameter of queryEntities to retrieve more results.
And we also can refer to the sample at Azure-storage-for-node repository on GitHub. Which has told us the answer.