Translate N1QL Query to Java SDK


I’m using couchbase 6.5.1 and java sdk 2.7.1
I have compare speed between using N1QL and SDK, it’s much faster using SDK
(N1QL insert vs SDK upsert)
I have merge query below:

MERGE INTO myBucket AS target
{ “name”:“test”}
] AS source
ON key “TEST::1”
} )
returning target.*;

Is it possible change this N1QL to SDK version?


As you already have key,
Get the document.
If present update with cas else insert

Thanks @vsr1 for your quick response

So there’s no direct function for merge using sdk?

Do you have java sample code for that update cas?Is it the same as mutateIn?


update (SDK replace), MERGE is SQL statement (no SDK operations)

1 Like

how about ARRAY DISTINCT, is it applicable using KV or sdk? @vsr1

All these are N1QL syntax

Hi @vsr1,

I have implemented that logic but now having concurrent sequence issue.

My sample data is: (a,b,c,d,e) using same doc id

My CAS logic is when getting CASMismatchException, I will do sleep for 1 sec then retry.

When I tried to run the code, it saves all the data but the sequence is wrong (a,c,e,d,b)

The problem is that I need the data sequential

If I change the method to sync it can solve the sequential problem, but the performance is not as fast as async.

Do you have any insights for this?


not sure what do u mean by sequence is it array

let say i have 5 concurrent message in kafka to be processed with sequence inside doc :
{ “seq”:”a” ,… } { “seq”:”b” ,…} { “seq”:”c” ,…} { “seq”:”d”,…} { “seq”:”e”,…}
this will be appended into 1 couchbase doc id with expected result:

{ [{“seq”:”a”}, {“seq”:”b”},…e ]}

If you are using SUBDOC array insert ot array append will not work.
You need to get whole array and construct by inserting right order and write . If cas miss match you need to repeat.

or take array and sort in seq use it