Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.
Guida rapida: crea un database Firestore utilizzando una libreria client server

Crea un database Firestore utilizzando una libreria client del server

Questa guida rapida mostra come configurare Firestore, aggiungere dati e leggere dati utilizzando la libreria client C#, Go, Java, Node.js, PHP, Python o Ruby.

Prima di iniziare

  • Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti gratuiti per l'esecuzione, il test e il deployment dei carichi di lavoro.
  • Nella pagina del selettore dei progetti in Google Cloud Console, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

  • Nella pagina del selettore dei progetti in Google Cloud Console, seleziona o crea un progetto Google Cloud.

    Vai al selettore progetti

Crea un database Firestore in modalità Native

Se questo è un nuovo progetto, devi creare un'istanza di database Firestore.

  1. Vai al visualizzatore Firestore.

  2. Nella schermata Seleziona un servizio di database, scegli Firestore in modalità Native.

  3. Seleziona una località per il tuo Firestore.

    Questa impostazione della località corrisponde alla località predefinita delle risorse di Google Cloud Platform (GCP) del progetto. Tieni presente che questa località verrà utilizzata per i servizi GCP nel tuo progetto che richiedono un'impostazione di località, in particolare il bucket Cloud Storage predefinito e l'app App Engine (obbligatoria se utilizzi Cloud Scheduler).

  4. Fai clic su Crea database.

Quando crei un progetto Firestore, abilita anche l'API in Cloud API Manager.

Configura l'autenticazione

Per eseguire la libreria client, devi prima configurare l'autenticazione creando un account di servizio e impostando una variabile di ambiente.

Fornisci le credenziali di autenticazione al codice della tua applicazione impostando la variabile di ambiente GOOGLE_APPLICATION_CREDENTIALS. Questa variabile si applica solo alla sessione shell corrente. Se vuoi che la variabile venga applicata alle sessioni shell future, impostala nel file di avvio della shell, ad esempio nel file ~/.bashrc o ~/.profile.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Sostituisci KEY_PATH con il percorso del file JSON che contiene la chiave dell'account di servizio.

Ad esempio:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Per PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Sostituisci KEY_PATH con il percorso del file JSON che contiene la chiave dell'account di servizio.

Ad esempio:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Per il prompt dei comandi:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Sostituisci KEY_PATH con il percorso del file JSON che contiene la chiave dell'account di servizio.

Aggiungere la libreria client del server all'app

Aggiungi le dipendenze e le librerie client necessarie alla tua app.

Java

Aggiungi la libreria Java di Firestore alla tua app:

  • Con Maven:
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.11.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-firestore</artifactId>
      </dependency>
  • Se utilizzi Gradle o non hai configurato la distinta base, consulta la pagina relativa al client Firestore per Java README.
  • Utilizzo di un IDE:

    Se utilizzi VS Code, IntelliJ o Eclipse, puoi aggiungere librerie client al progetto utilizzando i seguenti plug-in IDE:

    I plug-in forniscono funzionalità aggiuntive, come la gestione delle chiavi per gli account di servizio. Per informazioni dettagliate, consulta la documentazione di ogni plug-in.

Python

Aggiungi la libreria Python di Firestore alla tua app:

pip install --upgrade google-cloud-firestore

Node.js

Aggiungi la libreria Node.js di Firestore alla tua app:

npm install --save @google-cloud/firestore
Go

Installa la libreria Firestore Go:

go get cloud.google.com/go/firestore

Aggiungi la libreria Firestore Go alla tua app:

import "cloud.google.com/go/firestore"
PHP
  1. Installa e attiva l'estensione gRPC per PHP, che dovrai utilizzare nella libreria client.
  2. Aggiungi la libreria PHP Firestore alla tua app:
    composer require google/cloud-firestore
C#
  1. Aggiungi la libreria C# di Firestore alla tua app nel file .csproj:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  2. Aggiungi quanto segue al tuo file Program.cs:
    using Google.Cloud.Firestore;
Ruby
  1. Aggiungi la libreria Ruby di Firestore alla tua app in Gemfile:
    gem "google-cloud-firestore"
  2. Installa le dipendenze da Gemfile utilizzando:
    bundle install

Inizializza Firestore

Inizializza un'istanza di Firestore:

Java
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
FirestoreOptions firestoreOptions =
    FirestoreOptions.getDefaultInstance().toBuilder()
        .setProjectId(projectId)
        .setCredentials(GoogleCredentials.getApplicationDefault())
        .build();
