When to use N1QL

Is there anywhere some articles which discusses when to use N1QL vs sdk function. For example I can call a N1QL query in nodeJS to create a new doc or I can do an bucket.insert. Both will create my doc. Is there plans to move to N1QL overtime all together or is there any drawbacks using one vs the other. Just want to make sure I use the correct Methode.

1 Like

Hi @makeawish. Great question! It’s something we’ve been seeing a lot of in the forums lately, where Couchbase users are defaulting to N1QL and not being sure when to use the key-value (KV) SDK. So no, to be clear, while N1QL is awesome we have no plans to move everything to it, and using the KV SDK is an essential component of writing a really performant app. You’ll probably want to use both N1QL and KV together.

Whenever you’re doing an operation with a single doc where you know the key, e.g. inserting a new one, or getting a doc, I’d always use the KV SDK. It’s simply going to be faster. The client can go directly to the correct Couchbase node, there’s no overhead of parsing the N1QL query, and it’s using the highly efficient memcached protocol. It’s hard to quantify the exact speed difference you’ll see using KV vs N1QL for single doc ops, I could throw out some numbers but it’s dependent on your own cluster topology, network, hardware, etc. and you may want to test. Plus, arguably, some complex document manipulations are easier to achieve with KV than N1QL, and you have the option of efficient sub-document operations.

N1QL is fantastic for multi-doc queries, of course, or single-doc queries where you don’t know the key.

For multi-doc updates, it depends. In some cases you may know the keys of the docs you want to update, in which case KV would very likely be faster: the client can fanout the queries directly to the required nodes, and there’s no parsing overhead. It’d be worth testing both approaches. If you don’t know the keys, then N1QL is the way to go.

I hope that’s given a starting point for when you’d use which API. It’s not the whole story, and if you’re interested then my colleague @daschl has an excellent presentation on’Picking the right API for the right job’ at Connect 2016 that’s a great deep dive on this topic, and outlines some advanced techniques mixing the two APIs together.

5 Likes