Jainendra
Jainendra

Reputation: 25153

How to extract all keys with a prefix in Couchbase

I want to delete all the documents with a prefix. For example, all the documents with documentIds starting with name lets say Identifier1.

I've found this article which does this using NodeJS. I'm not able to convert this code to equivalent C# code.

Upvotes: 2

Views: 992

Answers (2)

David Ostrovsky
David Ostrovsky

Reputation: 2481

If you're using Couchbase 4.x, then in addition to what Simon suggested in his answer, you can use N1QL to delete documents with a simple query.

First, if you haven't used N1QL before, make sure you have a primary index on the bucket by running the following query once:

CREATE PRIMARY INDEX ON <bucket> USING GSI;

You can use the command-line query tool (located in /opt/couchbase/bin/cbq) or, if using Couchbase 4.5+, the Query Workbench in the UI.

Then, to delete all document by an ID prefix, use the following command:

DELETE FROM <bucket> WHERE meta().id LIKE '<prefix>%';

Again, you can use the command-line tool, the Query Workbench, or do this programmatically, which will look something like the following in C#:

var result = await bucket.QueryAsync("<query>");

Upvotes: 2

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28351

In C# the range is expressed as a StartKey and EndKey.

First on the server side the view must be created and published to production:

function(doc, meta) {
    emit(meta.id, null);
}

Then on the client side use a ViewQuery object with a StartKey and EndKey:

var prefix = "pre_"; //this should be a parameter of your method
var query = ViewQuery.From("designDocumentName", "viewName");
query.StartKey(prefix);
query.EndKey(prefix + "\u0000");

Then execute the query using the Bucket's Query(ViewQuery) method.

Upvotes: 1

Related Questions