Firestore db = firestoreOptions.getService();
Python
from google.cloud import firestore

# The `project` parameter is optional and represents which project the client
# will act on behalf of. If not supplied, the client falls back to the default
# project inferred from the environment.
db = firestore.Client(project='my-project-id')
Python
(asincrono)
from google.cloud import firestore

# The `project` parameter is optional and represents which project the client
# will act on behalf of. If not supplied, the client falls back to the default
# project inferred from the environment.
db = firestore.AsyncClient(project='my-project-id')
Node.js
const Firestore = require('@google-cloud/firestore');

const db = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});
Go
import (
	"context"
	"flag"
	"fmt"
	"log"

	"google.golang.org/api/iterator"

	"cloud.google.com/go/firestore"
)

func createClient(ctx context.Context) *firestore.Client {
	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	// Close client when done with
	// defer client.Close()
	return client
}
PHP
use Google\Cloud\Firestore\FirestoreClient;

/**
 * Initialize Cloud Firestore with default project ID.
 */
function setup_client_create(string $projectId = null)
{
    // Create the Cloud Firestore client
    if (empty($projectId)) {
        // The `projectId` parameter is optional and represents which project the
        // client will act on behalf of. If not supplied, the client falls back to
        // the default project inferred from the environment.
        $db = new FirestoreClient();
        printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
    } else {
        $db = new FirestoreClient([
            'projectId' => $projectId,
        ]);
        printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
    }
}
C#
FirestoreDb db = FirestoreDb.Create(project);
Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
Ruby
require "google/cloud/firestore"

# The `project_id` parameter is optional and represents which project the
# client will act on behalf of. If not supplied, the client falls back to the
# default project inferred from the environment.
firestore = Google::Cloud::Firestore.new project_id: project_id

puts "Created Cloud Firestore client with given project ID."

Aggiungi dati

Firestore archivia i dati in Documenti, che sono archiviati in Raccolte. Firestore crea raccolte e documenti in modo implicito la prima volta che aggiungi dati al documento. Non devi creare esplicitamente raccolte o documenti.

Crea una nuova raccolta e un nuovo documento usando il seguente codice di esempio.

Java

DocumentReference docRef = db.collection("users").document("alovelace");
// Add document data  with id "alovelace" using a hashmap
Map<String, Object> data = new HashMap<>();
data.put("first", "Ada");
data.put("last", "Lovelace");
data.put("born", 1815);
//asynchronously write data
ApiFuture<WriteResult> result = docRef.set(data);
// ...
// result.get() blocks on response
System.out.println("Update time : " + result.get().getUpdateTime());

Python

doc_ref = db.collection(u'users').document(u'alovelace')
doc_ref.set({
    u'first': u'Ada',
    u'last': u'Lovelace',
    u'born': 1815
})

Python
(Async)

doc_ref = db.collection("users").document("alovelace")
await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

Node.js

const docRef = db.collection('users').doc('alovelace');

await docRef.set({
  first: 'Ada',
  last: 'Lovelace',
  born: 1815
});

Go

_, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
	"first": "Ada",
	"last":  "Lovelace",
	"born":  1815,
})
if err != nil {
	log.Fatalf("Failed adding alovelace: %v", err)
}

PHP

$docRef = $db->collection('samples/php/users')->document('alovelace');
$docRef->set([
    'first' => 'Ada',
    'last' => 'Lovelace',
    'born' => 1815
]);
printf('Added data to the lovelace document in the users collection.' . PHP_EOL);

C#

DocumentReference docRef = db.Collection("users").Document("alovelace");
Dictionary<string, object> user = new Dictionary<string, object>
{
    { "First", "Ada" },
    { "Last", "Lovelace" },
    { "Born", 1815 }
};
await docRef.SetAsync(user);

Ruby

doc_ref = firestore.doc "#{collection_path}/alovelace"

doc_ref.set(
  {
    first: "Ada",
    last:  "Lovelace",
    born:  1815
  }
)

puts "Added data to the alovelace document in the users collection."

Ora aggiungi un altro documento alla raccolta users. Tieni presente che questo documento include una coppia chiave-valore (nome intermedio) che non viene visualizzata nel primo documento. I documenti di una raccolta possono contenere insiemi di informazioni diversi.

Java

DocumentReference docRef = db.collection("users").document("aturing");
// Add document data with an additional field ("middle")
Map<String, Object> data = new HashMap<>();
data.put("first", "Alan");
data.put("middle", "Mathison");
data.put("last", "Turing");
data.put("born", 1912);

