In questo tutorial imparerai come connetterti a un cluster di Couchbase Capella per creare, leggere, aggiornare e cancellare documenti e come scrivere semplici query SQL++ parametrizzate.
Prerequisiti
Per eseguire questo progetto preconfigurato, avrete bisogno di:
- Couchbase Capella cluster with Travel-sample La carretta è carica.
- Per eseguire questo tutorial utilizzando un cluster di Couchbase gestito autonomamente, si prega di consultare la documentazione relativa al comando appendice.
- Java JDK installed.
- Ensure that the Java version is compatibile con il SDK di Couchbase.
- Code Editor installed (Vim, IntelliJ IDEA, Eclipse, or Visual Studio Code)
- Loading Travel Sample Bucket
- If travel-sample is not loaded in your Capella cluster, you can load it by following the instructions for your Capella Cluster:
Configurazione di Couchbase Capella
Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.
- L'applicazione richiede che il bucket dei campioni di viaggio sia caricato nel cluster della Capella UI.
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
Configurazione dell'applicazione
We will walk through the different steps required to get the application running.
Cloning Repo
git clone https://github.com/couchbase-examples/kotlin-quickstart.git
Installare le dipendenze
./gradlew build -x test
Dependency Injection via Couchbase Koin module
The quickstart code provides a Koin module that exports configuration, cluster, bucket and scope beans to the application.
// Creates a cluster bean
fun createCluster(configuration: CouchbaseConfiguration): Cluster {
return Cluster.connect(
connectionString = configuration.connectionString,
username = configuration.username,
password = configuration.password,
)
}
// Creates a bucket bean
@ExperimentalTime
fun createBucket(cluster: Cluster, configuration: CouchbaseConfiguration): Bucket {
val result : Bucket?
runBlocking {
result = cluster.bucket(configuration.bucket).waitUntilReady(10.seconds)
}
return result
}
// Creates a bucket scope bean
fun createScope(bucket: Bucket, configuration: CouchbaseConfiguration): Scope {
return bucket.scope(configuration.scope)
}
from
src/main/kotlin/com/couchbase/kotlin/quickstart/CouchbaseConfiguration.kt
Configured database objects like the bucket and scope must exist on the cluster prior to starting the application.
Configurazione della database di configurazione
Per saperne di più su come connettersi al cluster Capella, si prega di seguire le istruzioni riportate nella pagina dedicata. istruzioni.
In particolare, è necessario fare quanto segue:
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
All configuration for communication with the database is stored in the src/main/resources/application.conf file under the couchbase section:
couchbase {
connectionString = "couchbases://yourassignedhostname.cloud.couchbase.com"
username = "Administrator"
password = "password"
bucket = "travel-sample"
scope = "inventory"
}
Nota: La stringa di connessione prevede
couchbases://ocouchbase://parte.
This includes the connection string, username, password, bucket and scope names. The default username is assumed to be Administrator and the default password is assumed to be password.
If these are different in your environment you will need to change them before running the application.
Running The Application
Directly on Machine
In questo momento abbiamo installato le dipendenze, caricato i dati del travel-sample e configurato l'applicazione con le credenziali. L'applicazione è ora pronta e potete lanciarla.
./gradlew run
Usare Docker
- Creare l'immagine Docker
docker build -t couchbase-koltin-quickstart .
- Run the docker image
docker run -e DB_CONN_STR=<connection_string> -e DB_USERNAME=<user_with_read_write_permission_to_travel-sample_bucket> -e DB_PASSWORD=<password_for_user> -p 8080:8080 couchbase-koltin-quickstart
You can access the Application on http://0.0.0.0:8080
Verificare l'applicazione
Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

L'applicazione verrà eseguita sul port 8080 della macchina locale (http://0.0.0.0:8080). You will find the Swagger documentation of the API if you go to the URL in your browser. Swagger documentation is used in this demo to showcase the different API end points and how they can be invoked. More details on the Swagger documentation can be found in the appendice.

Modello dei dati
Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario che contengono rispettivamente aeroporti campione, compagnie aeree e rotte aeree. La raccolta di rotte collega gli aeroporti e le compagnie aeree come mostrato nella figura sottostante. Usiamo queste connessioni nel quickstart per generare aeroporti direttamente collegati e compagnie aeree che collegano un aeroporto di destinazione. Nota che questi sono solo esempi per evidenziare come è possibile utilizzare le query SQL++ per aggregare le collezioni.

