You run your first SQL++ (N1QL) query on a new Couchbase bucket:
SELECT name, city FROM `travel-sample` WHERE type = "hotel" AND city = "Paris";
"code": 4000,
"msg": "No index available on keyspace `default`:`travel-sample` that matches your query.
Use CREATE PRIMARY INDEX ON `default`:`travel-sample` to create a primary index,
or check that your expected index is online."
The error suggests creating a primary index. That makes the error go away, and it's also the most common Couchbase performance mistake. Here's what to do instead.
How Couchbase queries find documents
Couchbase has two ways to read data:
- Key-value (KV) access by document ID:
get("hotel::1234"). It's the fastest possible path, served straight from the Data service's memory, and needs no index. - SQL++ queries, which go through the Query service and always need an index from the Index service (GSI) to find matching documents.
A primary index indexes every document key in the collection. A query that can only use it performs a primary scan: fetch every document and filter them. That's fine for 1,000 development documents, and a full scan on 50 million production ones.
Create secondary indexes that match your queries
Index the fields you filter on, equality fields first, then range or sort fields:
CREATE INDEX idx_hotel_city ON `travel-sample`(city, name)
WHERE type = "hotel";
- The
WHERE type = "hotel"clause makes it a partial index: smaller, and used only by queries that include that predicate.
