I’ve recently learned about the RETURNING keyword in N1QL. When you add it to end of a N1QL query, that query will return the result set that was operated on. For instance, if you use an UPDATE, and that query updates 10 documents, the RETURNING will then return those 10 documents.
You can use this within your .NET and .NET Core Couchbase applications.
Basic Setup
This blog post assumes that you have Couchbase Server setup locally, a bucket created called “default”, and at least a primary index created on that bucket.
Note: if you are having trouble getting started with Couchbase Server, or you are getting errors, especially in regards to N1QL indexing, you may want to revisit some of my “Getting Started” blog posts: Couchbase with Windows Part 1 and Couchbase with Windows Part 2 in particular.
I’m using a simple .NET Core console project, with the same tooling and setup that I used in my .NET Core with Visual Studio Code blog post.
Coding with .NET and N1QL
Most of this code should be pretty familiar if you’ve used .NET and Couchbase before. I’m creating 5 documents that have (initially) a processed field set to false
. The code below inserts them. It also writes them out to console for illustration purposes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
for(var i = 0;i < 5; i++) { var docKey = Guid.NewGuid().ToString(); var docContent = new { foo = "bar", type = "example", processed = false, dt = DateTime.Now }; var docContentJson = JsonConvert.SerializeObject(docContent); bucket.Insert(new Document { Id = docKey, Content = docContent }); Console.WriteLine($"Inserted: {docKey} - {docContentJson}"); } |
Next, this code immediately runs a N1QL UPDATE
to set all the processed
fields to true. It also has a RETURNING
statement at the end to return the documents as well as the keys.
1 2 3 4 5 6 7 8 |
var n1ql = @"UPDATE `default` d SET processed = true WHERE d.type = 'example' AND d.processed = false RETURNING d.*, META().id AS docKey"; var query = QueryRequest.Create(n1ql); query.ScanConsistency(ScanConsistency.RequestPlus); var results = bucket.Query(query); |
Finally, the following code prints out the returned JSON to console for illustration purposes.
1 2 3 4 |
foreach(var result in results.Rows) { var resultJson = JsonConvert.SerializeObject(result); Console.WriteLine($"Returned: {resultJson}"); } |
Running the program
To execute this program, simple enter dotnet run
at the console window. You should see an output like this:
Summary
The RETURNING
keyword can save you a step when updating/inserting a group of documents. Try experimenting with a more complex UPDATE
to see what happens. For example, try using IS MISSING
instead of relying on a boolean flag like ‘processed’.
If you have any questions, please leave a comment or contact me on Twitter.