ApiFuture<WriteResult> result = docRef.set(data);
System.out.println("Update time : " + result.get().getUpdateTime());

Python

doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.set({
    u'first': u'Alan',
    u'middle': u'Mathison',
    u'last': u'Turing',
    u'born': 1912
})

Python
(Async)

doc_ref = db.collection("users").document("aturing")
await doc_ref.set(
    {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
)

Node.js

const aTuringRef = db.collection('users').doc('aturing');

await aTuringRef.set({
  'first': 'Alan',
  'middle': 'Mathison',
  'last': 'Turing',
  'born': 1912
});

Go

_, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
	"first":  "Alan",
	"middle": "Mathison",
	"last":   "Turing",
	"born":   1912,
})
if err != nil {
	log.Fatalf("Failed adding aturing: %v", err)
}

PHP

$docRef = $db->collection('samples/php/users')->document('aturing');
$docRef->set([
    'first' => 'Alan',
    'middle' => 'Mathison',
    'last' => 'Turing',
    'born' => 1912
]);
printf('Added data to the aturing document in the users collection.' . PHP_EOL);

C#

DocumentReference docRef = db.Collection("users").Document("aturing");
Dictionary<string, object> user = new Dictionary<string, object>
{
    { "First", "Alan" },
    { "Middle", "Mathison" },
    { "Last", "Turing" },
    { "Born", 1912 }
};
await docRef.SetAsync(user);

Ruby

doc_ref = firestore.doc "#{collection_path}/aturing"

doc_ref.set(
  {
    first:  "Alan",
    middle: "Mathison",
    last:   "Turing",
    born:   1912
  }
)

puts "Added data to the aturing document in the users collection."

Lettura di dati

Per verificare rapidamente di aver aggiunto dati a Firestore, utilizza il visualizzatore dati nella Console Firebase.

Puoi anche utilizzare il metodo get per recuperare l'intera raccolta.

Java

// asynchronously retrieve all users
ApiFuture<QuerySnapshot> query = db.collection("users").get();
// ...
// query.get() blocks on response
QuerySnapshot querySnapshot = query.get();
List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
for (QueryDocumentSnapshot document : documents) {
  System.out.println("User: " + document.getId());
  System.out.println("First: " + document.getString("first"));
  if (document.contains("middle")) {
    System.out.println("Middle: " + document.getString("middle"));
  }
  System.out.println("Last: " + document.getString("last"));
  System.out.println("Born: " + document.getLong("born"));
}

Python

users_ref = db.collection(u'users')
docs = users_ref.stream()

for doc in docs:
    print(f'{doc.id} => {doc.to_dict()}')

Python
(Async)

users_ref = db.collection("users")
docs = users_ref.stream()

async for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")

Node.js

const snapshot = await db.collection('users').get();
snapshot.forEach((doc) => {
  console.log(doc.id, '=>', doc.data());
});

Go

iter := client.Collection("users").Documents(ctx)
for {
	doc, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatalf("Failed to iterate: %v", err)
	}
	fmt.Println(doc.Data())
}

PHP

$usersRef = $db->collection('samples/php/users');
$snapshot = $usersRef->documents();
foreach ($snapshot as $user) {
    printf('User: %s' . PHP_EOL, $user->id());
    printf('First: %s' . PHP_EOL, $user['first']);
    if (!empty($user['middle'])) {
        printf('Middle: %s' . PHP_EOL, $user['middle']);
    }
    printf('Last: %s' . PHP_EOL, $user['last']);
    printf('Born: %d' . PHP_EOL, $user['born']);
    printf(PHP_EOL);
}
printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);

C#

CollectionReference usersRef = db.Collection("users");
QuerySnapshot snapshot = await usersRef.GetSnapshotAsync();
foreach (DocumentSnapshot document in snapshot.Documents)
{
    Console.WriteLine("User: {0}", document.Id);
    Dictionary<string, object> documentDictionary = document.ToDictionary();
    Console.WriteLine("First: {0}", documentDictionary["First"]);
    if (documentDictionary.ContainsKey("Middle"))
    {
        Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
    }
    Console.WriteLine("Last: {0}", documentDictionary["Last"]);
    Console.WriteLine("Born: {0}", documentDictionary["Born"]);
    Console.WriteLine();
}

Ruby

users_ref = firestore.col collection_path
users_ref.get do |user|
  puts "#{user.document_id} data: #{user.data}."
end

Passaggi successivi

Approfondisci le tue conoscenze con i seguenti argomenti: