@google-cloud/datastore
- Version 9.1.0
- Published
- 4.27 MB
- 9 dependencies
- Apache-2.0 license
Install
npm i @google-cloud/datastore
yarn add @google-cloud/datastore
pnpm add @google-cloud/datastore
Overview
Cloud Datastore Client Library for Node.js
Index
Variables
Functions
Classes
Datastore
- auth
- baseUrl_
- clients_
- createAggregationQuery()
- createQuery()
- customEndpoint_
- DatastoreRequest
- defaultBaseUrl_
- determineBaseUrl_()
- double()
- export()
- geoPoint()
- getDatabaseId()
- getIndexes()
- getIndexesStream()
- getProjectId()
- import()
- index()
- insert()
- int()
- isDouble()
- isGeoPoint()
- isInt()
- isKey()
- key()
- KEY
- KEY
- keyFromLegacyUrlsafe()
- keyToLegacyUrlSafe()
- MORE_RESULTS_AFTER_CURSOR
- MORE_RESULTS_AFTER_CURSOR
- MORE_RESULTS_AFTER_LIMIT
- MORE_RESULTS_AFTER_LIMIT
- namespace
- NO_MORE_RESULTS
- NO_MORE_RESULTS
- options
- port_
- Query
- save()
- transaction()
- Transaction
- update()
- upsert()
DatastoreAdminClient
- apiEndpoint
- apiEndpoint
- auth
- cancelOperation()
- checkCreateIndexProgress()
- checkDeleteIndexProgress()
- checkExportEntitiesProgress()
- checkImportEntitiesProgress()
- close()
- createIndex()
- datastoreAdminStub
- deleteIndex()
- deleteOperation()
- descriptors
- exportEntities()
- getIndex()
- getOperation()
- getProjectId()
- importEntities()
- initialize()
- innerApiCalls
- listIndexes()
- listIndexesAsync()
- listIndexesStream()
- listOperationsAsync()
- operationsClient
- port
- scopes
- servicePath
- universeDomain
- warn
DatastoreClient
- allocateIds()
- apiEndpoint
- apiEndpoint
- auth
- beginTransaction()
- cancelOperation()
- close()
- commit()
- datastoreStub
- deleteOperation()
- descriptors
- getOperation()
- getProjectId()
- initialize()
- innerApiCalls
- listOperationsAsync()
- lookup()
- operationsClient
- port
- reserveIds()
- rollback()
- runAggregationQuery()
- runQuery()
- scopes
- servicePath
- universeDomain
- warn
Interfaces
Type Aliases
Variables
variable v1
const v1: any;
Functions
Classes
class AggregateField
abstract class AggregateField {}
An AggregateField is a class that contains data that defines an aggregation.
property alias_
alias_?: string;
method alias
alias: (alias?: string) => AggregateField;
Sets the alias on the aggregate field that should be used.
Parameter alias
The label used in the results to describe this aggregate field when a query is run.
Returns
{AggregateField}
method average
static average: (property: string) => Average;
Gets a copy of the Average aggregate field.
Returns
{Average}
method count
static count: () => Count;
Gets a copy of the Count aggregate field.
Returns
{Count}
method sum
static sum: (property: string) => Sum;
Gets a copy of the Sum aggregate field.
Returns
{Sum}
method toProto
abstract toProto: () => any;
Gets the proto for the aggregate field.
class Datastore
class Datastore extends DatastoreRequest {}
Idiomatic class for interacting with Cloud Datastore. Uses the lower-level DatastoreClient class under the hood.
In addition to the constructor options shown here, the Datastore class constructor accepts the same options accepted by DatastoreClient.
The Datastore Emulator
Make sure you have the gcloud SDK installed, then run:
$ gcloud beta emulators datastore start --no-legacy
You will see the following printed:
[datastore] API endpoint: http://localhost:8005 [datastore] If you are using a library that supports the DATASTORE_EMULATOR_HOST environment variable, run: [datastore] [datastore] export DATASTORE_EMULATOR_HOST=localhost:8005 [datastore] [datastore] Dev App Server is now running.
Set that environment variable and your localhost Datastore will automatically be used. You can also pass this address in manually with
apiEndpoint
.Additionally,
DATASTORE_PROJECT_ID
is recognized. If you have this set, you don't need to provide aprojectId
.Parameter options
Configuration options.
Parameter
{string} [options.apiEndpoint] Override the default API endpoint used to reach Datastore. This is useful for connecting to your local Datastore server (usually "http://localhost:8080").
Parameter
{string} [options.namespace] Namespace to isolate transactions to.
Example 1
Import the client library
const {Datastore} = require('@google-cloud/datastore');Example 2
Create a client that uses Application Default Credentials (ADC):
const datastore = new Datastore();Example 3
Create a client with explicit credentials:
const datastore = new Datastore({projectId: 'your-project-id',keyFilename: '/path/to/keyfile.json'});Example 4
Retrieving Records
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();// Records, called "entities" in Datastore, are retrieved by using a key. The// key is more than a numeric identifier, it is a complex data structure that// can be used to model relationships. The simplest key has a string `kind`// value, and either a numeric `id` value, or a string `name` value.//// A single record can be retrieved with {@link Datastore#key} and// {@link Datastore#get}.//-const key = datastore.key(['Company', 'Google']);datastore.get(key, function(err, entity) {// entity = The record.// entity[datastore.KEY] = The key for this entity.});//-// <h3>Querying Records</h3>//// Create a query with {@link Datastore#createQuery}.//-const query = datastore.createQuery('Company');//-// Multiple records can be found that match criteria with// {@link Query#filter}.//-query.filter('location', 'CA');//-// Records can also be ordered with {@link Query#order}.//-query.order('name');//-// The number of records returned can be specified with// {@link Query#limit}.//-query.limit(5);//-// Records' key structures can also be queried with// {@link Query#hasAncestor}.//-const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);query.hasAncestor(ancestorKey);//-// Run the query with {@link Datastore#runQuery}.//-datastore.runQuery(query, (err, entities) => {// entities = An array of records.// Access the Key object for an entity.const firstEntityKey = entities[0][datastore.KEY];});Example 5
Paginating Records
// Imagine building a website that allows a user to sift through hundreds of// their contacts. You'll likely want to only display a subset of these at// once, so you set a limit.//-const express = require('express');const app = express();const NUM_RESULTS_PER_PAGE = 15;app.get('/contacts', (req, res) => {const query = datastore.createQuery('Contacts').limit(NUM_RESULTS_PER_PAGE);if (req.query.nextPageCursor) {query.start(req.query.nextPageCursor);}datastore.runQuery(query, (err, entities, info) => {if (err) {// Error handling omitted.return;}// Respond to the front end with the contacts and the cursoring token// from the query we just ran.const frontEndResponse = {contacts: entities};// Check if more results may exist.if (info.moreResults !== datastore.NO_MORE_RESULTS) {frontEndResponse.nextPageCursor = info.endCursor;}res.render('contacts', frontEndResponse);});});Example 6
Creating Records
// New entities can be created and persisted with {@link Datastore#save}.// The entity must have a key to be saved. If you don't specify an// identifier for the key, one is generated for you.//// We will create a key with a `name` identifier, "Google".//-const key = datastore.key(['Company', 'Google']);const data = {name: 'Google',location: 'CA'};datastore.save({key: key,data: data}, (err) => {if (!err) {// Record saved successfully.}});//-// We can verify the data was saved by using {@link Datastore#get}.//-datastore.get(key, (err, entity) => {// entity = {// name: 'Google',// location: 'CA'// }});//-// If we want to update this record, we can modify the data object and re-// save it.//-data.symbol = 'GOOG';datastore.save({key: key, // defined above (datastore.key(['Company', 'Google']))data: data}, (err, entity) => {if (!err) {// Record updated successfully.}});Example 7
Deleting Records
// Entities can be removed from Datastore by passing the entity's key object// to {@link Datastore#delete}.//-const key = datastore.key(['Company', 'Google']);datastore.delete(key, (err) => {if (!err) {// Record deleted successfully.}});Example 8
Transactions
// Complex logic can be wrapped in a transaction with// {@link Datastore#transaction}. All queries and updates run within// the transaction will be applied when the `done` function is called.//-const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}const key = datastore.key(['Company', 'Google']);transaction.get(key, (err, entity) => {if (err) {// Error handling omitted.}entity.symbol = 'GOOG';transaction.save(entity);transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});Example 9
Queries with Ancestors
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const customerId1 = 2993844;const customerId2 = 4993882;const customerKey1 = datastore.key(['Customer', customerId1]);const customerKey2 = datastore.key(['Customer', customerId2]);const cookieKey1 = datastore.key(['Customer', customerId1, 'Cookie','cookie28839']); // child entity const cookieKey2 =datastore.key(['Customer', customerId1, 'Cookie', 'cookie78984']); // childentity const cookieKey3 = datastore.key(['Customer', customerId2, 'Cookie','cookie93911']); // child entityconst entities = [];entities.push({key: customerKey1,data: {name: 'Jane Doe',address: '4848 Liller'}});entities.push({key: customerKey2,data: {name: 'John Smith',address: '4848 Pine'}});entities.push({key: cookieKey1,data: {cookieVal: 'dj83kks88rkld'}});entities.push({key: cookieKey2,data: {cookieVal: 'sj843ka99s'}});entities.push({key: cookieKey3,data: {cookieVal: 'otk82k2kw'}});datastore.upsert(entities);const query = datastore.createQuery().hasAncestor(customerKey1);datastore.runQuery(query, (err, entities) => {for (let entity of entities) {console.log(entity[datastore.KEY]);}});const query2 = datastore.createQuery().hasAncestor(customerKey2);datastore.runQuery(query2, (err, entities) => {for (let entity of entities) {console.log(entity[datastore.KEY]);}});datastore.runQuery(query2, (entities) => {console.log(entities);});
constructor
constructor(options?: DatastoreOptions);
property auth
auth: GoogleAuth;
property baseUrl_
baseUrl_?: string;
property clients_
clients_: Map<string, ClientStub>;
property customEndpoint_
customEndpoint_?: boolean;
property DatastoreRequest
DatastoreRequest: typeof DatastoreRequest;
DatastoreRequest class.
Datastore.DatastoreRequest
See Also
DatastoreRequest {constructor}
property defaultBaseUrl_
defaultBaseUrl_: string;
property KEY
static KEY: Symbol;
Access the Key from an Entity object.
Datastore#KEY {symbol}
property KEY
KEY: Symbol;
property MORE_RESULTS_AFTER_CURSOR
static MORE_RESULTS_AFTER_CURSOR: string;
This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults
.There *may* be more results after the specified end cursor.
{string}
property MORE_RESULTS_AFTER_CURSOR
MORE_RESULTS_AFTER_CURSOR: string;
property MORE_RESULTS_AFTER_LIMIT
static MORE_RESULTS_AFTER_LIMIT: string;
This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults
.There *may* be more results after the specified limit.
{string}
property MORE_RESULTS_AFTER_LIMIT
MORE_RESULTS_AFTER_LIMIT: string;
property namespace
namespace?: string;
property NO_MORE_RESULTS
static NO_MORE_RESULTS: string;
This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults
.There are no more results left to query for.
{string}
property NO_MORE_RESULTS
NO_MORE_RESULTS: string;
property options
options: DatastoreOptions;
property port_
port_?: number;
property Query
Query: typeof Query;
Query class.
Datastore.Query
See Also
Query {constructor}
property Transaction
Transaction: typeof Transaction;
Transaction class.
Datastore.Transaction
See Also
Transaction {constructor}
method createAggregationQuery
createAggregationQuery: (query: Query) => AggregateQuery;
Create an aggregation query from a Query.
Parameter query
A Query object.
method createQuery
createQuery: { (kind?: string): Query; (kind?: string[]): Query; (namespace: string, kind: string): Query; (namespace: string, kind: string[]): Query;};
Create a query for the specified kind. See Query for all of the available methods.
Parameter namespace
Namespace.
Parameter kind
The kind to query.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');See Also
method determineBaseUrl_
determineBaseUrl_: (customApiEndpoint?: string) => void;
Determine the appropriate endpoint to use for API requests. If not explicitly defined, check for the "DATASTORE_EMULATOR_HOST" environment variable, used to connect to a local Datastore server.
Parameter customApiEndpoint
Custom API endpoint.
method double
static double: (value: number) => entity.Double;
Helper function to get a Datastore Double object.
Parameter value
The double value.
Returns
{object}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const threeDouble = datastore.double(3.0);
method export
export: { (config: ExportEntitiesConfig): Promise<LongRunningResponse>; (config: ExportEntitiesConfig, callback: LongRunningCallback): void;};
Export entities from this project to a Google Cloud Storage bucket.
Parameter config
Configuration object.
Parameter
{string | Bucket} config.bucket The
gs://bucket
path or a @google-cloud/storage Bucket object.Parameter
{string[]} [config.kinds] The kinds to include in this import.
Parameter
{string[]} [config.namespaces] The namespace IDs to include in this import.
Parameter
{object} [config.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Operation} callback.operation An operation object that can be used to check the status of the request.
method geoPoint
static geoPoint: (coordinates: entity.Coordinates) => entity.GeoPoint;
Helper function to get a Datastore Geo Point object.
Parameter coordinates
Coordinate value.
Parameter
{number} coordinates.latitude Latitudinal value.
Parameter
{number} coordinates.longitude Longitudinal value.
Returns
{object}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const coordinates = {latitude: 40.6894,longitude: -74.0447};const geoPoint = datastore.geoPoint(coordinates);//-// List all companies that are located at 40.123 latitude// and -74.0447 longitude.//-const query = datastore.createQuery('Company');const companyQuery = query.filter('geoPoint.latitude', datastore.double(40.123)).filter('geoPoint.longitude', datastore.double(-74.0447));
method getDatabaseId
getDatabaseId: () => string | undefined;
Gets the database id that all requests will be run against.
Returns
{string} The database id that the current client is set to that requests will run against.
method getIndexes
getIndexes: { (options?: GetIndexesOptions): Promise<GetIndexesResponse>; (options: GetIndexesOptions, callback: GetIndexesCallback): void; (callback: GetIndexesCallback): void;};
Get all of the indexes in this project.
Parameter optionsOrCallback
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.error An error returned while making this request.
Parameter
{Index[]} callback.indexes All matching Index instances.
Parameter
{object} callback.apiResponse The full API response. {void | Promise}
method getIndexesStream
getIndexesStream: (options?: GetIndexesOptions) => NodeJS.ReadableStream;
Get all of the indexes in this project as a readable object stream.
Parameter options
Configuration object. See Datastore#getIndexes for a complete list of options.
Returns
{ReadableStream}
method getProjectId
getProjectId: () => Promise<string>;
method import
import: { (config: ImportEntitiesConfig): Promise<LongRunningResponse>; (config: ImportEntitiesConfig, callback: LongRunningCallback): void;};
Import entities into this project from a remote file.
Parameter config
Configuration object.
Parameter
{string | File} config.file The
gs://bucket/file
path or a @google-cloud/storage File object.Parameter
{string[]} [config.kinds] The kinds to include in this import.
Parameter
{string[]} [config.namespaces] The namespace IDs to include in this import.
Parameter
{object} [config.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Operation} callback.operation An operation object that can be used to check the status of the request.
method index
index: (id: string) => Index;
Get a reference to an Index.
Parameter id
The index name or id.
Returns
{Index}
method insert
insert: { (entities: Entities): Promise<InsertResponse>; (entities: any, callback: CommitCallback): void;};
Maps to Datastore#save, forcing the method to be
insert
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
method int
static int: (value: number | string) => entity.Int;
Helper function to get a Datastore Integer object.
This is also useful when using an ID outside the bounds of a JavaScript Number object.
Parameter value
The integer value.
Returns
{object}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const sevenInteger = datastore.int(7);//-// Create an Int to support long Key IDs.//-const key = datastore.key(['Kind',datastore.int('100000000000001234')]);
method isDouble
static isDouble: (value?: {}) => value is entity.Double;
Helper function to check if something is a Datastore Double object.
Parameter value
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isDouble(0.42); // falsedatastore.isDouble(datastore.double(0.42)); // true
method isGeoPoint
static isGeoPoint: (value?: {}) => value is entity.GeoPoint;
Helper function to check if something is a Datastore Geo Point object.
Parameter value
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const coordinates = {latitude: 0,longitude: 0};datastore.isGeoPoint(coordinates); // falsedatastore.isGeoPoint(datastore.geoPoint(coordinates)); // true
method isInt
static isInt: (value?: {}) => value is entity.Int;
Helper function to check if something is a Datastore Integer object.
Parameter value
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isInt(42); // falsedatastore.isInt(datastore.int(42)); // true
method isKey
static isKey: (value?: {}) => value is entity.Key;
Helper function to check if something is a Datastore Key object.
Parameter value
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isKey({path: ['Company', 123]}); // falsedatastore.isKey(datastore.key(['Company', 123])); // true
method key
key: { (options: entity.KeyOptions): entity.Key; (path: PathType[]): entity.Key; (path: string): entity.Key;};
Helper to create a Key object, scoped to the instance's namespace by default.
You may also specify a configuration object to define a namespace and path.
Parameter options
Key path. To specify or override a namespace, you must use an object here to explicitly state it.
Parameter
{string|array} [options.path] Key path.
Parameter
{string} [options.namespace] Optional namespace.
Returns
{Key} A newly created Key from the options given.
Example 1
<caption>Create an incomplete key with a kind value of `Company`.Since no Id is supplied, Datastore will generate one on save.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key('Company');Example 2
<caption>Create a complete key with a kind value of `Company` and Id `123`.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company', 123]);Example 3
<caption>If the ID integer is outside the bounds of a JavaScript Numberobject, create an Int.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company',datastore.int('100000000000001234')]);Example 4
<caption>Create a complete key with a kind value of `Company` and name `Google`.Because the supplied Id is a string, Datastore will prefix it with "name=".Had the supplied Id been numeric, Datastore would prefix it with the standard, "id=".</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company', 'Google']);Example 5
<caption>Create a complete key from a provided namespace and path.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key({namespace: 'My-NS',path: ['Company', 123]});Example 6
<caption>Create a complete key that specifies an ancestor. This will create a Team entitywith a name of "Datastore", which belongs to the Company with the "name=Google" key.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company', 'Google', 'Team', 'Datastore']);Example 7
<caption>Create a incomplete key that specifies an ancestor. This will create an Employee entitywith an auto-generated Id, which belongs to the Company with the "name=Google" key.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company', 'Google', 'Employee']);
method keyFromLegacyUrlsafe
keyFromLegacyUrlsafe: (key: string) => entity.Key;
Helper to convert URL safe key string to entity key object
This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference").
Parameter key
Entity key object.
Parameter locationPrefix
Optional . The location prefix of an App Engine project ID. Often this value is 's~', but may also be 'e~', or other location prefixes currently unknown.
Returns
{string} Created urlsafe key.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const urlSafeKey = 'ag9ncmFzcy1jbHVtcC00NzlyEwsSB0NvbXBhbnkiBkdvb2dsZQw';datastore.keyFromLegacyUrlsafe(key);
method keyToLegacyUrlSafe
keyToLegacyUrlSafe: { (key: entity.Key, locationPrefix?: string): Promise<string>; (key: entity.Key, callback: KeyToLegacyUrlSafeCallback): void; ( key: entity.Key, locationPrefix: string, callback: KeyToLegacyUrlSafeCallback ): void;};
Helper to create a URL safe key.
This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). The returned string can be used as the "urlsafe" The base64 encoded values will have padding removed.
Parameter key
Entity key object.
Parameter locationPrefix
Optional . The location prefix of an App Engine project ID. Often this value is 's~', but may also be 'e~', or other location prefixes currently unknown.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{string} callback.urlSafeKey A Base64-encoded URL-safe key.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company', 'Google']);datastore.keyToLegacyUrlSafe(key, (err, urlSafeKey) => {if (err) {// Error handling omitted.}console.log(urlSafeKey);});//-// Create a complete URL-safe key using a location prefix.//-const locationPrefix = 's~';datastore.keyToLegacyUrlSafe(key, locationPrefix, (err, urlSafeKey) => {if (err) {// Error handling omitted.}console.log(urlSafeKey);});//-// If the callback is omitted, we'll return a Promise.//-datastore.keyToLegacyUrlSafe(key).then((data) => {const urlSafeKey = data[0];console.log(urlSafeKey);});
method save
save: { (entities: Entities, gaxOptions?: CallOptions): Promise<SaveResponse>; (entities: any, gaxOptions: CallOptions, callback: CommitCallback): void; (entities: any, callback: CommitCallback): void;};
Insert or update the specified object(s). If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID.
This method will determine the correct Datastore method to execute (
upsert
,insert
, orupdate
) by using the key(s) provided. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be updated with the data specified.By default, all properties are indexed. To prevent a property from being included in *all* indexes, you must supply an
excludeFromIndexes
array.To prevent large properties from being included in *all* indexes, you must supply
excludeLargeProperties: true
. See below for an example.Transaction#save as save
Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the example below to see how to target properties at different levels of nesting within your
Parameter
{boolean} [entities.excludeLargeProperties] Automatically exclude large properties from indexing. It help in storing large values.
Parameter
{string} [entities.method] Explicit method to use, either 'insert', 'update', or 'upsert'.
Parameter
{object} entities.data Data to save with the provided key. entity.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
Throws
{Error} If an unrecognized method is provided.
Example 1
//-// Save a single entity.//// Notice that we are providing an incomplete key. After saving, the// original Key object used to save will be updated to contain the path// with its generated ID.//-const key = datastore.key('Company');const entity = {key: key,data: {rating: '10'}};datastore.save(entity, (err) => {console.log(key.path); // [ 'Company', 5669468231434240 ]console.log(key.namespace); // undefined});//-// Save a single entity using a provided name instead of auto-generated ID.//// Here we are providing a key with name instead of an ID. After saving,// the original Key object used to save will be updated to contain the// path with the name instead of a generated ID.//-const key = datastore.key(['Company', 'donutshack']);const entity = {key: key,data: {name: 'DonutShack',rating: 8}};datastore.save(entity, (err) => {console.log(key.path); // ['Company', 'donutshack']console.log(key.namespace); // undefined});//-// Save a single entity with a provided namespace. Namespaces allow for// multitenancy. To read more about this, see// [the Datastore docs on key concepts](https://goo.gl/M1LUAu).//// Here we are providing a key with namespace.//-const key = datastore.key({namespace: 'my-namespace',path: ['Company', 'donutshack']});const entity = {key: key,data: {name: 'DonutShack',rating: 8}};datastore.save(entity, (err) => {console.log(key.path); // ['Company', 'donutshack']console.log(key.namespace); // 'my-namespace'});//-// Save different types of data, including ints, doubles, dates, booleans,// blobs, and lists.//// Notice that we are providing an incomplete key. After saving, the// original Key object used to save will be updated to contain the path// with its generated ID.//-const key = datastore.key('Company');const entity = {key: key,data: {name: 'DonutShack',rating: datastore.int(10),worth: datastore.double(123456.78),location: datastore.geoPoint({latitude: 40.6894,longitude: -74.0447}),numDonutsServed: 45,founded: new Date('Tue May 12 2015 15:30:00 GMT-0400 (EDT)'),isStartup: true,donutEmoji: Buffer.from('\uD83C\uDF69'),keywords: ['donut','coffee','yum']}};datastore.save(entity, (err, apiResponse) => {});//-// Use an array, `excludeFromIndexes`, to exclude properties from indexing.// This will allow storing string values larger than 1500 bytes.//-const entity = {key: datastore.key('Company'),excludeFromIndexes: ['description','embeddedEntity.description','arrayValue[]','arrayValue[].description'],data: {description: 'Long string (...)',embeddedEntity: {description: 'Long string (...)'},arrayValue: ['Long string (...)',{description: 'Long string (...)'}]}};datastore.save(entity, (err, apiResponse) => {});//-// Use boolean `excludeLargeProperties`, to auto exclude Large properties from indexing.// This will allow storing string values larger than 1500 bytes.//-const entity = {key: datastore.key('Company'),data: {description: 'Long string (...)',embeddedEntity: {description: 'Long string (...)'},arrayValue: ['Long string (...)',{description: 'Long string (...)'}]},excludeLargeProperties: true};datastore.save(entity, (err, apiResponse) => {});//-// Save multiple entities at once.//-const companyKey = datastore.key(['Company', 123]);const productKey = datastore.key(['Product', 'Computer']);const entities = [{key: companyKey,data: {HQ: 'Dallas, TX'}},{key: productKey,data: {vendor: 'Dell'}}];datastore.save(entities, (err, apiResponse) => {});//-// Explicitly attempt to 'insert' a specific entity.//-const userKey = datastore.key(['User', 'chilts']);const entity = {key: userKey,method: 'insert',data: {fullName: 'Andrew Chilton'}};datastore.save(entity, (err, apiResponse) => {});//-// Returns a Promise if callback is omitted.//-datastore.save(entity).then((data) => {const apiResponse = data[0];});
method transaction
transaction: (options?: TransactionOptions) => Transaction;
Create a new Transaction object.
Parameter options
Configuration object.
Parameter
{string} [options.id] The ID of a previously run transaction.
Parameter
{boolean} [options.readOnly=false] A read-only transaction cannot modify entities.
Returns
{Transaction}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();
method update
update: { (entities: Entities): Promise<UpdateResponse>; (entities: any, callback: CommitCallback): void;};
Maps to Datastore#save, forcing the method to be
update
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
method upsert
upsert: { (entities: Entities): Promise<UpsertResponse>; (entities: any, callback: CommitCallback): void;};
Maps to Datastore#save, forcing the method to be
upsert
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
class DatastoreAdminClient
class DatastoreAdminClient {}
Google Cloud Datastore Admin API
The Datastore Admin API provides several admin services for Cloud Datastore.
Concepts: Project, namespace, kind, and entity as defined in the Google Cloud Datastore API.
Operation: An Operation represents work being performed in the background.
EntityFilter: Allows specifying a subset of entities in a project. This is specified as a combination of kinds and namespaces (either or both of which may be all).
Export/Import Service:
- The Export/Import service provides the ability to copy all or a subset of entities to/from Google Cloud Storage. - Exported data may be imported into Cloud Datastore for any Google Cloud Platform project. It is not restricted to the export source project. It is possible to export from one project and then import into another. - Exported data can also be loaded into Google BigQuery for analysis. - Exports and imports are performed asynchronously. An Operation resource is created for each export/import. The state (including any errors encountered) of the export/import may be queried via the Operation resource.
Index Service:
- The index service manages Cloud Datastore composite indexes. - Index creation and deletion are performed asynchronously. An Operation resource is created for each such asynchronous operation. The state of the operation (including any errors encountered) may be queried via the Operation resource.
Operation Service:
- The Operations collection provides a record of actions performed for the specified project (including any operations in progress). Operations are not created directly but through calls on other collections or resources. - An operation that is not yet done may be cancelled. The request to cancel is asynchronous and the operation may continue to run for some time after the request to cancel is made. - An operation that is done may be deleted so that it is no longer listed as part of the Operation collection. - ListOperations returns all pending operations, but not completed operations. - Operations are created by service DatastoreAdmin, but are accessed via service google.longrunning.Operations. v1
constructor
constructor(opts?: ClientOptions, gaxInstance?: any);
Construct an instance of DatastoreAdminClient.
Parameter options
The configuration object. The options accepted by the constructor are described in detail in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). The common options are:
Parameter
{object} [options.credentials] - Credentials object.
Parameter
{string} [options.credentials.client_email]
Parameter
{string} [options.credentials.private_key]
Parameter
{string} [options.email] - Account email address. Required when using a .pem or .p12 keyFilename.
Parameter
{string} [options.keyFilename] - Full path to the a .json, .pem, or .p12 key downloaded from the Google Developers Console. If you provide a path to a JSON file, the projectId option below is not necessary. NOTE: .pem and .p12 require you to specify options.email as well.
Parameter
{number} [options.port] - The port on which to connect to the remote host.
Parameter
{string} [options.projectId] - The project ID from the Google Developer's Console, e.g. 'grape-spaceship-123'. We will also check the environment variable GCLOUD_PROJECT for your project ID. If your app is running in an environment which supports , your project ID will be detected automatically.
Parameter
{string} [options.apiEndpoint] - The domain name of the API remote host.
Parameter
{gax.ClientConfig} [options.clientConfig] - Client configuration override. Follows the structure of gapicConfig.
Parameter
{boolean} [options.fallback] - Use HTTP/1.1 REST mode. For more information, please check the .
Parameter gaxInstance
: loaded instance of
google-gax
. Useful if you need to avoid loading the default gRPC version and want to use the fallback HTTP implementation. Load only fallback version and pass it to the constructor: ``` const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC const client = new DatastoreAdminClient({fallback: true}, gax); ```
property apiEndpoint
static readonly apiEndpoint: string;
The DNS address for this API service - same as servicePath.
Returns
{string} The DNS address for this service.
Deprecated
Use the apiEndpoint method of the client instance.
property apiEndpoint
readonly apiEndpoint: string;
The DNS address for this API service.
Returns
{string} The DNS address for this service.
property auth
auth: gax.GoogleAuth;
property datastoreAdminStub
datastoreAdminStub?: Promise<{ [name: string]: Function }>;
property descriptors
descriptors: Descriptors;
property innerApiCalls
innerApiCalls: { [name: string]: Function };
property operationsClient
operationsClient: gax.OperationsClient;
property port
static readonly port: number;
The port for this API service.
Returns
{number} The default port for this service.
property scopes
static readonly scopes: string[];
The scopes needed to make gRPC calls for every method defined in this service.
Returns
{string[]} List of default scopes.
property servicePath
static readonly servicePath: string;
The DNS address for this API service.
Returns
{string} The DNS address for this service.
Deprecated
Use the apiEndpoint method of the client instance.
property universeDomain
readonly universeDomain: string;
property warn
warn: (code: string, message: string, warnType?: string) => void;
method cancelOperation
cancelOperation: ( request: protos.google.longrunning.CancelOperationRequest, options?: | gax.CallOptions | Callback< protos.google.protobuf.Empty, protos.google.longrunning.CancelOperationRequest, {} | undefined | null >, callback?: Callback< protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} >) => Promise<protos.google.protobuf.Empty>;
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
google.rpc.Code.UNIMPLEMENTED
. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding toCode.CANCELLED
.Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource to be cancelled.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call. {Promise} - The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();await client.cancelOperation({name: ''});
method checkCreateIndexProgress
checkCreateIndexProgress: ( name: string) => Promise< LROperation< protos.google.datastore.admin.v1.Index, protos.google.datastore.admin.v1.IndexOperationMetadata >>;
Check the status of the long running operation returned by
createIndex()
.Parameter name
The operation name that will be passed.
Returns
{Promise} - The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.create_index.js region_tag:datastore_v1_generated_DatastoreAdmin_CreateIndex_async
method checkDeleteIndexProgress
checkDeleteIndexProgress: ( name: string) => Promise< LROperation< protos.google.datastore.admin.v1.Index, protos.google.datastore.admin.v1.IndexOperationMetadata >>;
Check the status of the long running operation returned by
deleteIndex()
.Parameter name
The operation name that will be passed.
Returns
{Promise} - The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.delete_index.js region_tag:datastore_v1_generated_DatastoreAdmin_DeleteIndex_async
method checkExportEntitiesProgress
checkExportEntitiesProgress: ( name: string) => Promise< LROperation< protos.google.datastore.admin.v1.ExportEntitiesResponse, protos.google.datastore.admin.v1.ExportEntitiesMetadata >>;
Check the status of the long running operation returned by
exportEntities()
.Parameter name
The operation name that will be passed.
Returns
{Promise} - The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.export_entities.js region_tag:datastore_v1_generated_DatastoreAdmin_ExportEntities_async
method checkImportEntitiesProgress
checkImportEntitiesProgress: ( name: string) => Promise< LROperation< protos.google.protobuf.Empty, protos.google.datastore.admin.v1.ImportEntitiesMetadata >>;
Check the status of the long running operation returned by
importEntities()
.Parameter name
The operation name that will be passed.
Returns
{Promise} - The promise which resolves to an object. The decoded operation object has result and metadata field to get information from. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.import_entities.js region_tag:datastore_v1_generated_DatastoreAdmin_ImportEntities_async
method close
close: () => Promise<void>;
Terminate the gRPC channel and close the client.
The client will no longer be usable and all future behavior is undefined.
Returns
{Promise} A promise that resolves when the client is closed.
method createIndex
createIndex: { ( request?: protos.google.datastore.admin.v1.ICreateIndexRequest, options?: CallOptions ): Promise< [ LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation | undefined, {} | undefined ] >; ( request: protos.google.datastore.admin.v1.ICreateIndexRequest, options: CallOptions, callback: Callback< LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation, {} > ): void; ( request: protos.google.datastore.admin.v1.ICreateIndexRequest, callback: Callback< LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation, {} > ): void;};
Creates the specified index. A newly created index's initial state is
CREATING
. On completion of the returned google.longrunning.Operation, the state will beREADY
. If the index already exists, the call will return anALREADY_EXISTS
status.During index creation, the process could result in an error, in which case the index will move to the
ERROR
state. The process can be recovered by fixing the data that caused the error, removing the index with delete, then re-creating the index with [create] [google.datastore.admin.v1.DatastoreAdmin.CreateIndex].Indexes with a single property cannot be created.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{google.datastore.admin.v1.Index} request.index The index to create. The name and state fields are output only and will be ignored. Single property indexes cannot be created or deleted.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing a long running operation. Its
promise()
method returns a promise you canawait
for. Please see the documentation for more details and examples.Example 1
include:samples/generated/v1/datastore_admin.create_index.js region_tag:datastore_v1_generated_DatastoreAdmin_CreateIndex_async
method deleteIndex
deleteIndex: { ( request?: protos.google.datastore.admin.v1.IDeleteIndexRequest, options?: CallOptions ): Promise< [ LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation | undefined, {} | undefined ] >; ( request: protos.google.datastore.admin.v1.IDeleteIndexRequest, options: CallOptions, callback: Callback< LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation, {} > ): void; ( request: protos.google.datastore.admin.v1.IDeleteIndexRequest, callback: Callback< LROperation< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IIndexOperationMetadata >, protos.google.longrunning.IOperation, {} > ): void;};
Deletes an existing index. An index can only be deleted if it is in a
READY
orERROR
state. On successful execution of the request, the index will be in aDELETING
state. And on completion of the returned google.longrunning.Operation, the index will be removed.During index deletion, the process could result in an error, in which case the index will move to the
ERROR
state. The process can be recovered by fixing the data that caused the error, followed by calling delete again.Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{string} request.indexId The resource ID of the index to delete.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing a long running operation. Its
promise()
method returns a promise you canawait
for. Please see the documentation for more details and examples.Example 1
include:samples/generated/v1/datastore_admin.delete_index.js region_tag:datastore_v1_generated_DatastoreAdmin_DeleteIndex_async
method deleteOperation
deleteOperation: ( request: protos.google.longrunning.DeleteOperationRequest, options?: | gax.CallOptions | Callback< protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined >, callback?: Callback< protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} >) => Promise<protos.google.protobuf.Empty>;
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns
google.rpc.Code.UNIMPLEMENTED
.Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource to be deleted.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call. {Promise} - The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();await client.deleteOperation({name: ''});
method exportEntities
exportEntities: { ( request?: protos.google.datastore.admin.v1.IExportEntitiesRequest, options?: CallOptions ): Promise< [ LROperation< protos.google.datastore.admin.v1.IExportEntitiesResponse, protos.google.datastore.admin.v1.IExportEntitiesMetadata >, protos.google.longrunning.IOperation | undefined, {} | undefined ] >; ( request: protos.google.datastore.admin.v1.IExportEntitiesRequest, options: CallOptions, callback: Callback< LROperation< protos.google.datastore.admin.v1.IExportEntitiesResponse, protos.google.datastore.admin.v1.IExportEntitiesMetadata >, protos.google.longrunning.IOperation, {} > ): void; ( request: protos.google.datastore.admin.v1.IExportEntitiesRequest, callback: Callback< LROperation< protos.google.datastore.admin.v1.IExportEntitiesResponse, protos.google.datastore.admin.v1.IExportEntitiesMetadata >, protos.google.longrunning.IOperation, {} > ): void;};
Exports a copy of all or a subset of entities from Google Cloud Datastore to another storage system, such as Google Cloud Storage. Recent updates to entities may not be reflected in the export. The export occurs in the background and its progress can be monitored and managed via the Operation resource that is created. The output of an export may only be used once the associated operation is done. If an export operation is cancelled before completion it may leave partial data behind in Google Cloud Storage.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. Project ID against which to make the request.
Parameter
{number[]} request.labels Client-assigned labels.
Parameter
{google.datastore.admin.v1.EntityFilter} request.entityFilter Description of what data from the project is included in the export.
Parameter
{string} request.outputUrlPrefix Required. Location for the export metadata and data files.
The full resource URL of the external storage location. Currently, only Google Cloud Storage is supported. So output_url_prefix should be of the form:
gs://BUCKET_NAME[/NAMESPACE_PATH]
, whereBUCKET_NAME
is the name of the Cloud Storage bucket andNAMESPACE_PATH
is an optional Cloud Storage namespace path (this is not a Cloud Datastore namespace). For more information about Cloud Storage namespace paths, see [Object name considerations](https://cloud.google.com/storage/docs/naming#object-considerations).The resulting files will be nested deeper than the specified URL prefix. The final output URL will be provided in the google.datastore.admin.v1.ExportEntitiesResponse.output_url field. That value should be used for subsequent ImportEntities operations.
By nesting the data files deeper, the same Cloud Storage bucket can be used in multiple ExportEntities operations without conflict.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing a long running operation. Its
promise()
method returns a promise you canawait
for. Please see the documentation for more details and examples.Example 1
include:samples/generated/v1/datastore_admin.export_entities.js region_tag:datastore_v1_generated_DatastoreAdmin_ExportEntities_async
method getIndex
getIndex: { ( request?: protos.google.datastore.admin.v1.IGetIndexRequest, options?: CallOptions ): Promise< [ protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IGetIndexRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.admin.v1.IGetIndexRequest, options: CallOptions, callback: Callback< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IGetIndexRequest, {} > ): void; ( request: protos.google.datastore.admin.v1.IGetIndexRequest, callback: Callback< protos.google.datastore.admin.v1.IIndex, protos.google.datastore.admin.v1.IGetIndexRequest, {} > ): void;};
Gets an index.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{string} request.indexId The resource ID of the index to get.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing Index. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.get_index.js region_tag:datastore_v1_generated_DatastoreAdmin_GetIndex_async
method getOperation
getOperation: ( request: protos.google.longrunning.GetOperationRequest, options?: | gax.CallOptions | Callback< protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined >, callback?: Callback< protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} >) => Promise<[protos.google.longrunning.Operation]>;
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call.
The second parameter to the callback is an object representing google.longrunning.Operation. {Promise} - The promise which resolves to an array. The first element of the array is an object representing google.longrunning.Operation. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();const name = '';const [response] = await client.getOperation({name});// doThingsWith(response)
method getProjectId
getProjectId: { (): Promise<string>; (callback: Callback<string, undefined, undefined>): void;};
method importEntities
importEntities: { ( request?: protos.google.datastore.admin.v1.IImportEntitiesRequest, options?: CallOptions ): Promise< [ LROperation< protos.google.protobuf.IEmpty, protos.google.datastore.admin.v1.IImportEntitiesMetadata >, protos.google.longrunning.IOperation | undefined, {} | undefined ] >; ( request: protos.google.datastore.admin.v1.IImportEntitiesRequest, options: CallOptions, callback: Callback< LROperation< protos.google.protobuf.IEmpty, protos.google.datastore.admin.v1.IImportEntitiesMetadata >, protos.google.longrunning.IOperation, {} > ): void; ( request: protos.google.datastore.admin.v1.IImportEntitiesRequest, callback: Callback< LROperation< protos.google.protobuf.IEmpty, protos.google.datastore.admin.v1.IImportEntitiesMetadata >, protos.google.longrunning.IOperation, {} > ): void;};
Imports entities into Google Cloud Datastore. Existing entities with the same key are overwritten. The import occurs in the background and its progress can be monitored and managed via the Operation resource that is created. If an ImportEntities operation is cancelled, it is possible that a subset of the data has already been imported to Cloud Datastore.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. Project ID against which to make the request.
Parameter
{number[]} request.labels Client-assigned labels.
Parameter
{string} request.inputUrl Required. The full resource URL of the external storage location. Currently, only Google Cloud Storage is supported. So input_url should be of the form:
gs://BUCKET_NAME[/NAMESPACE_PATH]/OVERALL_EXPORT_METADATA_FILE
, whereBUCKET_NAME
is the name of the Cloud Storage bucket,NAMESPACE_PATH
is an optional Cloud Storage namespace path (this is not a Cloud Datastore namespace), andOVERALL_EXPORT_METADATA_FILE
is the metadata file written by the ExportEntities operation. For more information about Cloud Storage namespace paths, see [Object name considerations](https://cloud.google.com/storage/docs/naming#object-considerations).For more information, see google.datastore.admin.v1.ExportEntitiesResponse.output_url.
Parameter
{google.datastore.admin.v1.EntityFilter} request.entityFilter Optionally specify which kinds/namespaces are to be imported. If provided, the list must be a subset of the EntityFilter used in creating the export, otherwise a FAILED_PRECONDITION error will be returned. If no filter is specified then all entities from the export are imported.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing a long running operation. Its
promise()
method returns a promise you canawait
for. Please see the documentation for more details and examples.Example 1
include:samples/generated/v1/datastore_admin.import_entities.js region_tag:datastore_v1_generated_DatastoreAdmin_ImportEntities_async
method initialize
initialize: () => Promise<{ [name: string]: Function }>;
Initialize the client. Performs asynchronous operations (such as authentication) and prepares the client. This function will be called automatically when any class method is called for the first time, but if you need to initialize it before calling an actual method, feel free to call initialize() directly.
You can await on this method if you want to make sure the client is initialized.
Returns
{Promise} A promise that resolves to an authenticated service stub.
method listIndexes
listIndexes: { ( request?: protos.google.datastore.admin.v1.IListIndexesRequest, options?: CallOptions ): Promise< [ protos.google.datastore.admin.v1.IIndex[], protos.google.datastore.admin.v1.IListIndexesRequest | null, protos.google.datastore.admin.v1.IListIndexesResponse ] >; ( request: protos.google.datastore.admin.v1.IListIndexesRequest, options: CallOptions, callback: PaginationCallback< protos.google.datastore.admin.v1.IListIndexesRequest, protos.google.datastore.admin.v1.IListIndexesResponse, protos.google.datastore.admin.v1.IIndex > ): void; ( request: protos.google.datastore.admin.v1.IListIndexesRequest, callback: PaginationCallback< protos.google.datastore.admin.v1.IListIndexesRequest, protos.google.datastore.admin.v1.IListIndexesResponse, protos.google.datastore.admin.v1.IIndex > ): void;};
Lists the indexes that match the specified filters. Datastore uses an eventually consistent query to fetch the list of indexes and may occasionally return stale results.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{string} request.filter
Parameter
{number} request.pageSize The maximum number of items to return. If zero, then all results will be returned.
Parameter
{string} request.pageToken The next_page_token value returned from a previous List request, if any.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is Array of Index. The client library will perform auto-pagination by default: it will call the API as many times as needed and will merge results from all the pages into this array. Note that it can affect your quota. We recommend using
listIndexesAsync()
method described below for async iteration which you can stop as needed. Please see the documentation for more details and examples.
method listIndexesAsync
listIndexesAsync: ( request?: protos.google.datastore.admin.v1.IListIndexesRequest, options?: CallOptions) => AsyncIterable<protos.google.datastore.admin.v1.IIndex>;
Equivalent to
listIndexes
, but returns an iterable object.for
-await
-of
syntax is used with the iterable to get response elements on-demand.Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{string} request.filter
Parameter
{number} request.pageSize The maximum number of items to return. If zero, then all results will be returned.
Parameter
{string} request.pageToken The next_page_token value returned from a previous List request, if any.
Parameter options
Call options. See CallOptions for more details.
Returns
{Object} An iterable Object that allows async iteration. When you iterate the returned iterable, each element will be an object representing Index. The API will be called under the hood as needed, once per the page, so you can stop the iteration when you don't need more results. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore_admin.list_indexes.js region_tag:datastore_v1_generated_DatastoreAdmin_ListIndexes_async
method listIndexesStream
listIndexesStream: ( request?: protos.google.datastore.admin.v1.IListIndexesRequest, options?: CallOptions) => Transform;
Equivalent to
method.name.toCamelCase()
, but returns a NodeJS Stream object.Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Project ID against which to make the request.
Parameter
{string} request.filter
Parameter
{number} request.pageSize The maximum number of items to return. If zero, then all results will be returned.
Parameter
{string} request.pageToken The next_page_token value returned from a previous List request, if any.
Parameter options
Call options. See CallOptions for more details.
Returns
{Stream} An object stream which emits an object representing Index on 'data' event. The client library will perform auto-pagination by default: it will call the API as many times as needed. Note that it can affect your quota. We recommend using
listIndexesAsync()
method described below for async iteration which you can stop as needed. Please see the documentation for more details and examples.
method listOperationsAsync
listOperationsAsync: ( request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions) => AsyncIterable<protos.google.longrunning.ListOperationsResponse>;
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns
UNIMPLEMENTED
. Returns an iterable object.For-await-of syntax is used with the iterable to recursively get response element on-demand.
Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation collection.
Parameter
{string} request.filter - The standard list filter.
Parameter
{number=} request.pageSize - The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Returns
{Object} An iterable Object that conforms to iteration protocols.
Example 1
const client = longrunning.operationsClient();for await (const response of client.listOperationsAsync(request));// doThingsWith(response)
class DatastoreClient
class DatastoreClient {}
Each RPC normalizes the partition IDs of the keys in its input entities, and always returns entities with keys with normalized partition IDs. This applies to all keys and entities, including those in values, except keys with both an empty path and an empty or unset partition ID. Normalization of input keys sets the project ID (if not already set) to the project ID from the request.
v1
constructor
constructor(opts?: ClientOptions, gaxInstance?: any);
Construct an instance of DatastoreClient.
Parameter options
The configuration object. The options accepted by the constructor are described in detail in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). The common options are:
Parameter
{object} [options.credentials] - Credentials object.
Parameter
{string} [options.credentials.client_email]
Parameter
{string} [options.credentials.private_key]
Parameter
{string} [options.email] - Account email address. Required when using a .pem or .p12 keyFilename.
Parameter
{string} [options.keyFilename] - Full path to the a .json, .pem, or .p12 key downloaded from the Google Developers Console. If you provide a path to a JSON file, the projectId option below is not necessary. NOTE: .pem and .p12 require you to specify options.email as well.
Parameter
{number} [options.port] - The port on which to connect to the remote host.
Parameter
{string} [options.projectId] - The project ID from the Google Developer's Console, e.g. 'grape-spaceship-123'. We will also check the environment variable GCLOUD_PROJECT for your project ID. If your app is running in an environment which supports , your project ID will be detected automatically.
Parameter
{string} [options.apiEndpoint] - The domain name of the API remote host.
Parameter
{gax.ClientConfig} [options.clientConfig] - Client configuration override. Follows the structure of gapicConfig.
Parameter
{boolean} [options.fallback] - Use HTTP/1.1 REST mode. For more information, please check the .
Parameter gaxInstance
: loaded instance of
google-gax
. Useful if you need to avoid loading the default gRPC version and want to use the fallback HTTP implementation. Load only fallback version and pass it to the constructor: ``` const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC const client = new DatastoreClient({fallback: true}, gax); ```
property apiEndpoint
static readonly apiEndpoint: string;
The DNS address for this API service - same as servicePath.
Returns
{string} The DNS address for this service.
Deprecated
Use the apiEndpoint method of the client instance.
property apiEndpoint
readonly apiEndpoint: string;
The DNS address for this API service.
Returns
{string} The DNS address for this service.
property auth
auth: gax.GoogleAuth;
property datastoreStub
datastoreStub?: Promise<{ [name: string]: Function }>;
property descriptors
descriptors: Descriptors;
property innerApiCalls
innerApiCalls: { [name: string]: Function };
property operationsClient
operationsClient: gax.OperationsClient;
property port
static readonly port: number;
The port for this API service.
Returns
{number} The default port for this service.
property scopes
static readonly scopes: string[];
The scopes needed to make gRPC calls for every method defined in this service.
Returns
{string[]} List of default scopes.
property servicePath
static readonly servicePath: string;
The DNS address for this API service.
Returns
{string} The DNS address for this service.
Deprecated
Use the apiEndpoint method of the client instance.
property universeDomain
readonly universeDomain: string;
property warn
warn: (code: string, message: string, warnType?: string) => void;
method allocateIds
allocateIds: { ( request?: protos.google.datastore.v1.IAllocateIdsRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IAllocateIdsResponse, protos.google.datastore.v1.IAllocateIdsRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IAllocateIdsRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IAllocateIdsResponse, protos.google.datastore.v1.IAllocateIdsRequest, {} > ): void; ( request: protos.google.datastore.v1.IAllocateIdsRequest, callback: Callback< protos.google.datastore.v1.IAllocateIdsResponse, protos.google.datastore.v1.IAllocateIdsRequest, {} > ): void;};
Allocates IDs for the given keys, which is useful for referencing an entity before it is inserted.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{number[]} request.keys Required. A list of keys with incomplete key paths for which to allocate IDs. No key may be reserved/read-only.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing AllocateIdsResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.allocate_ids.js region_tag:datastore_v1_generated_Datastore_AllocateIds_async
method beginTransaction
beginTransaction: { ( request?: protos.google.datastore.v1.IBeginTransactionRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IBeginTransactionResponse, protos.google.datastore.v1.IBeginTransactionRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IBeginTransactionRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IBeginTransactionResponse, protos.google.datastore.v1.IBeginTransactionRequest, {} > ): void; ( request: protos.google.datastore.v1.IBeginTransactionRequest, callback: Callback< protos.google.datastore.v1.IBeginTransactionResponse, protos.google.datastore.v1.IBeginTransactionRequest, {} > ): void;};
Begins a new transaction.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{google.datastore.v1.TransactionOptions} request.transactionOptions Options for a new transaction.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing BeginTransactionResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.begin_transaction.js region_tag:datastore_v1_generated_Datastore_BeginTransaction_async
method cancelOperation
cancelOperation: ( request: protos.google.longrunning.CancelOperationRequest, options?: | gax.CallOptions | Callback< protos.google.protobuf.Empty, protos.google.longrunning.CancelOperationRequest, {} | undefined | null >, callback?: Callback< protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} >) => Promise<protos.google.protobuf.Empty>;
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
google.rpc.Code.UNIMPLEMENTED
. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding toCode.CANCELLED
.Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource to be cancelled.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call. {Promise} - The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();await client.cancelOperation({name: ''});
method close
close: () => Promise<void>;
Terminate the gRPC channel and close the client.
The client will no longer be usable and all future behavior is undefined.
Returns
{Promise} A promise that resolves when the client is closed.
method commit
commit: { ( request?: protos.google.datastore.v1.ICommitRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.ICommitResponse, protos.google.datastore.v1.ICommitRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.ICommitRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.ICommitResponse, protos.google.datastore.v1.ICommitRequest, {} > ): void; ( request: protos.google.datastore.v1.ICommitRequest, callback: Callback< protos.google.datastore.v1.ICommitResponse, protos.google.datastore.v1.ICommitRequest, {} > ): void;};
Commits a transaction, optionally creating, deleting or modifying some entities.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{google.datastore.v1.CommitRequest.Mode} request.mode The type of commit to perform. Defaults to
TRANSACTIONAL
.Parameter
{Buffer} request.transaction The identifier of the transaction associated with the commit. A transaction identifier is returned by a call to Datastore.BeginTransaction.
Parameter
{google.datastore.v1.TransactionOptions} request.singleUseTransaction Options for beginning a new transaction for this request. The transaction is committed when the request completes. If specified, TransactionOptions.mode must be TransactionOptions.ReadWrite.
Parameter
{number[]} request.mutations The mutations to perform.
When mode is
TRANSACTIONAL
, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a singleCommit
request:-
insert
followed byinsert
-update
followed byinsert
-upsert
followed byinsert
-delete
followed byupdate
When mode is
NON_TRANSACTIONAL
, no two mutations may affect a single entity.Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing CommitResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.commit.js region_tag:datastore_v1_generated_Datastore_Commit_async
method deleteOperation
deleteOperation: ( request: protos.google.longrunning.DeleteOperationRequest, options?: | gax.CallOptions | Callback< protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined >, callback?: Callback< protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} >) => Promise<protos.google.protobuf.Empty>;
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns
google.rpc.Code.UNIMPLEMENTED
.Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource to be deleted.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call. {Promise} - The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();await client.deleteOperation({name: ''});
method getOperation
getOperation: ( request: protos.google.longrunning.GetOperationRequest, options?: | gax.CallOptions | Callback< protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined >, callback?: Callback< protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} >) => Promise<[protos.google.longrunning.Operation]>;
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation resource.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Parameter callback
The function which will be called with the result of the API call.
The second parameter to the callback is an object representing google.longrunning.Operation. {Promise} - The promise which resolves to an array. The first element of the array is an object representing google.longrunning.Operation. The promise has a method named "cancel" which cancels the ongoing API call.
Example 1
const client = longrunning.operationsClient();const name = '';const [response] = await client.getOperation({name});// doThingsWith(response)
method getProjectId
getProjectId: { (): Promise<string>; (callback: Callback<string, undefined, undefined>): void;};
method initialize
initialize: () => Promise<{ [name: string]: Function }>;
Initialize the client. Performs asynchronous operations (such as authentication) and prepares the client. This function will be called automatically when any class method is called for the first time, but if you need to initialize it before calling an actual method, feel free to call initialize() directly.
You can await on this method if you want to make sure the client is initialized.
Returns
{Promise} A promise that resolves to an authenticated service stub.
method listOperationsAsync
listOperationsAsync: ( request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions) => AsyncIterable<protos.google.longrunning.ListOperationsResponse>;
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns
UNIMPLEMENTED
. Returns an iterable object.For-await-of syntax is used with the iterable to recursively get response element on-demand.
Parameter request
The request object that will be sent.
Parameter
{string} request.name - The name of the operation collection.
Parameter
{string} request.filter - The standard list filter.
Parameter
{number=} request.pageSize - The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.
Parameter options
Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.
Returns
{Object} An iterable Object that conforms to iteration protocols.
Example 1
const client = longrunning.operationsClient();for await (const response of client.listOperationsAsync(request));// doThingsWith(response)
method lookup
lookup: { ( request?: protos.google.datastore.v1.ILookupRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.ILookupResponse, protos.google.datastore.v1.ILookupRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.ILookupRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.ILookupResponse, protos.google.datastore.v1.ILookupRequest, {} > ): void; ( request: protos.google.datastore.v1.ILookupRequest, callback: Callback< protos.google.datastore.v1.ILookupResponse, protos.google.datastore.v1.ILookupRequest, {} > ): void;};
Looks up entities by key.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{google.datastore.v1.ReadOptions} request.readOptions The options for this lookup request.
Parameter
{number[]} request.keys Required. Keys of entities to look up.
Parameter
{google.datastore.v1.PropertyMask} request.propertyMask The properties to return. Defaults to returning all properties.
If this field is set and an entity has a property not referenced in the mask, it will be absent from .
The entity's key is always returned.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing LookupResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.lookup.js region_tag:datastore_v1_generated_Datastore_Lookup_async
method reserveIds
reserveIds: { ( request?: protos.google.datastore.v1.IReserveIdsRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IReserveIdsResponse, protos.google.datastore.v1.IReserveIdsRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IReserveIdsRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IReserveIdsResponse, protos.google.datastore.v1.IReserveIdsRequest, {} > ): void; ( request: protos.google.datastore.v1.IReserveIdsRequest, callback: Callback< protos.google.datastore.v1.IReserveIdsResponse, protos.google.datastore.v1.IReserveIdsRequest, {} > ): void;};
Prevents the supplied keys' IDs from being auto-allocated by Cloud Datastore.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{number[]} request.keys Required. A list of keys with complete key paths whose numeric IDs should not be auto-allocated.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing ReserveIdsResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.reserve_ids.js region_tag:datastore_v1_generated_Datastore_ReserveIds_async
method rollback
rollback: { ( request?: protos.google.datastore.v1.IRollbackRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IRollbackResponse, protos.google.datastore.v1.IRollbackRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IRollbackRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IRollbackResponse, protos.google.datastore.v1.IRollbackRequest, {} > ): void; ( request: protos.google.datastore.v1.IRollbackRequest, callback: Callback< protos.google.datastore.v1.IRollbackResponse, protos.google.datastore.v1.IRollbackRequest, {} > ): void;};
Rolls back a transaction.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{Buffer} request.transaction Required. The transaction identifier, returned by a call to Datastore.BeginTransaction.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing RollbackResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.rollback.js region_tag:datastore_v1_generated_Datastore_Rollback_async
method runAggregationQuery
runAggregationQuery: { ( request?: protos.google.datastore.v1.IRunAggregationQueryRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IRunAggregationQueryResponse, protos.google.datastore.v1.IRunAggregationQueryRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IRunAggregationQueryRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IRunAggregationQueryResponse, protos.google.datastore.v1.IRunAggregationQueryRequest, {} > ): void; ( request: protos.google.datastore.v1.IRunAggregationQueryRequest, callback: Callback< protos.google.datastore.v1.IRunAggregationQueryResponse, protos.google.datastore.v1.IRunAggregationQueryRequest, {} > ): void;};
Runs an aggregation query.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{google.datastore.v1.PartitionId} request.partitionId Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID.
Parameter
{google.datastore.v1.ReadOptions} request.readOptions The options for this query.
Parameter
{google.datastore.v1.AggregationQuery} request.aggregationQuery The query to run.
Parameter
{google.datastore.v1.GqlQuery} request.gqlQuery The GQL query to run. This query must be an aggregation query.
Parameter
{google.datastore.v1.ExplainOptions} [request.explainOptions] Optional. Explain options for the query. If set, additional query statistics will be returned. If not, only query results will be returned.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing RunAggregationQueryResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.run_aggregation_query.js region_tag:datastore_v1_generated_Datastore_RunAggregationQuery_async
method runQuery
runQuery: { ( request?: protos.google.datastore.v1.IRunQueryRequest, options?: CallOptions ): Promise< [ protos.google.datastore.v1.IRunQueryResponse, protos.google.datastore.v1.IRunQueryRequest | undefined, {} | undefined ] >; ( request: protos.google.datastore.v1.IRunQueryRequest, options: CallOptions, callback: Callback< protos.google.datastore.v1.IRunQueryResponse, protos.google.datastore.v1.IRunQueryRequest, {} > ): void; ( request: protos.google.datastore.v1.IRunQueryRequest, callback: Callback< protos.google.datastore.v1.IRunQueryResponse, protos.google.datastore.v1.IRunQueryRequest, {} > ): void;};
Queries for entities.
Parameter request
The request object that will be sent.
Parameter
{string} request.projectId Required. The ID of the project against which to make the request.
Parameter
{string} request.databaseId The ID of the database against which to make the request.
'(default)' is not allowed; please use empty string '' to refer the default database.
Parameter
{google.datastore.v1.PartitionId} request.partitionId Entities are partitioned into subsets, identified by a partition ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID.
Parameter
{google.datastore.v1.ReadOptions} request.readOptions The options for this query.
Parameter
{google.datastore.v1.Query} request.query The query to run.
Parameter
{google.datastore.v1.GqlQuery} request.gqlQuery The GQL query to run. This query must be a non-aggregation query.
Parameter
{google.datastore.v1.PropertyMask} request.propertyMask The properties to return. This field must not be set for a projection query.
Parameter
{google.datastore.v1.ExplainOptions} [request.explainOptions] Optional. Explain options for the query. If set, additional query statistics will be returned. If not, only query results will be returned.
Parameter options
Call options. See CallOptions for more details.
Returns
{Promise} - The promise which resolves to an array. The first element of the array is an object representing RunQueryResponse. Please see the documentation for more details and examples.
Example 1
include:samples/generated/v1/datastore.run_query.js region_tag:datastore_v1_generated_Datastore_RunQuery_async
class DatastoreRequest
class DatastoreRequest {}
Handle logic for Datastore API operations. Handles request logic for Datastore.
Creates requests to the Datastore endpoint. Designed to be inherited by the Datastore and Transaction classes.
property datastore
datastore: Datastore;
property id
id: string | Uint8Array;
property requestCallbacks_
requestCallbacks_: any;
property requests_
requests_: any;
property state
protected state: TransactionState;
method allocateIds
allocateIds: { ( key: entity.Key, options: AllocateIdsOptions | number ): Promise<AllocateIdsResponse>; ( key: entity.Key, options: number | AllocateIdsOptions, callback: AllocateIdsCallback ): void;};
Generate IDs without creating entities.
Parameter key
The key object to complete.
Parameter options
Either the number of IDs to allocate or an options object for further customization of the request.
Parameter
{number} options.allocations How many IDs to allocate.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{array} callback.keys The generated IDs
Parameter
{object} callback.apiResponse The full API response.
Example 1
const incompleteKey = datastore.key(['Company']);//-// The following call will create 100 new IDs from the Company kind, which// exists under the default namespace.//-datastore.allocateIds(incompleteKey, 100, (err, keys) => {});//-// Or, if you're using a transaction object.//-const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.allocateIds(incompleteKey, 100, (err, keys) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});//-// You may prefer to create IDs from a non-default namespace by providingan// incomplete key with a namespace. Similar to the previous example, thecall// below will create 100 new IDs, but from the Company kind that existsunder// the "ns-test" namespace.//-const incompleteKey = datastore.key({namespace: 'ns-test',path: ['Company']});function callback(err, keys, apiResponse) {}datastore.allocateIds(incompleteKey, 100, callback);//-// Returns a Promise if callback is omitted.//-datastore.allocateIds(incompleteKey, 100).then((data) => {const keys = data[0];const apiResponse = data[1];});
method checkExpired
protected checkExpired: () => void;
method createReadStream
createReadStream: ( keys: Entities, options?: CreateReadStreamOptions) => Transform;
Retrieve the entities as a readable object stream.
Parameter keys
Datastore key object(s).
Parameter options
Optional configuration. See Datastore#get for a complete list of options.
Throws
{Error} If at least one Key object is not provided.
Throws
{Error} If read time and read consistency cannot both be specified.
Example 1
const keys = [datastore.key(['Company', 123]),datastore.key(['Product', 'Computer'])];datastore.createReadStream(keys).on('error', (err) => {}).on('data', (entity) => {// entity is an entity object.}).on('end', () => {// All entities retrieved.});
method delete
delete: { (keys: Entities, gaxOptions?: CallOptions): Promise<DeleteResponse>; (keys: any, callback: CommitCallback): void; (keys: any, gaxOptions: CallOptions, callback: CommitCallback): void;};
Delete all entities identified with the specified key(s).
Parameter key
Datastore key object(s).
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
Example 1
const key = datastore.key(['Company', 123]);datastore.delete(key, (err, apiResp) => {});//-// Or, if you're using a transaction object.//-const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.delete(key);transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});//-// Delete multiple entities at once.//-datastore.delete([datastore.key(['Company', 123]),datastore.key(['Product', 'Computer'])], (err, apiResponse) => {});//-// Returns a Promise if callback is omitted.//-datastore.delete().then((data) => {const apiResponse = data[0];});
method get
get: { ( keys: entity.Key | entity.Key[], options?: CreateReadStreamOptions ): Promise<GetResponse>; (keys: entity.Key | entity.Key[], callback: GetCallback): void; ( keys: entity.Key | entity.Key[], options: RunQueryOptions, callback: GetCallback ): void;};
Retrieve the entities identified with the specified key(s) in the current transaction. Get operations require a valid key to retrieve the key-identified entity from Datastore.
Parameter keys
Datastore key object(s).
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strong
oreventual
. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean
, this will wrap values in Datastore#Int objects. If anobject
, this will return a value returned bywrapNumbers.integerTypeCastFunction
. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object|object[]} callback.entity The entity object(s) which match the provided keys.
Throws
{Error} If at least one Key object is not provided.
Example 1
//-// Get a single entity.//-const key = datastore.key(['Company', 123]);datastore.get(key, (err, entity) => {});//-// Or, if you're using a transaction object.//-const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.get(key, (err, entity) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});//-// Get multiple entities at once with a callback.//-const keys = [datastore.key(['Company', 123]),datastore.key(['Product', 'Computer'])];datastore.get(keys, (err, entities) => {});//-// Below is how to update the value of an entity with the help of the// `save` method.//-datastore.get(key, (err, entity) => {if (err) {// Error handling omitted.}entity.newValue = true;datastore.save({key: key,data: entity}, (err) => {});});//-// Returns a Promise if callback is omitted.//-datastore.get(keys).then((data) => {const entities = data[0];});
method merge
merge: { (entities: Entities): Promise<CommitResponse>; (entities: any, callback: CommitCallback): void;};
Merge the specified object(s). If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be get the data from datastore and merge with the data specified. By default, all properties are indexed. To prevent a property from being included in *all* indexes, you must supply an
excludeFromIndexes
array.Maps to Datastore#save, forcing the method to be
upsert
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to merge to the same for provided key.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
method parseTransactionResponse
protected parseTransactionResponse: (resp?: { transaction?: Uint8Array | string | undefined | null;}) => void;
This function saves results from a successful beginTransaction call.
Parameter response
The response from a call to begin a transaction that completed successfully.
method prepareGaxRequest_
prepareGaxRequest_: (config: RequestConfig, callback: Function) => void;
method request_
request_: (config: RequestConfig, callback: RequestCallback) => void;
Make a request to the API endpoint. Properties to indicate a transactional or non-transactional operation are added automatically.
Parameter config
Configuration object.
Parameter
{object} config.gaxOpts GAX options.
Parameter
{string} config.client The name of the gax client.
Parameter
{function} config.method The gax method to call.
Parameter
{object} config.reqOpts Request options.
Parameter callback
The callback function.
method requestStream_
requestStream_: (config: RequestConfig) => AbortableDuplex;
Make a request as a stream.
Parameter config
Configuration object.
Parameter
{object} config.gaxOpts GAX options.
Parameter
{string} config.client The name of the gax client.
Parameter
{string} config.method The gax method to call.
Parameter
{object} config.reqOpts Request options.
method runAggregationQuery
runAggregationQuery: { ( query: AggregateQuery, options?: RunQueryOptions ): Promise<RunQueryResponse>; ( query: AggregateQuery, options: RunQueryOptions, callback: RunAggregationQueryCallback ): void; (query: AggregateQuery, callback: RunAggregationQueryCallback): void;};
Datastore allows you to run aggregate queries by supplying aggregate fields which will determine the type of aggregation that is performed.
The query is run, and the results are returned in the second argument of the callback provided.
Parameter query
AggregateQuery object.
Parameter options
Optional configuration
Parameter callback
The callback function. If omitted, a promise is returned.
Throws
{Error} If read time and read consistency cannot both be specified.
method runQuery
runQuery: { (query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>; (query: Query, options: RunQueryOptions, callback: RunQueryCallback): void; (query: Query, callback: RunQueryCallback): void;};
Datastore allows you to query entities by kind, filter them by property filters, and sort them by a property name. Projection and pagination are also supported.
The query is run, and the results are returned as the second argument to your callback. A third argument may also exist, which is a query object that uses the end cursor from the previous query as the starting cursor for the next query. You can pass that object back to this method to see if more results exist.
Parameter query
Query object.
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strong
oreventual
. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean
, this will wrap values in Datastore#Int objects. If anobject
, this will return a value returned bywrapNumbers.integerTypeCastFunction
. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function. If omitted, a readable stream instance is returned.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object[]} callback.entities A list of entities.
Parameter
{object} callback.info An object useful for pagination.
Parameter
{?string} callback.info.endCursor Use this in a follow-up query to begin from where these results ended.
Parameter
{string} callback.info.moreResults Datastore responds with one of:
- Datastore#MORE_RESULTS_AFTER_LIMIT: There *may* be more results after the specified limit. - Datastore#MORE_RESULTS_AFTER_CURSOR: There *may* be more results after the specified end cursor. - Datastore#NO_MORE_RESULTS: There are no more results.
Example 1
//-// Where you see `transaction`, assume this is the context that's relevantto// your use, whether that be a Datastore or a Transaction object.//-const query = datastore.createQuery('Lion');datastore.runQuery(query, (err, entities, info) => {// entities = An array of records.// Access the Key object for an entity.const firstEntityKey = entities[0][datastore.KEY];});//-// Or, if you're using a transaction object.//-const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.runQuery(query, (err, entities) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});//-// A keys-only query returns just the keys of the result entities insteadof// the entities themselves, at lower latency and cost.//-const keysOnlyQuery = datastore.createQuery('Lion').select('__key__');datastore.runQuery(keysOnlyQuery, (err, entities) => {const keys = entities.map((entity) => {return entity[datastore.KEY];});});//-// Returns a Promise if callback is omitted.//-datastore.runQuery(query).then((data) => {const entities = data[0];});
method runQueryStream
runQueryStream: (query: Query, options?: RunQueryStreamOptions) => Transform;
Get a list of entities as a readable object stream.
See Datastore#runQuery for a list of all available options.
Parameter query
Query object.
Parameter options
Optional configuration.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Throws
{Error} If read time and read consistency cannot both be specified.
Example 1
datastore.runQueryStream(query).on('error', console.error).on('data', (entity) => {// Access the Key object for this entity.const key = entity[datastore.KEY];}).on('info', (info) => {}).on('end', () => {// All entities retrieved.});//-// If you anticipate many results, you can end a stream early to prevent// unnecessary processing and API requests.//-datastore.runQueryStream(query).on('data', (entity) => {this.end();});
class Index
class Index {}
Parameter datastore
The parent instance of this index.
Parameter id
The index name or id.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const index = datastore.index('my-index');
constructor
constructor(datastore: Datastore, id: string);
property datastore
datastore: Datastore;
property id
id: string;
property metadata
metadata?: google.datastore.admin.v1.IIndex;
method get
get: { (gaxOptions?: CallOptions): Promise<GetIndexResponse>; (callback: GetIndexCallback): void; (gaxOptions: CallOptions, callback: GetIndexCallback): void;};
Get an index if it exists.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Index} callback.index The Index instance.
Parameter
{object} callback.apiResponse The full API response.
method getMetadata
getMetadata: { (gaxOptions?: CallOptions): Promise<IndexGetMetadataResponse>; (callback: IndexGetMetadataCallback): void; (gaxOptions: CallOptions, callback: IndexGetMetadataCallback): void;};
Get the metadata of this index.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{object} callback.metadata The metadata.
class PropertyFilter
class PropertyFilter<T extends string> extends EntityFilter implements IFilter {}
A PropertyFilter is a filter that gets applied to a query directly.
See Also
constructor
constructor(name: string, op: Operator, val: {});
Build a Property Filter object.
Parameter Property
Parameter operator
Parameter val
property name
name: string;
property op
op: Operator;
property val
val: {};
method toProto
toProto: () => any;
Gets the proto for the filter.
class Query
class Query {}
Build a Query object.
**Queries are built with {module:datastore#createQuery} and Transaction#createQuery.**
Parameter scope
The parent scope the query was created from.
Parameter namespace
Namespace to query entities from.
Parameter kinds
Kind to query.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('AnimalNamespace', 'Lion');See Also
constructor
constructor(scope?: Transaction | Datastore, kinds?: string[]);
constructor
constructor( scope?: Transaction | Datastore, namespace?: string, kinds?: string[]);
property endVal
endVal: any;
property entityFilters
entityFilters: EntityFilter[];
property filters
filters: Filter[];
property groupByVal
groupByVal: {}[];
property kinds
kinds: string[];
property limitVal
limitVal: number;
property namespace
namespace?: string;
property offsetVal
offsetVal: number;
property orders
orders: Order[];
property scope
scope?: Transaction | Datastore;
property selectVal
selectVal: {}[];
property startVal
startVal: any;
method end
end: (end: string | Buffer) => this;
Set an ending cursor to a query.
Parameter cursorToken
The ending cursor token.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');const cursorToken = 'X';// Retrieve results limited to the extent of cursorToken.const endQuery = companyQuery.end(cursorToken);See Also
method filter
filter: { (filter: EntityFilter): Query; <T extends string>(property: T, value: AllowedFilterValueType<T>): Query; <T extends string>( property: T, operator: Operator, value: AllowedFilterValueType<T> ): Query;};
Datastore allows querying on properties. Supported comparison operators are
=
,<
,>
,<=
,>=
,!=
,HAS_ANCESTOR
,IN
andNOT_IN
.*To filter by ancestors, see {module:datastore/query#hasAncestor}.*
Parameter propertyOrFilter
The field name.
Parameter operator
Operator (=, <, >, <=, >=).
Parameter value
Value to compare property to.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');//-// List all companies that are located in California.//-const caliQuery = query.filter('state', 'CA');//-// List all companies named Google that have less than 400 employees.//-const companyQuery = query.filter('name', 'Google').filter('size', '<', 400);//-// To filter by key, use `__key__` for the property name. Filter on keys// stored as properties is not currently supported.//-const key = datastore.key(['Company', 'Google']);const keyQuery = query.filter('__key__', key);See Also
method groupBy
groupBy: (fieldNames: string | string[]) => this;
Group query results by a list of properties.
Parameter properties
Properties to group by.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');const groupedQuery = companyQuery.groupBy(['name', 'size']);
method hasAncestor
hasAncestor: (key: Key) => this;
Filter a query by ancestors.
Parameter key
Key object to filter by.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('MyKind');const ancestoryQuery = query.hasAncestor(datastore.key(['Parent', 123]));See Also
method limit
limit: (n: number) => this;
Set a limit on a query.
Parameter n
The number of results to limit the query to.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');// Limit the results to 10 entities.const limitQuery = companyQuery.limit(10);See Also
method offset
offset: (n: number) => this;
Set an offset on a query.
Parameter n
The offset to start from after the start cursor.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');// Start from the 101st result.const offsetQuery = companyQuery.offset(100);See Also
method order
order: (property: string, options?: OrderOptions) => this;
Sort the results by a property name in ascending or descending order. By default, an ascending sort order will be used.
Parameter property
The property to order by.
Parameter options
Options object.
Parameter
{boolean} [options.descending=false] Sort the results by a property name in descending order.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');// Sort by size ascendingly.const companiesAscending = companyQuery.order('size');// Sort by size descendingly.const companiesDescending = companyQuery.order('size', {descending: true});See Also
method run
run: { (options?: RunQueryOptions): Promise<RunQueryResponse>; (options: RunQueryOptions, callback: RunQueryCallback): void; (callback: RunQueryCallback): void;};
Run the query.
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strong
oreventual
. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean
, this will wrap values in Datastore#Int objects. If anobject
, this will return a value returned bywrapNumbers.integerTypeCastFunction
. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function. If omitted, a readable stream instance is returned.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object[]} callback.entities A list of entities.
Parameter
{object} callback.info An object useful for pagination.
Parameter
{?string} callback.info.endCursor Use this in a follow-up query to begin from where these results ended.
Parameter
{string} callback.info.moreResults Datastore responds with one of:
- Datastore#MORE_RESULTS_AFTER_LIMIT: There *may* be more results after the specified limit. - Datastore#MORE_RESULTS_AFTER_CURSOR: There *may* be more results after the specified end cursor. - Datastore#NO_MORE_RESULTS: There are no more results.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');query.run((err, entities, info) => {// entities = An array of records.// Access the Key object for an entity.const firstEntityKey = entities[0][datastore.KEY];});//-// A keys-only query returns just the keys of the result entities insteadof// the entities themselves, at lower latency and cost.//-query.select('__key__');query.run((err, entities) => {const keys = entities.map((entity) => {return entity[datastore.KEY];});});//-// If the callback is omitted, we'll return a Promise.//-query.run().then((data) => {const entities = data[0];});
method runStream
runStream: (options?: RunQueryStreamOptions) => any;
Run the query as a readable object stream.
Query#runStream
Parameter options
Optional configuration. See Query#run for a complete list of options.
Returns
{stream}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');query.runStream().on('error', console.error).on('data', function (entity) {// Access the Key object for this entity.const key = entity[datastore.KEY];}).on('info', (info) => {}).on('end', () => {// All entities retrieved.});//-// If you anticipate many results, you can end a stream early to prevent// unnecessary processing and API requests.//-query.runStream().on('data', function (entity) {this.end();});
method select
select: (fieldNames: string | string[]) => this;
Retrieve only select properties from the matched entities.
Queries that select a subset of properties are called Projection Queries.
Parameter fieldNames
Properties to return from the matched entities.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');// Only retrieve the name property.const selectQuery = companyQuery.select('name');// Only retrieve the name and size properties.const selectQuery = companyQuery.select(['name', 'size']);See Also
method start
start: (start: string | Buffer) => this;
Set a starting cursor to a query.
Parameter cursorToken
The starting cursor token.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const companyQuery = datastore.createQuery('Company');const cursorToken = 'X';// Retrieve results starting from cursorToken.const startQuery = companyQuery.start(cursorToken);See Also
class Transaction
class Transaction extends DatastoreRequest {}
A transaction is a set of Datastore operations on one or more entities. Each transaction is guaranteed to be atomic, which means that transactions are never partially applied. Either all of the operations in the transaction are applied, or none of them are applied.
Parameter datastore
A Datastore instance. module:datastore/request
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();See Also
{Request}
constructor
constructor(datastore: Datastore, options?: TransactionOptions);
property modifiedEntities_
modifiedEntities_: ModifiedEntities;
property namespace
namespace?: string;
property readOnly
readOnly: boolean;
property request
request: Function;
property skipCommit
skipCommit?: boolean;
method commit
commit: { (gaxOptions?: CallOptions): Promise<CommitResponse>; (callback: CommitCallback): void; (gaxOptions: CallOptions, callback: CommitCallback): void;};
Commit the remote transaction and finalize the current transaction instance.
If the commit request fails, we will automatically rollback the transaction.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request. If the commit fails, we automatically try to rollback the transaction (see {module:datastore/transaction#rollback}).
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.commit((err, apiResponse) => {if (err) {// Transaction could not be committed.}});//-// If the callback is omitted, we'll return a Promise.//-transaction.commit().then((data) => {const apiResponse = data[0];});
method createAggregationQuery
createAggregationQuery: (query: Query) => AggregateQuery;
Create an aggregation query from the query specified. See {module:datastore/query} for all of the available methods.
method createQuery
createQuery: { (kind?: string): Query; (kind?: string[]): Query; (namespace: string, kind: string): Query; (namespace: string, kind: string[]): Query;};
Create a query for the specified kind. See {module:datastore/query} for all of the available methods.
Parameter namespace
Namespace.
Parameter kind
The kind to query.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();// Run the query inside the transaction.transaction.run((err) => {if (err) {// Error handling omitted.}const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);const query = transaction.createQuery('Company').hasAncestor(ancestorKey);query.run((err, entities) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});// Run the query inside the transaction.with namespacetransaction.run((err) => {if (err) {// Error handling omitted.}const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);const query = transaction.createQuery('CompanyNamespace', 'Company').hasAncestor(ancestorKey);query.run((err, entities) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});See Also
method delete
delete: (entities?: Entities) => any;
Delete all entities identified with the specified key(s) in the current transaction.
Parameter key
Datastore key object(s).
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}// Delete a single entity.transaction.delete(datastore.key(['Company', 123]));// Delete multiple entities at once.transaction.delete([datastore.key(['Company', 123]),datastore.key(['Product', 'Computer'])]);transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});
method get
get: { ( keys: entity.Key | entity.Key[], options?: CreateReadStreamOptions ): Promise<GetResponse>; (keys: entity.Key | entity.Key[], callback: GetCallback): void; ( keys: entity.Key | entity.Key[], options: RunQueryOptions, callback: GetCallback ): void;};
This function calls get on the super class. If the transaction has not been started yet then the transaction is started before the get call is made.
Parameter keys
Datastore key object(s).
Parameter options
Optional configuration.
Parameter callback
The callback function.
method insert
insert: (entities: Entities) => void;
Maps to Datastore#save, forcing the method to be
insert
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
method rollback
rollback: { (callback: RollbackCallback): void; (gaxOptions?: CallOptions): Promise<RollbackResponse>; (gaxOptions: CallOptions, callback: RollbackCallback): void;};
Reverse a transaction remotely and finalize the current transaction instance.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.rollback((err) => {if (!err) {// Transaction rolled back successfully.}});});//-// If the callback is omitted, we'll return a Promise.//-transaction.rollback().then((data) => {const apiResponse = data[0];});
method run
run: { (options?: RunOptions): Promise<RunResponse>; (callback: RunCallback): void; (options: RunOptions, callback: RunCallback): void;};
Begin a remote transaction. In the callback provided, run your transactional commands.
Parameter options
Configuration object.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean} [options.readOnly=false] A read-only transaction cannot modify entities.
Parameter
{string} [options.transactionId] The ID of a previous transaction.
Parameter callback
The function to execute within the context of a transaction.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Transaction} callback.transaction This transaction instance.
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.run((err, transaction) => {// Perform Datastore transactional operations.const key = datastore.key(['Company', 123]);transaction.get(key, (err, entity) => {entity.name = 'Google';transaction.save({key: key,data: entity});transaction.commit((err) => {if (!err) {// Data saved successfully.}});});});//-// If the callback is omitted, we'll return a Promise.//-transaction.run().then((data) => {const transaction = data[0];const apiResponse = data[1];});
method runAggregationQuery
runAggregationQuery: { ( query: AggregateQuery, options?: RunQueryOptions ): Promise<RunQueryResponse>; ( query: AggregateQuery, options: RunQueryOptions, callback: RequestCallback ): void; (query: AggregateQuery, callback: RequestCallback): void;};
This function calls runAggregationQuery on the super class. If the transaction has not been started yet then the transaction is started before the runAggregationQuery call is made.
Parameter query
AggregateQuery object.
Parameter options
Optional configuration
Parameter callback
The callback function. If omitted, a promise is returned.
method runQuery
runQuery: { (query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>; (query: Query, options: RunQueryOptions, callback: RunQueryCallback): void; (query: Query, callback: RunQueryCallback): void;};
This function calls runQuery on the super class. If the transaction has not been started yet then the transaction is started before the runQuery call is made.
Parameter query
Query object.
Parameter options
Optional configuration.
Parameter callback
The callback function. If omitted, a readable stream instance is returned.
method save
save: (entities: Entities) => void;
Insert or update the specified object(s) in the current transaction. If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID.
This method will determine the correct Datastore method to execute (
upsert
,insert
, orupdate
) by using the key(s) provided. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be updated with the data specified.By default, all properties are indexed. To prevent a property from being included in *all* indexes, you must supply an
excludeFromIndexes
array. See below for an example.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the example below to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
Example 1
<caption>Save a single entity.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();// Notice that we are providing an incomplete key. After the transaction is// committed, the Key object held by the `key` variable will be populated// with a path containing its generated ID.//-const key = datastore.key('Company');transaction.run((err) => {if (err) {// Error handling omitted.}transaction.save({key: key,data: {rating: '10'}});transaction.commit((err) => {if (!err) {// Data saved successfully.}});});Example 2
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();// Use an array, `excludeFromIndexes`, to exclude properties from indexing.// This will allow storing string values larger than 1500 bytes.transaction.run((err) => {if (err) {// Error handling omitted.}transaction.save({key: key,excludeFromIndexes: ['description','embeddedEntity.description','arrayValue[].description'],data: {description: 'Long string (...)',embeddedEntity: {description: 'Long string (...)'},arrayValue: [{description: 'Long string (...)'}]}});transaction.commit((err) => {if (!err) {// Data saved successfully.}});});Example 3
<caption>Save multiple entities at once.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();const companyKey = datastore.key(['Company', 123]);const productKey = datastore.key(['Product', 'Computer']);transaction.run((err) => {if (err) {// Error handling omitted.}transaction.save([{key: companyKey,data: {HQ: 'Dallas, TX'}},{key: productKey,data: {vendor: 'Dell'}}]);transaction.commit((err) => {if (!err) {// Data saved successfully.}});});
method update
update: (entities: Entities) => void;
Maps to Datastore#save, forcing the method to be
update
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
method upsert
upsert: (entities: Entities) => void;
Maps to Datastore#save, forcing the method to be
upsert
.Parameter entities
Datastore key object(s).
Parameter
{Key} entities.key Datastore key object.
Parameter
{string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.
Parameter
{object} entities.data Data to save with the provided key.
Interfaces
interface BooleanObject
interface BooleanObject {}
index signature
[key: string]: boolean;
interface DatastoreOptions
interface DatastoreOptions extends GoogleAuthOptions {}
property apiEndpoint
apiEndpoint?: string;
property databaseId
databaseId?: string;
property fallback
fallback?: Fallback;
property namespace
namespace?: string;
property sslCreds
sslCreds?: ChannelCredentials;
interface EntityProtoReduceAccumulator
interface EntityProtoReduceAccumulator {}
index signature
[key: string]: ValueProto;
interface EntityProtoReduceData
interface EntityProtoReduceData {}
property excludeFromIndexes
excludeFromIndexes: ValueProto;
property name
name: string | number;
property value
value: ValueProto;
interface ExportEntitiesConfig
interface ExportEntitiesConfig extends Omit<google.datastore.admin.v1.IExportEntitiesRequest, 'projectId'> {}
property bucket
bucket?: | string | { name: string; };
property gaxOptions
gaxOptions?: CallOptions;
property kinds
kinds?: string[];
property namespaces
namespaces?: string[];
interface ImportEntitiesConfig
interface ImportEntitiesConfig extends Omit<google.datastore.admin.v1.IImportEntitiesRequest, 'projectId'> {}
property file
file?: | string | { bucket: { name: string; }; name: string; };
property gaxOptions
gaxOptions?: CallOptions;
property kinds
kinds?: string[];
property namespaces
namespaces?: string[];
interface KeyToLegacyUrlSafeCallback
interface KeyToLegacyUrlSafeCallback {}
call signature
(err?: Error | null, urlSafeKey?: string): void;
interface LongRunningCallback
interface LongRunningCallback {}
call signature
( err: ServiceError | null, operation?: Operation, apiResponse?: google.longrunning.IOperation): void;
interface TransactionOptions
interface TransactionOptions {}
Type Aliases
type Entity
type Entity = any;
type Fallback
type Fallback = boolean | 'rest' | 'proto';
type InsertCallback
type InsertCallback = CommitCallback;
type InsertResponse
type InsertResponse = CommitResponse;
type LongRunningResponse
type LongRunningResponse = [Operation, google.longrunning.IOperation];
type PathType
type PathType = string | number | entity.Int;
type UpdateCallback
type UpdateCallback = CommitCallback;
type UpdateResponse
type UpdateResponse = CommitResponse;
type UpsertCallback
type UpsertCallback = CommitCallback;
type UpsertResponse
type UpsertResponse = CommitResponse;
Package Files (10)
Dependencies (9)
Dev Dependencies (26)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@google-cloud/datastore
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@google-cloud/datastore)
- HTML<a href="https://www.jsdocs.io/package/@google-cloud/datastore"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10135 ms. - Missing or incorrect documentation? Open an issue for this package.