Proviamo a rivedere il codice
Per iniziare questo tutorial, clonate il repo e apriamolo nell'IDE di vostra scelta. Ora potete imparare come creare, leggere, aggiornare e cancellare documenti in Couchbase Server.
Layout del codice
├── src
│ ├── main
│ │ ├── kotlin/com/couchbase/kotlin/quickstart
│ │ │ ├── models
│ │ │ │ ├── AirlineModel.kt
│ │ │ │ ├── AirportModel.kt
│ │ │ │ └── RouteModel.kt
│ │ │ ├── repositories
│ │ │ │ ├── AirlineRepository
│ │ │ │ ├── AirportRepository
│ │ │ │ └── RouteRepository
│ │ │ ├── routes
│ │ │ │ ├── AirlineRoutes.kt
│ │ │ │ ├── AirportRoutes.kt
│ │ │ │ └── RouteRoutes.kt
│ │ │ ├── services
│ │ │ │ ├── AirlineService
│ │ │ │ ├── AirportService
│ │ │ │ └── RouteService
│ │ │ ├── Application.kt
│ │ │ └── CouchbaseConfiguration.kt
│ │ └── resources
│ │ ├── application.conf
│ │ └── logback.xml
│ └── test/kotlin/com/couchbase
│ └── kotlin/quickstart
│ ├── AirlineTests
│ ├── AirportTests
│ └── RouteTests
├── build.gradle.kts
└── Dockerfile
Entità aeroportuale
For this tutorial, we will focus on the airport entity. The other entities are similar.
Stabiliremo un'API REST per gestire i documenti aeroportuali.
- Aeroporto POST – Creare un nuovo aeroporto
- GET Airport – Leggere l'aeroporto specificato
- Aeroporto di PUT – Aggiornamento aeroporto specificato
- DELETE Airport – Eliminare l'aeroporto
- Elenco degli aeroporti – Raccogliere tutti gli aeroporti. Opzionalmente è possibile filtrare l’elenco per paese
- Connessioni dirette – Ottieni una lista di aeroporti direttamente collegati all'aeroporto specificato
Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore che sono integrate nel Couchbase SDK per creare, leggere, aggiornare e cancellare un documento. Ogni documento avrà bisogno di un ID (simile a una chiave primaria in altre database) per essere salvato nel database. Questo ID viene passato nell'URL. Per gli altri endpoint, utilizzeremo SQL++ per richiedere documenti.
Struttura dei documenti dell'aeroporto
Our airport document will have an airportname, city, country, faa code, icao code, timezone info and the geographic coordinates. For this demo, we will store all airport information in one document in the aeroporto raccolta nel Travel-sample bucket.
{
"airportname": "Sample Airport",
"city": "Sample City",
"country": "United Kingdom",
"faa": "SAA",
"icao": "SAAA",
"tz": "Europe/Paris",
"geo": {
"lat": 48.864716,
"lon": 2.349014,
"alt": 92
}
}
Aeroporto POST
Apri AirportRoutes.kt file found in the src/main/kotlin/com/couchbase/kotlin/quickstart/routes folder.
This file contains all http routes defined in the API, which are grouped under the /api/v1/airport common route.
The first handler function allows API clients to create new airport by submitting a POST request with json-serialized airport.
The handler passes received airport data to createAirport method of application’s Airport service, defined in AirportService.kt which, in turn, delegates the request to AirportRepository::create method:
fun create(data: AirportModel, id: String): Airport {
val airport = Airport().apply {
airportname = data.airportname
city = data.city
country = data.country
faa = data.faa
geo = data.geo
icao = data.icao
tz = data.tz
}
runBlocking(databaseContext) {
collection.insert(id, airport)
}
return airport
}
from
AirportRepository.kt
The repository method creates a new Airport object with an id, populates it with received data and then uses SDK collection object to store the airport on the cluster.
Stored airport is then returned up the call stack and rendered as JSON in HTTP response body.
GET Airport
The GET handler returns airport object with requested ID. It delegates all work to the airport service, which uses the SDK to fetch the requested document from Couchbase’s key-value service:
fun getById(id: String): Airport {
var result: Airport
runBlocking(databaseContext) {
result = collection.get(id).contentAs()
}
return result
}
from
AirportRepository.kt
Aeroporto di PUT
The PUT handler additionally accepts an Airport object in the HTTP request body and then uses the SDK key-value operation to store it in Couchbase, overriding the previous airport data:
fun update(airport: Airport, id: String): Airport {
runBlocking(databaseContext) {
collection.replace(id, airport)
}
return airport
}
from
AirportRepository.kt
DELETE Airport
The DELETE handler, which accepts only an Airport identifier as the last part of the request URL, deletes corresponding airport documents from the cluster.
fun delete(id: String) {
runBlocking(databaseContext) {
collection.remove(id)
}
}
from
AirportRepository.kt
Lista aeroporti
Questo endpoint recupera l'elenco degli aeroporti presenti nel database. L'API offre la possibilità di specificare la dimensione della pagina dei risultati e il paese da cui estrarre i documenti relativi agli aeroporti.
SQL++ is a powerful query language based on SQL, but designed for structured and flexible JSON documents. We will use a SQL+ query to search for airports with Limit, Offset, and Country option.
Apri AirportRepository.kt file and navigate to the list method. This endpoint is different from the others we have seen before because it makes the SQL++ query rather than a key-value operation. This usually means more overhead because the query engine is involved. For this query, we are using the predefined indices in the Travel-sample bucket. Possiamo creare un altro indice specifico per questa query per renderla più efficiente.
We need to get the values from the query string for country, limit, and offset that we will use in our query.
Questo endpoint ha due query a seconda del valore del parametro Paese. Se viene specificato un nome di paese, recuperiamo i documenti relativi all’aeroporto per quel paese specifico. Se non viene specificato, recuperiamo l’elenco degli aeroporti di tutti i paesi. Le query sono leggermente diverse per questi due scenari.
Costruiamo la nostra query SQL++ utilizzando il parametri specificato da $ simbolo per entrambi questi scenari. La differenza tra le due query è la presenza del paese Il parametro nella query. Normalmente, per le query con la funzione di paginaazione, si consiglia di ordinare i risultati per mantenere l'ordine dei risultati in più query.
Successivamente passiamo oltre richiesta to the richiesta method of the Couchbase SDK. We save the results in a list form.
This endpoint calls the richiesta metodo definito nel Ambito di applicazione tramite il SDK di Couchbase.
fun list(country: String? = null, limit: Int = 10, offset: Int = 0): List<Airport> {
val lowerCountry = country?.lowercase()
val query = if (!lowerCountry.isNullOrEmpty()) {
"""
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
WHERE lower(airport.country) = '$lowerCountry'
ORDER BY airport.airportname
LIMIT $limit
OFFSET $offset
"""
} else {
"""
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
ORDER BY airport.airportname
LIMIT $limit
OFFSET $offset
"""
}
return runBlocking(databaseContext) {
val result = collection.scope.query(query, readonly = true).execute()
result.rows.map {
it.contentAs<Airport>()
}.toList()
}
}
Connessioni dirette
This endpoint fetches the airports that can be reached directly from the specified source airport code. This also uses a SQL++ query to fetch the results similar to the List Airport endpoint.
Consideriamo la query utilizzata qui:
SELECT distinct (route.destinationairport)
DALLA STAZIONE AEROPORTUALE COME STAZIONE AEROPORTUALE
Inserire la rotta come percorso su route.sourceairport = airport.faa
WHERE $airport.faa = aeroporto e route.stops = 0
Ordine per percorso. Aeroporto di destinazione
LIMIT $limite
OFFSET $offset
Raccogliamo le connessioni dirette unendo la raccolta dell'aeroporto alla raccolta del percorso e filtrando in base all'aeroporto di origine specificato dall'utente e alle rotte senza fermate.
Running The Tests
We have defined integration tests using the JUnit package for all the API end points. The integration tests use the same database configuration as the application. For the integration tests, we perform the operation using the API and confirm the results by checking the documents in the database. For example, to check the creation of the document by the API, we would call the API to create the document and then read the same document from the database and compare them. After the tests, the documents are cleaned up by calling the DELETE endpoint
To run the standard integration tests, use the following commands:
./gradlew test
Appendice
Ampliare l'API aggiungendo un'entità nuova
Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:
- Creare la nuova entità (collezione) nel bucket Couchbase. È possibile creare la collezione utilizzando il comando SDK o tramite il Interfaccia del server Couchbase.
- Define the routes in a file inside the
src/main/kotlin/com/couchbase/kotlin/quickstart/routesfolder similar to the existing routes. - Define the services in a new file inside the
src/main/kotlin/com/couchbase/kotlin/quickstart/servicesfolder similar to the existing services. - Define the repository for this collection inside a new file inside the
src/main/kotlin/com/couchbase/kotlin/quickstart/repositoriesfolder similar to the existing repositories. - Aggiungere i test per le nuove rotte in un nuovo file nel
src/test/kotlin/com/couchbase/kotlin/quickstartfolder similar to the existing ones.
Gestione automatica di un cluster di Couchbase
Se stai eseguendo questo quickstart con un cluster di Couchbase gestito autonomamente, è necessario caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.
È necessario aggiornare la stringa di connessione e le credenziali nel file src/main/resources/application.conf file nella cartella di origine.
NOTA: Couchbase must be installed and running prior to running the the ASP.NET app.
Documentazione Swagger
La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.
Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.
Testare l'API
È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.
-
Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.
-
Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.
Modelli
Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.